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 |
---|---|---|---|---|---|---|---|---|
1,638 |
That Today Kasam Solved List Question Number is dear by 0.5 inch by one Question Number is dear by 0.5 inch by one Question Number is dear by 0.5 inch by one character is Properly statement given two strings like 1000 number of but you can choose and 1m 3 sub string of these and replace single character by different characters representing subscribe of team In words find number of substance in 10 days from subscribe exactly one character for example the underlined substance in computer in competition intermediate from morning that we have to tell in this that there is a substance in which if we change the teams quarter then that means in that in this The highest one like this is AB here and this is this and this is also here and if we change BDO in b4m then the lowest of one gas will be reduced by becoming a brother actor like this area also alarm this among each other exactly. If we do this then we will change it, if we make this one then the channel will be submitted once again, this one, if we take change with this one too and if we change it with this one brought here, then now these will give us accepting, then this one. Even if you mix it with spices, there will be a balance system and this bag will be changed simultaneously because it will happen to me, so basically it tells us how many substrings you can make by changing one character of the team. So that at that time, I like his Aspirin, see here in AB and BV, that if I take this growled and change B in BV and change this one too, then this will also be done and will come from here to me. So this Abby is at the forefront of the FD so then just like that if we pick up this one and change it with this one piece so that will also be a ballet dancer and then if we look at the whole Justin Bieber Baby then in the wife already just so If we change this piece to B, then this will also become this and this event, all friends, so let's move on to the extension part, it is a very simple problem, it is like we have two strings N B, so one, if we do this If we celebrate all the substrings, then one will be at the forefront, second will be the baby and the third will be the lion, if we pick up a snack and then the police will generate all the submissions and check with it and then we will check that the actor will be changed exactly. After how many administrators are being created whose effect is string, then that should be my answer. See here, if we check the wife and pick it up, then if we check the PAN with the hot farmers, then it is not becoming exact but the character is changing and that is all about it. Settings are closed. Salary. If we check this one here with this one and this one also, now if we check with this one also, then a film is made with this one and one office person also, meaning with this one also. If you check then that is the best see if I change the spoon here then this will also go this and this will go bf now what is the string that I have so see all this forbidden similarly if we go to this whole sub screen biggest ne baby Hey, if we look at us too, if we replace this one like this, then it will also be a bar dancer. Now for me, this is the third case that we have the last option, I have one left and here see its subscribed skin. That is also made, now see, it is definitely there, so if I want to change it here, then it is equal to 20 and also give the answer to Real Madrid, he has to change it in exact one quarter and tell how many valid substances are being made. If we look at the mission question, there is so much constraint given in the question, then its problem is basically controlled, so if we ask it in Bringing off and why from others, then we will get its answer easily, so if you thank us for that then it will be a hobby of ₹ 10. if you thank us for that then it will be a hobby of ₹ 10. if you thank us for that then it will be a hobby of ₹ 10. And it will run on it easily, so my approach is that first of all we subscribe to one and then we generate all the substrings of one and after that we check that which one is the best for my tab skin and also. Exactly how many character differences are there, if we are making reference to the character then it will be sexual and we will make our control like see here this is I from here the first character of mine is this and wearing shoes substring gas is this and whatever. You can wear that too, now we will let you comeback to each other, this too is not a lotus among each other, so take a bigger one in your counter, but this will remain my balance, I will increase some function on your answer, then my next or is becoming mine. It is one of the best in the country and I also have the maximum, that is the wife. See, if you are surprised and the wife is sorry, if we look at the second substring here, there is another such satsang and we will check it in this application, then also it is similar to each other. A but if we look at it from the back then if we change it exactly by becoming B here by changing Chakli a tractor then it will also become this and I will give a big one to the counter and this of mine will become ballet dancer two. Similarly if I do neck tuition then my Jo The subject will be one, you can do this and it will also be of similarity, then this too is not related to each other, then here the counter will be one, you will mix the answers and parcel it out from one. Understand that when polling will be taken at the party level, it will be very easy. Before that let us stand with our friends. I again Vidmate app and Pintu Singh Luti wala will do us a favor and we will do a grate inside the entire skin from the roots approach. Subscribe First of all we will set it like this we will remove the submit after that we will generate teaser sub school and after that we will check among ourselves that I will take note of the pain and I will make a fool of you then surgical strike so that we can destroy every person of his. In such a situation, do subscribe to it and let me know that a bitter person like Intel will tell us that BK Jaitpur is the one who has surrendered before the enemy, he will invest in it and there is a regular account which will tell how much the character is. It depends on which channel the characters will be shown, then it will not be of any use to us and we will break the people from there and will come back to the team and then try to do all this on the internet, so we check ahead of that if the labs K and this is exactly that is subscribe so I have to do that not equal to t&c's equal to t&c's equal to t&c's portion greeting of see in this great animal means meaning Merasi village gets activated if gets heated up to the temperature then I have to break from here and move towards next this This is Edison, which will be my answer to the account. Hmm, his answer is, we will take the bigger one and both of them will please check both the points as well. After getting wet, everyone in the company is about a quarter of an inch from here. So let's see if the testicles are there. Please Shri Radhe, there have been a lot of requests here, the first request would be better, Meethi had written the size, thank you friends, it is giving the correct answer, how should I explain all the tests, let's see, there is a correct answer for all my updates, basically, I am saying that we Before here we are generating all its substance and Missai English We start this position and print is my substring we like we are the worst position then PK Dhawan himself means we start from the worst position you further till that if we have a trainer ABCD and we are still on, all the skins in front of that, we are generating it in this look, in this, all the settings are closed, we are checking whether the difference is the reference store of the mind, then we have to increase the encounter and then Take interest in the answer, Ginger, which is the difference, major difference, statistics, Switzerland, NTR, this is greater than one, should beg Gulf check, next ring is there, after submitting, see if you are giving the correct answer, hope you would have liked the video, thank you for watching.
|
Count Substrings That Differ by One Character
|
best-position-for-a-service-centre
|
Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly** one character.
For example, the underlined substrings in `"computer "` and `"computation "` only differ by the `'e'`/`'a'`, so this is a valid way.
Return _the number of substrings that satisfy the condition above._
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "aba ", t = "baba "
**Output:** 6
**Explanation:** The following are the pairs of substrings from s and t that differ by exactly 1 character:
( "aba ", "baba ")
( "aba ", "baba ")
( "aba ", "baba ")
( "aba ", "baba ")
( "aba ", "baba ")
( "aba ", "baba ")
The underlined portions are the substrings that are chosen from s and t.
**Example 2:**
**Input:** s = "ab ", t = "bb "
**Output:** 3
**Explanation:** The following are the pairs of substrings from s and t that differ by 1 character:
( "ab ", "bb ")
( "ab ", "bb ")
( "ab ", "bb ")
The underlined portions are the substrings that are chosen from s and t.
**Constraints:**
* `1 <= s.length, t.length <= 100`
* `s` and `t` consist of lowercase English letters only.
|
The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle.
|
Math,Geometry,Randomized
|
Hard
| null |
282 |
so hello everyone this is Deepak Joshi and we are back with uh another gfg problem that is expressions and AD operators so uh we are back with a very long interval of time because I was having um some health issues now I am fit and I'm back so we are going to solve this particular question of today's DFT problem that is expression add operators it is a hard level pushing and it is because I have taken more than two hours to uh solve it is very new for me uh and uh since from a very long time I have not coded it took me very long to solve it okay uh now if you have gone through the problem statement it has mentioned to us that we are going to get a string that is containing only uh integers and we are going to get a Target integer uh we have to manipulate the string in such a manner in such a fashion that uh we have we need to add positive symbol negative symbol and the multiplicative symbol to make all the elements sum or subtraction or multiplication to reach to the Target integer for example I have written two examples let us say I'll having uh this I'm having this example one comma two comma three are present in the string and the target integer which is given to us is six okay now uh what I am what I can do is in either I can do this okay this will make our condition 2 and 1 plus 2 plus 3 becomes six either we are or either we can do one multiply by two multiply by three it is also equal to six and hence in these two particular fashion I'm able to manipulate my string to reach to the Target integer so okay first of all uh I think all of you are aware of the presidency of The Operators like this and minus have the same precedence but uh if I talk about the positive in the multiplication then multiplication needs to be done first needs to be calculated first uh what do I mean by this let us take another example of it I have also written the example here that is 7 comma three comma two so okay and the target uh that is need to be reached is 13 now I'm going how I am going to approach it okay now uh the only way I can approach 13 is 7 plus 3 into 2 this is uh it okay it is going to get me 13 but there is another problem if I add 7 plus 3 first means I do something like this then it will become 10 multiplied by 2 that is 20 and that is not equal to 13 in any way but if I do 7 plus 3 multiplied by 2 then it will be 3 multiplied by 2 is 6 so 7 plus 6 and it will be 13 and it is equal to 13 and we have found out the way in which we can manipulate the string is to get 13 or the target integer now uh have you understand I understand what I'm going to but I am telling you that we need to focus on the precedence of The Operators also okay it's a very um but I'm going to make it simpler for you uh in my way as you know as all of you know that I am going to code along with explaining the problem so now we have to return a string teacher I am going to make the answer string that is answer okay then let us take a temporary string take it uh string that will be the path basically okay if I think many of you have done the DFS problems okay DFS problems um of the graphs uh so this temp variable will contain all the parts uh from which we are going to trace the string so you can increase the given string and we are going to take a previous uh one which is going to carry the previous uh numbers okay so that will be in the form of long pref that is initially for now is zero now we are going to call our DFS and we are going to return our answer now what we need in the previous let us make it private okay foreign as I'm going to mean my function in VFS I need many of the things like I need the index from where to start the DFX BF is gonna uh many of you have done VFS problem as I said uh if you have the random DFS problem then you need to know uh from where to start so I'm going uh I am having this index integer then we are going to have the string is as it is uh which is given to us this one I'm going to make it small okay so small then next uh I will have my target integer that I need a need to reach then I will be getting my uh I want it to be like this okay then uh I'll be getting my answer Victor but it should be called by a reference because I need to store all the reflections of my answer in the uh add operator function also so that's why I'm making it call by reference okay now uh next uh I'll be getting my temporary variable temporary string and my long press okay now there is uh some another thing that I need to store is that is uh the whole my calculation if I have operated symbol multiplication symbol and calculated by result then I need to store it and compare it whether it is equal to our Target or not so I'm going to store uh that particular thing in our result for now for long result uh is also what I need uh okay now this is fine I hope it is good now checking foreign answer then I need to send this temporary string then I'm going to send a temporary string then what I need to send is our previous value okay then previous value and I need to send my result so for the result purpose I am going to um I'm not going to make any variable because it is comparatively not used by the our ad operator function because there is no need to use our long result variable in the ACT operators I am simply going to calculate all my results and compare it whether it is equal to Target if it is equal to Target and I am going to store that particular path into my answer variable and calling the recursion again and again so initially I'm not making any type of variable to call result I am simply passing zero okay initially it is zero okay the sum is zero okay here my ADD operator function is completed and the answer will bring it to the add operator function and I'm going to return the answer from here only okay now yeah I think uh now we are we have to write the base case first second so the base case is what's the base case and then he gives this if you remember that our index becomes equal to the size of the string that is s dot size if it is equal now I have to add a new case here that it is mandatory if becomes equal to sort of size so it will be our base case and I'm checking with this key if I am at the last index and my result is equals to Target then simply push it as return in both the cases if it is equal or not written so okay this I have done now okay now I am going to make a decode uh let me explain uh why I'm going I am making a Space type of string um it took me more than 15 minutes to resolve this particular problem that I have to make in another string is C to um to manipulate my code uh because I have to pass away I have to pass this same thing whenever I was passing the system okay uh like I have to add a particular number with the stint because I'm getting all the uh all the increases as I know all the teachers are present in our string is so what I'm particularly doing is um I'm doing is I'm adding my you are going to get it in the upcoming code uh which I'm going to write here is now I'm making a long current which will which is going to have a look at the current integer which I'm getting okay now I'm starting a for Loop to trace or to um through my string which is not going to start from I uh it is going to start from into J is equals to index naming it as I okay uh and J is less than equal to x dot size my initials string dot size okay J plus okay I hope it is clear to you uh for now okay now in this particular for Loop what I am going to do is I'm going to check because here it is mentioned that of I H is equals to zero if this is the particular case that my present character is a zero then I'm what I'm going to do is I'm going to break okay now if it is not a zero then simply I am going to store this particular index into my string okay what is this s of I this is our string which is I'm getting from my mean add operators function I'm simply adding it to my history okay as I mentioned earlier that uh it is containing uh what it is containing a number okay now as I have mentioned my current I have created my current I am going to store uh numbers in the current and what is the formula for calculating numbers from the uh calculating the whole complete number from given set of integer is current multiplied betting plus uh as s of um and remember one thing also that it is not in the particular in the form of what in the form of integer so I need to convert it into integer first I'm sorry it should be okay this so how I am going to convert it into an integer minus 0 simple minus character 0 this is it uh for it to convert to get converted into the integer this is particularly let's say eight so current is 0 for now to eight the next time current will be 8 18 to 10 8 Peak the next number will be latest C7 so 87 will be our current so in this way it is going to create the particular number or from the given set of digits in the S of I okay now if all index is zero okay means it is the first particular case am I and then I am going to call my DFS function with I plus 1 that is our index plus one it's okay and all rest of things same as taking Target and my uh next thing uh from Target is answer okay then it should be answer and the next thing from the target is that is uh thing so in thing I'm going to add my thing that is empty for now because the index is equals to zero and I'm going to add 10 with my string that I have mentioned here because it is going to store the particular s of I which I have got from uh from the original string so I'm going to add St in this particular case I have mentioned earlier that um I was writing s of I uh s of file in the um in the integer form the system and previously I was writing integer here so it was creating an error okay uh then I got to know that I can use to string button but I decided to use a separate string to store this thing second then Plus also here okay now here index plus one is correct okay Target is again correct answer is correct ten plus now what you need to know here is we are going to add a plus single between them okay so it should be plus here and like this okay I have added a plus symbol because it is for the plus and our current will be current but our result will be result plus current okay this is the case the result I am getting from this uh from here the ydfs and I'm adding simply current into it okay now for the next line I'm going to again edit the DFS volume that is index plus one is again current Target is a again I have to manage for the third case that is our okay now uh here I need to what I need to do is in this particular scenario I have to manage this previous I've not written anything about this previous now this is our case that I am multiplying my previous with the current okay why I have done this because multiplication is done in this fashion only uh that we need to multiply the previous thing uh previous thing with the current thing that's why I am multiplying and the result will be because whole previous will be removed uh as I'm multiplying previous I'm not writing it properly as I'm multiplying previous with the current this is my current scenario let me uh corrected what I'm doing here is for the result mother part this thing for this result fall apart second I'm doing result minus previous remove all the previous from the result and simply add previous into current into the result section and call the DFS second because this is our complete code I have added too many blank spaces here let me remove all the spaces and let me explain you the DFS calls okay if this calls passes to the DFS function then what will happen the base case now you will be getting the much more better understanding of the base case that is um if I have called the uh BFS if index becomes equal to size simply what you check is whether the result is equals to Target if it is equals to Target simply push our path into the answer and from where we are getting this path okay now again uh it is mentioning to us that there is J so let's say he with it is correct or not again it is mentioning it should not be J it should be index second and again it is mentioning that SP plus I is nothing okay s t plus I is nothing but it should be J okay now I need to check whether I have done anything wrong again just mentioning that I was not declared in this range again I have uh I've done a lot of mistake there it should be G again it's okay now let us say let's see uh if it's mentioning to us that has not been declared when I have written stem it is not stiff it is string okay and okay it is telling us that uh no matching function calls for answer dot pushback then why it is mentioning this that answer dot pushback is not there I have also pushed back 10th long end point function let us check our I have created index Target Victor string answers uh 10th long previous long result then I have called my index is equal to size resulted equals to Target then answer dot pushback okay then second EMP same spelling and then I have returned SD then my test management are not created anything let me check zero I started and so then previous zero that is correct here then long eight long okay so now I have done I will actually have I find out the mistake it should be uh it should be J plus 1 now because at that particular instance where I have calculated my uh integer where I have founded out my integer and uh so at that particular place I have to uh from that particular page I have to carry on my calculation now or all my VFS calls so I have removed that index to J okay now what I'm going to check is I'm going to check why this thing is showing error to me is all correct okay it is not integer now it is correct it is submitted and hope it should get submitted okay so it's fine let's see uh the next challenge um and it was creating an issue for me and it was returning in empty also take care of yourself thank you
|
Expression Add Operators
|
expression-add-operators
|
Given a string `num` that contains only digits and an integer `target`, return _**all possibilities** to insert the binary operators_ `'+'`_,_ `'-'`_, and/or_ `'*'` _between the digits of_ `num` _so that the resultant expression evaluates to the_ `target` _value_.
Note that operands in the returned expressions **should not** contain leading zeros.
**Example 1:**
**Input:** num = "123 ", target = 6
**Output:** \[ "1\*2\*3 ", "1+2+3 "\]
**Explanation:** Both "1\*2\*3 " and "1+2+3 " evaluate to 6.
**Example 2:**
**Input:** num = "232 ", target = 8
**Output:** \[ "2\*3+2 ", "2+3\*2 "\]
**Explanation:** Both "2\*3+2 " and "2+3\*2 " evaluate to 8.
**Example 3:**
**Input:** num = "3456237490 ", target = 9191
**Output:** \[\]
**Explanation:** There are no expressions that can be created from "3456237490 " to evaluate to 9191.
**Constraints:**
* `1 <= num.length <= 10`
* `num` consists of only digits.
* `-231 <= target <= 231 - 1`
|
Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators.
1 + 2 = 3
1 + 2 - 4 --> 3 - 4 --> -1
1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!)
1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.
|
Math,String,Backtracking
|
Hard
|
150,224,227,241,494
|
127 |
given two words begin word and end word and the dictionary's word list find the length of shortest transformation sequence from begin word to end word such that only one letter can be changed at a time and each transformed word must exist in the word list note return 0 if there is no such transformation sequence all words have the same length all words contain only lowercase alphabetic characters you may assume no duplicates in the word list you may assume begin word and n-word are you may assume begin word and n-word are you may assume begin word and n-word are non-empty and are not the same non-empty and are not the same non-empty and are not the same in an example to this problem we are given begin word of hit and word of cog and the following word list actually this problem can be represented as a graph we can turn the word list into the following graph here the words become the nodes of the graph and we link two words if they can be transformed into each other with one letter change so hit is linked to hot this link to dot and lot and so on now it is quite clear that we can get from our starting word hit to the ending word cog and there are multiple ways of doing it we could go from hit to hot to dot to dog than to cog or we could take a more convoluted way and instead of going straight from hit to cog we could go back at some point or cycle through for example hot dot lot back to hot however the problem specifically asks for the minimum number of steps from hit to cog so we want to avoid the more convoluted solutions and just go straight from hit to go cog in the minimum number of steps and the way we can do this is with breadth first search in a breadth first search we traverse the graph from the starting point and as we go along the notes of the graph we mark the notes we have visited already so that we do not visit them again there are several parts to this problem so we want to do the breadth first search then we want to keep track of the distance from the first word given a word we are going to need to be able to find the words that it is connected that we haven't visited yet so finding links i will first code out how to find the connecting words and then i will do the breadth first search so i will have here const find connections is equal to word set and i'm using const and arrow notation the way i'm gonna be finding the linking words is through brute force so say i start with hit i will first replace the first letter with all possible letters in the alphabet then i will do the same thing to the second letter and then finally to the third and each time i will be checking whether or not the new word that i created is contained in my word set so in the problem we are given word list but because we constantly going to have to do lookups in the word list and lookups in an array have linear time complexity i want to use a data structure that will have constant lookup time and in javascript this data structure to do that is a set so i will have const word set is equal to new set word list and that's the variable i will be using in my find connections function first of all i will declare my results array as an empty array and at the end i will return results then i want to cycle through each letter of the word and i'll do it with the for loop i equal to zero if i listen word dot length i plus and after that i want to cycle through every single letter in the alphabet then 26. i'm able to do it with using ascii characters and i will just need to know um the ascii character of letter a and it's gonna be can be found by saying string a car code at zeros and to make my life easier i will define the first half of the word that remains the same and the second half so it will be word.substring so it will be word.substring so it will be word.substring 0 to i and then cons the last half is going to be word that substring i plus one okay and then the next word will be formed by concatenating the first half plus string from car code and i have here a s key plus j and then i will concatenate with the last half of the word okay and now if word set that has next word i will put it into my results array and that's it for the find connections function now i will move on to my breadth first search so breadth first search is typically carried out with a queue and it's initialized with the our starting word then while i want to keep looping through the cue while it's not empty so the first thing we do um in breadth first search we say const word is equal to q dot shift so the function shift will pop off the first element of the array and then we want to find all the connecting words to our given word so cons connections is equal to find connections word and word set okay after that we want to look through the connections and process them we want to put them into the queue and delete them from our word set to mark that we have already discovered that node so the word set is just going to contain words we have not discovered yet four let i equal to zero i less than connections.length less than connections.length less than connections.length i plus and here i will have um cons next word is equal to connections i'm gonna push down to the queue and then i'm gonna delete from the set so this will explore the graph but what we really care about is when the next word is equal to the end word at this point we want to return the distance from the initial word to the end word while this is an example of a classic breadth first search doesn't typically keep track of the distance we have to add something extra i will define variable distance to keep track of the distance and if we don't find the end word with our breadth first search i'm going to return 0. now if i were to increment the distance every time i'm writing the while loop it will count every single node in the graph which is not what we want going to my graph example here i have color-coded graph example here i have color-coded graph example here i have color-coded each words based on their distance from the word hit so the strategy for knowing when to increment the distance variable will be to first go through all the words at the level and then increment the distance the way to do that we would need to define let n equal to q dot length and also distance actually needs to be let as well because we're changing the variable and then i want to walk through all the nodes at the next level before going back through the outer while loop again and incrementing the distance and in this case when we do find our end word it will be located at distance plus one because we'll still be yeah because we will still be at the level before our end word so pretty much when we hit dog the word dog we're at distance four this is the moment when we will find cog and that's why we have to increment distance by one and so i'm going to submit this and it works now for the space and time complexity so the find connections it loops through each letter of the word so say l is the length of our words then the time complexity for find connection will be l times 26 because we have another loop that loops l times and the inner loop loops 26 times now for the ladder length let's say n is the number of words in word list then the time complexity is going to be n times l times 26 because the q shift operation should run linear push and delete should also be linear then we're just finding our connections for every single node that we visit and at most we visit endnote so time complexity will be n times l times 26 and as far as space complexity is gonna go we are creating a set which will have linear space complexity and then we have a queue which also is at most going to have n elements in it and the find connections doesn't really create anything extra i guess the results array is at most is going to be also n so overall the space complexity will be linear it's going to run in big o n and the time complexity is going to run in o n times l okay that's it thanks for watching and i will do i will be doing more of these in the future
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
884 |
Hello friends welcome to a new video in this video I'm going to discuss another Lead Core problem and this problem is based on string okay so the question is uncommon words from two sentences okay so a sentence is a string of single space separate words where each word consists only of lowercase letters okay so now you have to find out all the uncommon words right so how you can tell that what is uncommon okay so here what is uncommon if it appears exactly once in one of the sentences and does not appear in other sentences means the occurrency of the particular word is only once right okay so given two sentences S1 and is to return a list of all the uncommon words you may return the answer in any order means the order is not a big problem for us but you have to return all the uncommon words okay and uncommon words needs that particular award is appears only once okay so now let's see the first example as you can see this sweet and this Sava is appears only once okay and other words like this apple is appears two times right that's why your answer is sweet and sour okay you can also return shower sweet because the water is not a big problem for us but you have to return all the words may all the uncommon words right in the second example apple is appears two times but bananas appears only one time right let's show you answer is banana okay I think this question is clear too let's see how we can solve this problem okay we can solve this product using hash map why so because in the key part we can store all the words okay and in the value part we can store the number of the occurrences of that particular word right so that's true we can use hash map but here have another problem while because we only want the words like this word this apple word okay we don't want any space right so we can use split method okay means we can create a steam type array okay str1 okay then H1 those split okay so using this speed method we can store only the words okay means this word these apple is sweet only this words we can store in our array okay this is still one only store the words okay without any spaces okay I think it's clear so then in this in the I will do the same thing first string two also okay str2 equals to S2 to split okay so now I will take the hash map okay string comma integer hm equals to Nu has map okay so now I'll just Traverse our arrays okay so I'll use for each Loop thing is a spring is str1 okay then hm don't put this put method is used to add Keys values in our hash map okay then what is your key your keys is okay K or default e comma your default value okay then plus one okay this is HTM dot get your default method will give you the value of that particular key okay if they don't have any value then this method will give you this default value okay and our default value is 0 and at the end we just add plus 1 with that particular value okay I think it's clear right so now for str2 also okay coffee and then paste so okay spr is tr2 okay so now uh now we need to travel our hash map okay but before that we need a count variable why so because you need to return an array okay string type array you have to return but to declare an array you have to mention the size okay but we don't know what will be our size of our array right so that's why I use this count variable okay and now I'll just Traverse our hash map okay entry then e comma 87 Henry said okay if e dot get value is equals to 1 means what this means is occurrences is once right because in the value part we store the number of the occurrences right so you know we just increment this count variable okay at the end we just um paint we just declared our string type array that array we need to return okay new string a count okay and then add that value in k equals to 0 and then k equals to e dot get key okay and then K plus and we just return our array okay so now let's run this code Yeah so basically what's going on in this code let's see okay let's take the first example this first example these two sentences given to you right so I just uh convert these sentences into a string type adding okay so basically what we have in our fasting this Apple piece sweet okay this is uh this is our in zero index position this is our in one index position this is another two inches three index position okay so now the same thing is uh happening for our next string also this apple is sour okay so now next I just declare has my winter hashmap I just store all the words and in the valuable we just store the number of the occurrency of the particular word okay so now what we have in our asthma like for this we have one time right for is we have one time okay Apple we have only one time right and show it we have only one time right but after these four Loop we what we have we now has map now our this is appears two times right mean this and this okay now total appears this word is two times okay there is two times also okay apple is 2 times pulse 2 it is still one time okay and another his appears also one time okay so now I just get this value part means this value part is to these two this one we just check that value part okay so e dot get value will give you the values okay not the key so basically we just check equals to 1 okay but for this sweet equals to 1 and this hour is equals to 1 right well for that cases this count will increment by one okay so now our count value is what two okay do it now okay basically after that we just take an array why so because we need to return and add it okay string type Arrow we need to return but to declare an array we have to mention the size right so I take this count variable okay I think it's clear at the end I just again remember our hash map okay and I just take this condition okay and at the end I just add all the values in our array okay and let's just return attached our array I think it's clear okay if you have any question definition ask me the comment section okay so now let's submit this code yeah that's all for this video I hope this video is helpful for you and you can give me any type of suggestions that I can improve yeah so thanks for watching see you in the next video
|
Uncommon Words from Two Sentences
|
k-similar-strings
|
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters.
A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence.
Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**.
**Example 1:**
**Input:** s1 = "this apple is sweet", s2 = "this apple is sour"
**Output:** \["sweet","sour"\]
**Example 2:**
**Input:** s1 = "apple apple", s2 = "banana"
**Output:** \["banana"\]
**Constraints:**
* `1 <= s1.length, s2.length <= 200`
* `s1` and `s2` consist of lowercase English letters and spaces.
* `s1` and `s2` do not have leading or trailing spaces.
* All the words in `s1` and `s2` are separated by a single space.
| null |
String,Breadth-First Search
|
Hard
|
770
|
344 |
Turn the flash light Vaikuntha Questions and here the question which attends us is number 34 which is reverse bank meaning simple sa meaning dimple key explain that you have to reverse the screen here easy level difficulty question is very high for song here Depend vote affair is question, you have said here that I give you this pack in inputstream goddess address character, so you have question function here, this is bachelor from here and you have to create a function here which is using a spring. This is the seventh question here in this effect. If you explain a little here that CR is actually given to you here, then you are given Shalini Devi here, meaning you are given here, if I write COD, then you are given this spring, not Devi, you are given here. Deep given they are a character face and what you have here is something like this the input you have here is when character here okay and you have to reverse the screen here how does that work So if you here thing that if you here toe enter which one to put that from 2.1 what is you here toe enter which one to put that from 2.1 what is you here toe enter which one to put that from 2.1 what is this if you from here to here carrier simple you can lock it here then if you here a poor people chilli and Apart from one point, here at the beginning, take one point, you are here at the end, here, what is the meaning of doing reverse and animals, if the makers, you will see it by the name of the code, then you have to reverse the screen, meaning from Eid and you will get this. You have to write like here you have written hello here spring these people from here is the first character he should come last like here ford tractor you here with add second character here you add second character here settings character third title here A little bit of cricket world tractor here is the full credit characters of character they post here then spring here if you did Bigg Boss then one way here we can do this here we know that this is coming up near one which That we have here your opinion character add in Ayurveda so you can work here that you can take a point here Oye give the western modern point you can take the last see and you can hand over these two in the bus Dream means you have replaced this character with yours Subscribe It is something like this and after this you have to remind that this is the first point here, for that you have put a plus on one point position and This one, you have to decrement the point here, do it here - - so that you - - so that you - - so that you subscribe to Next9, then see it here, it is something like this, if you comment here after that, subscribe yes, comment here. While doing this, if it is not your department that after that if you talk to him then this will go on the wall and he will come back here, then you do not have to do this, then you just have to run the job till the people are there, the last point is that of the encounter. It is small means either it should not be equal then something like this should happen here, so in this case, till here you mean till half of your address, you have to run it from your point here, then the accused young man can see whose name it is very simple. It is very simple, you should not do anything here, let me tell you that you will get two points here, one point here, where is your specific artist collected from, here is the giver question, one on the venues, one here, and to enter. End re-enter, how far will the encounter go, re-enter, how far will the encounter go, re-enter, how far will the encounter go, you will go till the length of this address which is your address, so we can find the length of the address, but your patience starts from zero, then when the class tractor will be on - one, you will have to class tractor will be on - one, you will have to class tractor will be on - one, you will have to go till then. Unless your which start it's to be small cotton should be to end means if here acting took spin when I show you one thing here please my you spring if it was COD there for even after there Okay, so your tight, you will come here and you will come here, so start this, which is your boys at that time, job, see here, like the team directly, your point here you subscribe, and place also. If you replace the subscribe in this way, then start your controller and auditor are at the same point, so it should not be said that this point has been appointed to subscribe channel, here in the channel subscribe, then friends that it will come here. Here I can come and now I had belted my infinite here in time so if I can cheat the time here in life then this here a little here the contacts will be curved that brinjal and concept we here we all now we all have Accompanying effect time they find which country to table using so here a well from the darkness in the name of the tank here who will take my most starting now I could be here index here is the loot portion so I picked up my possible purse character I have inserted it in the camp, now I have put it in the point which is there to make a make over bridge, there is a patwa available in the enter after dipping the explain, now I have to put it inside and now I have put it filled with lust which is my pride here. Adding character is big in tempo here, just this little bit is effective here, after that there is strange voice typing, after that you have to press start here and for mix family and you have to do end here - - then that's all. If you - - then that's all. If you - - then that's all. If you submit your form here then you will be asked that I will run you here and see or click here, I want this training, here you have an option to submit and show it, now see this see here Submit is a verification, was turning point to point online submission. Now here, file the land of your questions here, do not use that, we will also be able to use follow here, you can definitely say, Sir, if you want, you can here. But you can also use flowers or semi will remain, we do n't tell you anything here, you are running it once even here in Great Ballia, it has to be run by the hands of list in the name of camps, it was explained to you that you and your entire length Till half of that, you will have to go to the list here, this oil ad is right here, exactly the time, you have to do here after this, whatever your CM Yogi, all the three condition scores have to be put here, what did you do here in the poor. In the name of tenth and in it you have put this first character of yours, before this where is the custom, where is it cheap, lastly, here is the giver question platform, so the behavior of the person who appointed you here, I had come here, must have started deteriorating. Okay, after that, now my cup of sugar which I have taken, I put a temple in the starting lane, then in the starting items, I changed the ending one, then to sim1, read your value in the end, in the value end of the year, good means it is lying in Scotland and minus one. But you have to select here if I show you here how I have here in which you were directly which now which is here in here you have this position here and here this position and always this position that this position is fine if you have this This position cannot be at the position, okay, after that, where will you come here, then you will have to do - I here, experiment method, then you will have to do - I here, experiment method, then you will have to do - I here, experiment method, your initial will be only here, so you will have zero only here, okay, there will be opposition only here. Will go - You will hero here, that's the Will go - You will hero here, that's the Will go - You will hero here, that's the end question here that I will you will be on here, then here next this will come up, after that look at the horses here, then you will be - off here, horses here, then you will be - off here, horses here, then you will be - off here, that is the length. Hey, here you are good benefit economic matters, if it is starting from zero then you should overestimate it here - the then you should overestimate it here - the then you should overestimate it here - the world has broken down here so much in 2012, so whatever end you do, it is the space here, we are here - I have felt. space here, we are here - I have felt. space here, we are here - I have felt. Okay so I hope you must want that we are here - mind why we are here so - I care we are here - mind why we are here so - I care we are here - mind why we are here so - I care we are here okay after that you have to go here in add length key and minus one and minor come you have to go here benefit you tempered Glass October is such a simple task that you can run something on the graph and see this skin of absolutely no opinion, it is completely traditional here, submit it and see, there is so much time complexity that here, I have seen the graph and time here. But don't be stupid that you have run this fold, there is only one person from there, it has taken time, free millisecond faster than only 30.20 free millisecond faster than only 30.20 free millisecond faster than only 30.20 online submission, so actually this card of yours is fast because in this case, we are ahead of 99.9 2% people. But in this case, we are ahead of 99.9 2% people. But in this case, we are ahead of 99.9 2% people. But from here, 31.60 seconds means it took 13 minutes, it took from here, 31.60 seconds means it took 13 minutes, it took from here, 31.60 seconds means it took 13 minutes, it took one criminal, okay, so you knew that there was a pastor there, those people, there is a little bit of controversy over this, so why have you come to this, that is what happened, this is the last edition, okay If you have then please comment and turn on the complete list.
|
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
|
215 |
question 215 ks largest element in an array from bitcoin let's jump to the question given an integer array nodes and integer k you return the case largest element so let's see what this question is asking us so the question is saying an integer array is given and integer k is given and we are supposed to return the ks largest element in the array so as you see in the first example this is the array is given to us and we are looking for the second largest element the first largest element is six here and the second largest element is five so this is the number that we are going to return and for the second example we are looking for the fourth largest element as you see here this is the first one this is the second one still it's the same so it's gonna be the third one and this is the fourth largest element in this area that we are going to return the like key point here is the array that are given to us they are not sorted so we cannot just say okay if we are looking for the first i the first largest element we're gonna return uh the first one from the end this is not the case the arrays are not sorted so let's jump to the solution and see how we can solve this problem i have three different solutions here that i'm going to explain this is the first one this is the second one and this is the third one so let's go through the first one first so for the first one we are going to use heap and we are using to uh we are going to use heap properties the modulus we are going to use here is a hip cue which is very easy to use so what we are going to do we are going to if this is the example of the array that we have and we are looking for the second largest element we are going to iterate over every single item and we are going to add it to the heap but what we are going to do we are going to add the negative of that number to the heap the reason is uh by default heap function is um sorting the items um ascendingly and uh if as we are looking for the largest element it's gonna be at the end of the heap so if we do it descendingly by using negative it's gonna be kind of easier and maybe it takes like less time for like special cases like long arrays right and what we are going to do after we are going uh after the for loop that we have added all the values in this array to the heap as you see we first add minus three then two and then one and then five is added and six and four right so and we are looking for the second largest element right so what is going to do is uh we are going to use a while loop or it can be a for loop until we get the ks element and we are going to um multiply that by a negative because we change the nature of the number at the for loop here so we multiply by negative and we are going to return ks element which is going to be for this one is going to be 5 and it's going to be -5 going to be 5 and it's going to be -5 going to be 5 and it's going to be -5 it's going to be multiplied by minus it's going to be 5 and this is the second largest element in this area and another solution that we can use it's a like simple one that we can use uh sort we sort the array first and then we get the uh from the sorted array we get the minus k um in index from this array and the reason that we're using minus because the array when it's sorted is going to be uh ascendingly and we're going to get from the end of the array right and the time complexity for these the first one is going to be um n log n for second first one and second one both is going to be n log n and the space complexity for the first one is going to be o n because we are storing this uh array in the heap and for the second one because we are doing it in place the space complexity is going to be all uh constant it's going to be one and another solution is we can use the like a heap module it comes with a function that is called enlarges that it will return the n largest element of the array and as you see we um like put the n that like uh in this case is gonna be like for example two and we're going to put the array in this case it's going to be num we're gonna put it in here and it's going to lose hand the largest one which we can use that too and the time complexity for this one is slightly better it's n log k and um that's about it thank you so much
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
575 |
welcome to march's leeco challenge today's problem is distribute candies alice has n candies where the ice candy is of type candy type i alice noticed she started to gain weight so she visited doctor the doctor advised alice to eat only and divide by two of the candies she has so half and n is always easier even alice likes her candies very much and she wants to eat the maximum number of different types of candies while also following the doctor's advice given the energy array candy type of length n return the maximum number of different types of candy alice can eat so this is a very simple problem we can see all the different types that you can eat now we know that there is going to be a length of n here right and basically what are the two uh upper bounds here like she can only eat up to half of these candies on top of that she can only eat the maximum bound of different types of candies which would be like a set of the candy type right so this would be something like length of the set so there's so many different types of unique candies and there's going to be half of the candies that we have right now so really all we need to do is return the minimum between these two this should be three and that works let's go and submit that yeah and that works the reason for this is well basically there's only so many unique types of candies we can eat and we can eat up to about half of these candies and basically one of these is going to be like setting a bound of how many we could possibly eat it's either going to be like we might be able to eat more than how many numbers we have but we're going to be bound by these unique numbers or we're only going to be able to eat half of these candies but we're going to be bound um by how many unique types we can eat right so it's you know the minimum between these two and you can probably even make it a one-liner by just putting in like this one-liner by just putting in like this one-liner by just putting in like this and put that here if you like and that would probably work as well yep so pretty simple problem hopefully that made sense thanks for watching my channel and remember do not trust me i know nothing
|
Distribute Candies
|
distribute-candies
|
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.
Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_.
**Example 1:**
**Input:** candyType = \[1,1,2,2,3,3\]
**Output:** 3
**Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
**Example 2:**
**Input:** candyType = \[1,1,2,3\]
**Output:** 2
**Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types.
**Example 3:**
**Input:** candyType = \[6,6,6,6\]
**Output:** 1
**Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
**Constraints:**
* `n == candyType.length`
* `2 <= n <= 104`
* `n` is even.
* `-105 <= candyType[i] <= 105`
|
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
|
Array,Hash Table
|
Easy
| null |
204 |
all right so this leap code question is called count primes it says count the number of prime numbers less than a non-negative number n so their example non-negative number n so their example non-negative number n so their example is the input of 10 and the output of 4 because there are 4 prime numbers less than 10 they are 2 3 5 & 7 than 10 they are 2 3 5 & 7 than 10 they are 2 3 5 & 7 all right so we'll solve this problem using something called the sieve of eratosthenes it sounds pretty complicated but it's really not just think of it this way usually when you try to determine if a number is a prime number you do it by dividing so let's say the number 7 is that a prime u divided by 2 is it evenly divisible by that no is it evenly divisible by 3 no four no five so at the end you decide that it's a prime number because it's not evenly divisible by anything the sieve of eratosthenes goes the opposite route what it does is it eliminates the multiples of a number and then it goes on to the next number and eliminates those and at the very end all you have to do is count up how many numbers are left I'll show you what I mean so we'll start with the number two we need to eliminate all multiples of two what's a multiple of 2 4 6 8 10 12 14 16 18 and 20 those are definitely not Prime's because they're a multiple of something so those are gone right off the bat now let's move to the next number the number 3 we can eliminate all of its multiples so what's a multiple of 3 6 which is already eliminated 9 12 which is also already eliminated 15 and 18 another number that's already eliminated so now look at what's left what we have left are by definition numbers that are not multiples of something so these are the prime numbers so now all we have to do is count how many numbers are remaining we don't start with the number one because that's not a prime but here is one two three four five six seven and eight alright so what we've done already is great but let's make it a little more efficient so what we have here are the numbers that have been eliminated after I've checked the multiples of two and three I have not checked the multiples of four yet but we actually don't have to check the multiples of four how do we know that because the number four has already been eliminated when I checked the multiples of two so how can we prove that if a number has already been eliminated we don't have to check its multiples because they have already been eliminated well let's just think about what a multiple is just made up of other numbers so the number four is two times two that's why it was eliminated when we checked the multiples of two what's another multiple of four eight all eight is 2 times 2 so this was also eliminated when we checked the number two let's go to the next multiple of 4 12 this is 2 times 3 so this one would also have been eliminated when we checked the multiples of 2 it also would have been eliminated when we checked the multiples of 3 but that's not relevant right now let's just do one more check the number 16 what's that it's 2 times 2 so again with the number 16 it's made up of at least one number 2 so it would have been eliminated when we check the multiples of 2 so again I'll repeat it if we come across a number that has already been eliminated like the number four we do not have to check any of its multiples because they have already been eliminated by something that came before the eliminated number you know what let's just be excessive let's go with the number six to prove this out once and for all the number six has already been eliminated so we don't have to check any of its multiples but let's do it anyway six is made up of three and two so this would have been eliminated either with the check of the multiples of two or the multiples of three let's go to another multiple of six twelve this two times three so that would have been eliminated with either of those checks finally 18 is 2 times 3 so again that would have been eliminated by either the check of 2 or 3 all right so how do we actually use the sieve of eratosthenes to figure out an implementation for our problem so remember the question is asking how many prime numbers are less than our n in this case we'll say that n is 10 so how many prime numbers are there that are less than 10 so what we'll do is we'll create an array of n Troost and it's 10 so we need an array of 10 Troost true meaning it's true that this is a prime number so 1 2 3 4 5 6 7 8 9 10 so we start with the assumption that everything is a prime number now what we do is we start with the number 2 and we flip all of its multiples to false so 4 is now false 6 is now false an eight is now false then we move to the next number the number three let's flip all of its multiples to false six is a multiple three that's already false so we just go to its next multiple which is the number nine and make that false now we'll just go to the next number the number four as we can see the number four is already false so we don't actually have to check any of its multiples based on what we proved before any multiples of a number that has already been eliminated don't need to be checked because they have already been eliminated so now the final step is we just need to count the number of truths that are left remember that the number is zero and one are not prime so again we start at the number two so what do we have one two three four prime numbers all right so let's code this out what lead code has given us is the function called count Prime's which accepts n so what we have to do remember is find how many prime numbers are less than n so first thing we're gonna do is create our array so let nums equals an empty array remember this is the array that we're going to initially set all values to true and then one by one change the non Prime's to false and then at the end count the number of primes speaking of that we need a variable to keep track of the count of Prime's so let prime count and will instantiate that to zero so far this is where we are just an empty array so now we're gonna have to fill this array with n number of truths so for what I equal zero I is less than n I plus we're going to set every value in it to true that'll look like this ten trips and just so we know what number were on I'll put the index below it messy handwriting okay so now we're going to start at the number two and eliminate all of its multiples so for let I equal two and we'll stop when I times I is no longer less than N and we'll quickly prove that let's say we start at the number two so I is to what's two times two four that would only bring us to this number we need to get to the number nine so let's get rid of that all right so now I is three what's 3 times three is the number nine which is the last number in our array so we can stop here because if we try to go one further what's 4 times 4 is 16 we'd be past the last element in our array all right I just noticed that I forgot the second I will finish off this for loop ok so right now we are here all right the first thing we have to do is we have to check to see if the number we're on has already been turned to false because remember if it has we can just skip that number because all of the multiples of any element that's already false are also false all right so now let's get all the multiples of the number we're on which is the number 2 so 4 let J equal 2 we'll stop when J times I is no longer less than n same reason as before we'll do J plus so just to make it clear the outer for loop is going to go over the elements in the array so it's going to start out as 2 then it's going to become 3 then it's going to become 4 this inner for loop is going to get the multiples of that element so this inner for loop is getting all the multiples of 2 and then once the outer for loop is at 3 the inner for loop is going to get all the multiples of 3 and remember what we have to do now is set all of the multiples of the number we're on to false all right so that would complete that so since we started at the number two let's just show what has happened so far it's changed this to false and this to false then the outer for loop went to the number three and then the inner for loop changed all of its multiples to false so the number six which is already false and the number nine which is now false so now all we have to do is we have to look at this array and count any element that's still true starting at the number two so how many elements are still true meaning still prime we have one two three and four that would look like this four let I equal to I is less than n I plus so we'll just check every number in the array starting at two so if nums I equals true so if it's still a prime then we'll just add that to the prime count total so at this point prime count is four so what's left to do all we have to do is return prime count all right let's see how we did looks good let's submit it all right our answer was accepted so our solution was faster than about 85% of solution was faster than about 85% of solution was faster than about 85% of JavaScript submissions as usual decode and written explanation or link down below if you liked the video give it a like and subscribe to the channel see you next time
|
Count Primes
|
count-primes
|
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106`
|
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
|
Array,Math,Enumeration,Number Theory
|
Medium
|
263,264,279
|
1,038 |
hello everyone so this question is binary search tree to a grid or some tree so the question is the census 538 so if you didn't watch the 538 video just please go to watch it and i'm going to just talk really quick on this video so you have a global sum and the and this value is going to update for every single element uh for every single tree node basically so i'm going to traverse the root so i need a helper function and i need a node root all right so i'm going to call the helper function i'm going to call it root and i'm going to return a root so if root equal to no then i would just return no matter what since it's going right so i'm going to say root.right so i'm going to say root.right so i'm going to say root.right and once it hit the right side then i'm going to add the value then at the end i would just update the value on the sum for the sum and then and traverse on the left side right you have to like uh going left as well so i'm going to submit and yes pass the test and the timing space is the same so which is time is over and space is constant and that will be the solution and peace
|
Binary Search Tree to Greater Sum Tree
|
number-of-squareful-arrays
|
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\]
**Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\]
**Example 2:**
**Input:** root = \[0,null,1\]
**Output:** \[1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `0 <= Node.val <= 100`
* All the values in the tree are **unique**.
**Note:** This question is the same as 538: [https://leetcode.com/problems/convert-bst-to-greater-tree/](https://leetcode.com/problems/convert-bst-to-greater-tree/)
| null |
Array,Math,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Hard
|
47
|
1,706 |
hi guys hope you're fine and doing well so today we will be discussing this problem from the lead code which is where will the ball fall so this is the 20th problem of the dynamic programming series so if you haven't watched the previous videos you can consider watching them since it will be really helpful for you to understand the concepts in the upcoming videos and in case you are new to this channel you can consider subscribing it and pressing the bell icon so that you don't miss any of the upcoming updates so let's get started with this problem so the question states that we are given a 2d grid of size m cross n which represents a box and we have n balls with us and the box is open from top and bottom the other thing that we are given is that each cell in this box has a diagonal board spanning two corners of the cell that can direct ball to either right or left we'll see in the upcoming example what does this mean to say and then what we are required to do is we need to drop one ball at the bottom of each column in the box and that ball will travel from top to the bottom via some root and then we have to return an array answer which is of size n which basically represents that for particular index i that the ball is dropped in the ith column where will in which column will that ball land after it has travelled all the cells and in case that ball is not able to reach the bottom then we have to simply put minus 1 in that index so let's see this example so here we are given a 2d grid and each cell of this grid has either integer one or integer minus one so what does this both of integers represent is in case this is one then the orientation of the board that will be in this cell will be like this and in case it is minus 1 then the orientation will be in this form so if we try to fill this out it will be something like this so i am just filling it for first row and similarly we will be doing this for all the cells so i have done this here so let me just clear this out and let's just enlarge this since we have to work on this yes so the question tries to say that after we have just placed all the cardboards in their orientations that is required then we will be required to drop the ball from each column so we have the total number of balls equal to the total number of columns in this grid so once we try to drop this ball so this ball will travel from this path and it will eventually come out from this column and if we try to just throw this ball it won't be able to reach the last row because it in this case the root is totally closed and similar will be the case for this fall this wall and this ball so what we are required to do is we are just required to return the array which contains like for this ball where this will ball come out from so this ball will come out from basically this index which is zero and one so it will be one and for this ball from where will it come out it won't be able to reach the last row hence it will be minus one and since the result is similar for all the other three balls since they won't be able to reach the last row hence all the indices will be minus one so this is the array that we will be returning so this clearly states that the first ball which is the ith ball will come out from the first row and these all balls won't be able to come out so let's see how can we do this so if we clearly observe all the patterns we are given with like this pattern and this pattern this one and this one so out of these four we need to figure out again which case the ball might travel so if we throw a ball in this pattern so it will be automatically blocked but in this case if we throw ball in this pattern so it can travel similar is the case with this one and if we throw here so it might travel to left side or to the right side so the only case where this ball is not able to travel is this case and in the other three cases it is able to travel so what we shall be doing is we will be iterating over all the columns and why we will be doing so it will be because we have to drop ball from every column and then see the result so that is the reason we will be iterating over all the columns and then for each column what we will do is we will simply keep two variables like x and y which represents x represents the rows and y represents the columns so we will be initializing this x and y with initially where the ball is starting its journey from and then eventually we will be checking out like if this pattern is this one so yes obviously it can travel so we will be increasing our x and y two x plus and y plus because it is traveling to in this direction and the other case might be for example in this case if the ball is here and the pattern is of this type so obviously the ball will travel to the row next but the column is previous one so it will be x plus and y minus so this is what we will be doing and in case we will be checking that in case the pattern is something like this so this ball won't be able to travel to any of the next cells so we will simply break out of our loop and simply return that in this case it is not possible to reach the end row so now let's see how can we code this problem so let me just change this name to a and then we will be declaring an integer n which is basically the length of this array a basically the number of rows and m is equal to a of zero dot length which is the total number of columns and then we will be creating an array that we have to return and which is of the size m which is the number of columns and then we will be filling this array with minus 1 so now what we will do is we'll simply apply for loop from i is equal to 0 to i is less than m and then we will just increment it so we have applied for loop for each column which represents the total number of balls that we will be throwing and the answer for each ball and the reason why we have filled this array initially to minus one is that we are presuming that for every ball they won't be able to reach the end and then after iterating over all of them will find out of all of them how many are able to reach the end so here we will create two variables x and y so x will be 0 and y will be i so basically this is the initial where they will start the journey from so for example for this ball x will be zeroth row and the column will be this column which is basically zero in this case if the ball starts the journey from here so x will be 0 and the y will be basically m minus 1 so after having initialized them so we will apply while loop and in this while loop will apply a condition in case this x is greater than equal to n so what does this condition mean that in this case if we have reached the end so in this case after having reached end so when we come out the x will be equal to n or it might be greater than n as well so this is the condition that we have to stop and in other case what we will do is that simply if y plus 1 is less than m and a of x of y is equal to 1 and a of x of y plus 1 is equal to 1. so what does this mean that in case that the condition is basically the pattern is of something like this type which is here this is one and one so in this case we are able to travel and the next cell that we will be traveling is will reach here so that is what we will be doing we will simply increment x 2 plus 1 and y also let me just yes so by plus or other case will be if y minus 1 is greater than equal to 0 and a of x of y is equal to -1 is equal to -1 is equal to -1 and a of x of y minus 1 is equal to minus 1 and in this case what we will do is we simply increase the row and decrease the column and in the else case we'll simply break out of this loop so for this condition else if condition what does it mean to say is that in case this ball is just here and if it needs to travel from here then it is minus 1 and minus 1 so yes it can travel here so that is what this else if condition is trying to say and in the else case it is the else cases of this type so in this case it won't be able to travel so we have simply break out of this loop and what we will do is after we are done with all the conditions we are just left with this one condition which is if x is equal to greater than equal to n that is we have reached our end row so we will simply see if y is greater than equal to 0 and y is less than m so we'll do something in this case or something else in this case so what does this condition mean is that in case for example let's hypothetically consider that ball was here so after reaching here so this ball will come out from here but this column if we see it is -1 but this column if we see it is -1 but this column if we see it is -1 so this is not possible so and in the other case what it might be that the ball is just traveling from here and then it will come out from this side like if this board was something like this so this was the channel that the ball was traveling through so if this was the channel then it will come out from here so which is basically greater than the length of this column so this is not possible so in this case also we won't be able to store our answer in the answer array that we have to return so that is the reason we have applied this condition so in this case we will simply write array of i is equal to y so what does this mean is basically if we just drop the ball from ith column it lands in the vyath column so in the else we need to break so i'll be just breaking it here and let's try to run this code so it is giving this okay compilation error so it is missing the return statement yes we have to return the array basically this is our answer array so it is getting accepted now let's try to submit this problem so yes this problem is getting accepted so i hope you understood solution in this video and if you appreciate my work you can consider subscribing to this channel and giving thumbs up to this video so let's meet in the next video till then bye
|
Where Will the Ball Fall
|
min-cost-to-connect-all-points
|
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.
* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.
We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box.
Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._
**Example 1:**
**Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\]
**Output:** \[1,-1,-1,-1,-1\]
**Explanation:** This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.
**Example 2:**
**Input:** grid = \[\[-1\]\]
**Output:** \[-1\]
**Explanation:** The ball gets stuck against the left wall.
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\]
**Output:** \[0,1,2,3,4,-1\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `grid[i][j]` is `1` or `-1`.
|
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
|
Array,Union Find,Minimum Spanning Tree
|
Medium
|
2287
|
151 |
hi everybody how are you all doing and how's your interview preparation going let me know in the comments below and let's dive into today's problem so we are given an input string s and we have to reverse the order of the words so we need to return a string of words in reverse order concatenated by a single space they're also saying that as may contain a leading or trailing spaces or multiple spaces between two words the return string should have only one space we do not have to include the extra spaces so for example if input string s is the sky is blue then the output should be blue is sky the okay and the second example we have some leading spaces and some trailing spaces in that case we have to simply return the word world followed by hello without any additional spaces and the input string three is a good example this has multiple spaces in between so when we return the output string we have to reverse the order so it's example good a and all of them separated by a single space okay so now let's think of a brute force solution words are separated by one or more spaces in the string so we can look for a space and then simply add the words into a stack and at the end simply remove the words from the stack and construct a reverse string okay now let's understand this with help of an example here is our input string a good example now underscores are indicating the spaces and here we have multiple spaces so first thing what we're going to do is look for a space and then find that word and add it to our stack so here we have a and then we find the next space here so this is another word we are going to add that into our stack and then look for another space which we don't have so at the end whatever is the last word we will simply add it to our stack and now since we are at the end of the string we will construct the output string by popping this element out first so example so that got removed from the string then we will add one space and then we will remove another element from the string sorry from the stack and then we will add another space and then we will return that one out and this will be our output we will have to do additional logic to account for multiple spaces now this logic works but it's not the most optimized solution so our approach is still the same we still want to break the string down into multiple words but instead of manually searching for the spaces we're going to use the split string function so here is our split string function it takes regular expression as a parameter and it returns the array of strings as an output okay so here is our regular expression for one or more spaces first we will declare an array of string so string array let's call it words equal to s dot split string let's add our regular expression for multiple spaces so with this code we got the input string converted into an array like this now all we need to do is to traverse from the end of the array all the way to zeroth element and construct an output string so let's first declare our output string call it reverse string initialize it to an empty string now let's declare our for loop int i equal to words dot length minus 1 i greater than equal to 0 because we're traversing from the last element all the way to 0 i minus okay so for every word here we have to bring that into our reverse string so let's say reverse string equal to reverse string plus words of i okay and then at the end we also have to add one space between these words so reverse string equal to reverse string plus one single space all right now we want to return the reverse string and we're going to trim it just because there is an additional space at the end and with the trim function it will get removed so now let's go ahead and run it our solution is accepted if you found this video helpful give me a thumbs up and if you want to do more lead code problems i have a playlist linked here and if you're interested in learning more about system design concepts i have a playlist linked here make sure to check those out
|
Reverse Words in a String
|
reverse-words-in-a-string
|
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return _a string of the words in reverse order concatenated by a single space._
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
**Example 1:**
**Input:** s = "the sky is blue "
**Output:** "blue is sky the "
**Example 2:**
**Input:** s = " hello world "
**Output:** "world hello "
**Explanation:** Your reversed string should not contain leading or trailing spaces.
**Example 3:**
**Input:** s = "a good example "
**Output:** "example good a "
**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string.
**Constraints:**
* `1 <= s.length <= 104`
* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
* There is **at least one** word in `s`.
**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
| null |
Two Pointers,String
|
Medium
|
186
|
1,721 |
hey everyone this is hope you're doing well so let's start with the question so the question is swiping notes in a linked list okay so you are given the head of the linked list and an integer k what you have to do you have to return the head of the linked list after swapping the value of kth node from the beginning and the k node from the end okay and the list is one like it's from one index okay so you are given a linked list and you have to swap the two nodes and basically the values of that so you have given a kth node so you have to take the node from the start and you have to take the node from the end and you have to swap both of them okay so let's see with these examples as you can see this one two three four five and we have k equal to 2 so from the start this is my you can say k equal to 2 uh node and from the last this is my k equal to node so we have swapped this 4 and this 2 will this will convert into this linked list okay so let's understand this question with an example okay so let's take this example okay so we have given this list and k equal to five so let's write it down like so this is 7 then we have 9 then we have 6 7 then so this is the linguist that is given to us so let's say this is our head pointer okay so let's take from k equal to five so if we go from this so okay so this is the linked list and let's say we'll give the indices so this is one two three four five six seven eight nine ten okay so from the beginning if you go to k equal to 5 so this is your first pointer and from the last if you go one two three four five so this is your last k equal to five so what you have to do you have to swap these two and your final link list will like seven nine then if this is six then you swap this so eight seven three and this is zero nine 5 okay so this is that's the question that you have to do so if i go with the name approach what i can do is i can basically treat them as an array and after that i will swap the element and then i again convert it into a linked list okay but if we go with that approach that will take an extra space of array so let's see how we can remove that extra space okay so like with our previous approach we are taking an extra space so let's see how can we remove that extra space what we can do is like if you can see for this case this is your first pointer and for k equal to 2 from the last it will be at this so you have to swap this and this okay so what if from the start i can go to this position and from the last if i can get this position okay how so if i give the indexes this is one two three four five okay like if i know the tail or the last length of the linked list i can easily get this position so let's say this is five and i can do five minus two and basically do plus run so i can get this location and i can swap this but instead like i have to if i need the length of the linked list i need to calculate first length of the english then calculate this particular index so if you can see we are going with the two parts like first we calculate the linked list then we calculate this can we do like instead of going uh by calculating the linked list can we basically convert it into or into one pass okay so let's see how we can optimize it okay so now what we will do we will take two pointer basically so this is your head okay so what we will do we will make our slow pointer so slow will also point at here and our fast pointer will also point at here okay so first step what we will do we will first find out the first basically we need to pointer first which will also start from head and we'll take a second which will also start from it so our first step is to first find that uh basically that node which is from beginning okay so what we will do will go till k equal to two basically what we will do we will loop over till one is less than okay so we'll go to here so what we will do we will check so this let's give this index one two three four five so we'll go one by one so we'll move our fast okay so our past will now come at here now we can't move further because k is only equal to two so we have reach our location so we have reach our fast at this position so we'll update our first so first we'll now point to you can say fast so which is equal to two okay now after this is the first step you have to go to this first location now the second step what you have to do is uh you have to take your slow and fast at the same speed basically at like every you have to do is move your fast by one so pass will come here similarly your slow will also come out here so we'll move till fast is not equal to null so we'll move again first okay again we move our slow so slow will come at here we'll again move our first and we again move our slope okay after this our fast dot next is equal to null so whenever our fast dot next is equal to null we just stopped there and we got the slow pointer so wherever the slow pointer is pointing this will be our you can say a second so this is pointing through slow so this will point to four after this what you have to do you just have to take a swap function and you just have to convert this first and second okay so like it will be more clear if we write the code for this so basically it's a simple straightforward implementation question so let's take a slow pointer which will also from head let's take a fast which is also head and let's take a first equal to head and let's take a second equal to head okay so first step is to update your first okay first pointer so what we will do basically while uh let's do a for loop for end and indexes is from 1 so 1 to i less than k i plus will update r fast okay so fast will move by this way okay so we have reached uh update our first so we'll need to update our first pointer so first equal to fast now we'll update a second okay how we will update so we'll move both so basically fast dot next is not equal to null will move both fast and slow at the same speed pass dot next and slow equal to slow dot next so after you reaching fast dot next is equal to not null so you will update your second the second will point too slow and after that you just have to swap the value so you will do end temp equal to first dot value and first dot value is equal to second dot value and you will do second dot value equal to temp so this is the swap function that you have that we will write and after that we just return the head okay let's run it okay let's see and sorry for the voice actually not well so this is accepted let's submit it so our code is submitted and as you can see we are only go in one flow only like we are not calculating the length then we calculate the tail so we are only in one pass only so it's a order of n time complexity you can say and space we are just using a constant pointer so it's a order of one for the space hope you like it thank you for watching my video
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
88 |
hello everyone today we're going to be going over a leak code question our lead code question for today is merge sorted erase essentially we're given two integer arrays and they want us to um put them together so it's kind of easy and make sure they're sorted as well so for example one we're given one two three zero m is three numbers two and is one they pretty much represent our e arrays and then when we merge them they'll come out to like this so let's go ahead and code that out and we'll see it'll make much more sense in just a bit so first we're going to create two variables to represent our uh arrays we are also going to make sure they start at the end of the array so we'll do it like this equals m minus one m is the representation of nums one so then we'll do the same thing for our second array all right now we're going to create a for loop we're essentially going to start at the end of the array and make sure that it as long as it's greater than zero we're going to keep incrementing down so let's go ahead and do that right now so for let i equals the first array plus the second array minus one which would be the end of the race we are going to say as long as it's greater than zero are equal to i'm sorry long as it's greater or equal to zero we will then increment i okay cool now that we have that done what we're going to do is see if the second array is less than zero which will be null and if it is we'll break our loop so if second all right so like i said as long as second is nulls which is less than zero or break now we first what we want to do is see if our first array the element we're on is less than is i'm sorry is greater than our second array so we got to see if it's greater than our second let's go ahead and do that first what we want to do is if nums one first is greater than numbers two seconds else if it's not what we're going to do is we're going to replace the current element that we're on in the first array with the second arrays element that we're currently on so let's go ahead and do that so else numbers one i equals numbs two which is the second once we do that all and we gave the nums two to the sac current element we're going to increment second okay now that we have that so if for example nums if nums one first is bigger halos syntax here if it's bigger than nums2 then what we're going to be doing is simply we'll be updating the placeholder with that current element so makes more sense when we write it out let's go ahead and do that num1 which is the current element we'll be updating it with the first okay and then after we do that we will move our placeholder and move it to the left so let's go ahead and de-increment our placeholder okay now let's see if this is working out correctly all right it looks like it works if this video helped you out in any way go ahead like and subscribe if you have any questions go ahead and drop a comment below thank you for watching have a great day
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
975 |
okay I'd even jump 975 you're given an image of a from some starting index you can make a series of jump the first third fifth jump in the series I call odd number jumps in the second four six jumps in series I call you even double jumps you may win the sniffles you may from index I jump forward to index J with i destined J in the following way you can jump forward okay to an odd number jumps one three five you jump to the index J such that a sum is less than or equal to a sub J and a sub K it's the smallest possible right if they're multiple such index.js you can jump to multiple such index.js you can jump to multiple such index.js you can jump to this more as such in that there's a lot of waiting in this one in a second doing even-numbered jumps you jump to J such even-numbered jumps you jump to J such even-numbered jumps you jump to J such that B sub I is greater than a sub J and a sub J is the largest possible value there multiple such index.js you can there multiple such index.js you can there multiple such index.js you can jump to smallest such index J it may be the case that for some indexed I don't nobody go jumps starting index is good if some index you've reached the end of the way by jumping some number of times possibly zero or more it's impossible zero or more than once we turn the number of good starring indexes yeah I mean I my first intuition is just that this is a flat first search but let's take a look at the kind of the constraint first so twenty thousand numbers oh yeah but first search is probably right but or some kind of shortest path type or like a single source yeah but one of the shortest paths where you have a single source that goes to all the other ones but I think I have to really read this problem again cuz it's just very confusing to be honest well now it's not that confusing but it's a little late and I'm no tired and I'm just trying to make sure that I understand this correctly okay that example there's an input that's 10 13 12 14 15 still we become values too because isn't so I guess there's always one at least but that's the point okay so okay for you so we each of these for example 210 will go to the smallest number to the right of it okay and that's for the odd number ones but you know even number ones it would take the large as Y of them over there yeah and you take the smallest such index so I want a leftmost bit to highest so why can't 13 coda notine goes to not just possible all right this is an even number of odd number jump side that's why okay 13 will go to the fourteen because sister smallest number that's larger than thirteen okay so some of these kind of graph problems I think the in theory I mean different ways to model it and there's a staff a graph a problem but that's only one component of the problem there are other components as well and what some of them requires more advanced data structures so I think the first kind of yeah man uh yeah sorry yeah so the first part is yet constructing Canada graph and I didn't personally explicitly but because of length is twenty thousand you can really create like an N squared graph will have an adequate way of doing it for twenty thousand I think you I would try to find something that's n lock and I guess try one in time yeah so maybe it's maybe test is to binary search one down over thinking of but so this more as possible you that's and each other money could be up to a hundred thousand okay it's having the coil so and also like this is Jim dilute I said it's a graph problem for the most part know each index has only or each yeah each in turn each node which this has a one-to-one which this has a one-to-one which this has a one-to-one correspondence but the index can only have one out edge and constructing the graph is kind of a hot point of the forum and then after that it's just a conductive to everything I mean uh I might have said I mean I've definitely said a shortest path but is you actually have to return there at the path we just have to it's more of a reach ability right so you still use peripheral search or something similar well probably buffer search but the actual problem is about constructing the graph and yeah and for this problem you're just trying to figure out now you try to create the data structure such that well you're solving two problems one is that for odd indexes yeah anyway this is actually then this problem was also a little confusing because I think the odd-numbered jumps is actually the odd-numbered jumps is actually the odd-numbered jumps is actually the even-numbered index and so and the other even-numbered index and so and the other even-numbered index and so and the other way around so I nobody kind of annoyed by typing r-13 jumps to what okay is that true okay so I understand this explanation that's what I'm trying to read right now for example 413 we can jump to ie goes to movie y 1 2 3 so 13 chapter 14 but I can't do it injunctive would be nervous it's not I think I confided some stuff that fine but basically what you will actually do is you just double the number of nodes one for each number jump and each and even-numbered and just see if you get to even-numbered and just see if you get to even-numbered and just see if you get to I don't and but yeah so that's I mean it's still the same problem you start itself or this thing's but how to do it so and you have to do it faster than N squared time so okay now I think this is maybe similar then to the last one we've done maybe you can tell me okay so for each index we have to figure out where top 150 is or she's not so but we have to figure out the smallest number that's bigger than this number but not like yeah I mean I think that's not that bad I mean you just got a solid man yeah okay yeah so you just I think you just I was trying to think of just anything tricky I have to do but if you just sort it and then you just create edges to the stuff adjacent to it I think that should be good yeah okay yeah and also for the other ones so that's quite two ways one is small is larger so they say it's the smallest number that's larger than this car number is to go to a list and it's you go to something like that right I mean hold on a second well let's see yeah okay well now it's pointed you in the wrong one so that can help okay Soviet soil but that's it just this work oh well I mean it kind of works but uh you might not table is just school right now but uh kind of works better we actually won the flip okay fine let me just create an alternate ring or I could just pass in the following how's that possible he was like lambda wait okay like that it's been a while okay Wow dad actually surprisingly worked really quickly mmm okay but uh oh yeah now you have this away and that actually just hold it in it actually your naming is not given Oh guys so now all we have to do is kind of create edges so that we can get to them easier know Jesus and now when I said about grabs actually I think because each point only has one out graph we actually don't even need to we could just walk to tag with some kind of now some memorization so that uh you know so we don't do the same thing twice but that should be good okay well that works for the smallest torches it's that true hmm well now hmm I mean just work for the first element in no and you know the 212 well that's not gonna work but I played actually and this is kind of very coincidental but now we do the thing where again with the stack right so like here we put this on the stack the first element and then we'll just put this all right so we put the first element on the stack so the stack is 0 10 and then when we get to 212 we pop this off and then when we process 113 well can't so we just push this under the stack and now we do 314 and then now we pop these two wait okay yeah so that's how you would construct them again okay so now it's very christened and two because again we solved the same form twice in a weird way but okay let's do odd numbered terms now a and then now so now okay so look literally did this earlier today so the same idea here so index max you care about index if the index is bigger than your current indexed and you pop no sound actually Vanitas man what's hoping at least something came out better okay no rips this is should be onion sudonym right now this works for one outlet but why didn't true mean I got it yeah that's right so on odd number chums zero will go to 12 13 will go to 14 12 will go to 14 and 14 will go to 15 so I so this is working as expected and in order to do the same thing with the even number charms the except for and reverse let's see again so the largest number that's more than this number okay largest number that smaller than this number I mean it's probably something similar but actually not now we want to be worse at this yep okay that's largest number that's small and this that's good except for the where is it yeah it's good it's just that not in this example do very few even-numbered this example do very few even-numbered this example do very few even-numbered charms yeah just that this example may not have given them with jumps them if you tried the second example is that in this case see what code it to I do tell will happen and even numbers okay so I think this is right maybe mm-hmm laughs that could be up could have been copy-pasted I guess so given number two can go to one which is probably true so we can go to one will go to three and then that's it okay so that seems right and now I think what was love is just kind of a I mean we said something about my first search earlier about like finding conductivity but given that we kind of construct this graph in this way I think so there are two ways you can do about it one is kind of go backwards in time or like I create a crater inverse graph or using with number jumps in our number jumps or you can just kind of what I'm going to do is I'm just going to go forward and do a recursive thing with memoization so let's do it there's a memorize function too but I'm not going to use it because I don't not for me I mean I know we're bad I'm not super familiar with somebody now just some homework for me next time but uh hey so now we that's me goodbye just it's easy against my past a yeah okay well you just passed all the other stuff that be calculated cool um okay and if you know K might just make it a pool in art and the currentindex return as possible well I'll do the print base case in a second but chums no just yeah okay make this last party in the second hangar so that's roughly why predict it's gonna be some clock conditioned and stuff like that so I just like did that twice now virgin okay now base cases well yeah it index is equal to whether done over a minus one maybe can return true right that's mostly yeah really oh yeah I'm going to check to see if yes okay well that's quickly one this floor I think there's some memorization that we can do here to make sure that does inspire into some craziness I mean our craziness there just be a haven and square which is four to twenty dollars now would you want but otherwise a real guy can I do this that's high misspelled I have too many windows open man what is that library call from tools okay fine I've just manually to it up in a while okay if oops quite another example why don't you write it now let's try some empty cases and stuff like that I mean I think in theory I would also try to pick case but I'm kind of lazy why not hmm I know that's the expect it I kind of got that way but I don't know I mean I think I got away more than ate it anyway I just want something big ish just make sure that it works okay wow that was very quick but uh okay I just a minute there hopefully I don't have any edge cases cool okay so this was accepted and one-time pretty slow better okay yeah so one-time pretty slow better okay yeah so one-time pretty slow better okay yeah so for this one I think that the same I mean it's a little unfortunate in the sense that we have a duplicate idea of what we did last time I think as a result of kind of these extra complexity this is actually a problem down like a lot as an interview I think it would apply taking me a little bit longer to figure it out everyone for put that obviously but I think as an interview I would actually like this problem just because it like again or these are kind of a basic concepts there's the stack also as an interviewee I would play they comment about modernizing this and cleaning this code up a little bit maybe kind of you know don't we clean myself a little bit there's stuff with some minor changes with that we can kind of fix actually maybe I mean the only thing that's different between these two things are mister lambda functions here so we can definitely try outside for putting it into two different ways that way so that's actually very easy code cleanup but it's an individual I like having layers and I like kind of seeing things this way others it's just graph to stack there's a little bit memorization though it's not super necessary if you had done the other way with breakfast search from the end but still like it you know there's a couple of steps and it takes kind of linking them together and that's what I like about it is an interviewer I've I think this is possibly a little bit hot side to be honest and an individual it's also one of those things where I would not necessarily asked interviewee to have an optimal answer I would just kind of ask them to work for it and ask them to you know what yeah halfway floor whatever have of the time did I actually write some code so that we can kinda see where it goes but otherwise I could see myself using this for this question as an interviewer maybe is a note tricky but I think there may be a little bit of calibration that we can kind of do and maybe you know us may maybe take out the odds even thing but for the most part I think it's a fun problem and yeah I mean I think it takes a little bit understanding but otherwise I take this problem and I would like it to maybe play around with to get the calibration right on an interview
|
Odd Even Jump
|
range-sum-of-bst
|
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices.
You may jump forward from index `i` to index `j` (with `i < j`) in the following way:
* During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`.
* During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`.
* It may be the case that for some index `i`, there are no legal jumps.
A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once).
Return _the number of **good** starting indices_.
**Example 1:**
**Input:** arr = \[10,13,12,14,15\]
**Output:** 2
**Explanation:**
From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more.
From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.
From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.
From starting index i = 4, we have reached the end already.
In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of
jumps.
**Example 2:**
**Input:** arr = \[2,3,1,1,4\]
**Output:** 3
**Explanation:**
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:
During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\].
During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3
During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\].
We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.
In a similar manner, we can deduce that:
From starting index i = 1, we jump to i = 4, so we reach the end.
From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
From starting index i = 3, we jump to i = 4, so we reach the end.
From starting index i = 4, we are already at the end.
In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some
number of jumps.
**Example 3:**
**Input:** arr = \[5,1,3,4,2\]
**Output:** 3
**Explanation:** We can reach the end from starting indices 1, 2, and 4.
**Constraints:**
* `1 <= arr.length <= 2 * 104`
* `0 <= arr[i] < 105`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
| null |
1,029 |
hello everyone today's question is to city scheduling there are 20 people a company is planning to interview the cost of flying the I person to CTA is costs I zero and the cost applying the I person to city B is costs i won return the minimum cost to fly every person to a city such that exactly n people arrive in its city now we will move to pen and paper and understand this question more clearly so now we will understand this problem statement using this given example suppose here we have four people okay we have to send four people in different cities there is this is indicate for CTA this is for city be subsequently this slide city B okay so what we have to return we have to send we have presented to people this is 4 so we have to send half people to CTA represent two people city be and two people to city a represent equal number of people to each city two people see TB and two people city a with another condition with minimum cost okay so with minimum cost we have two so possible minimum cost we have to maintain possible minimum cost means first what we have to do where to first we send people we have to send first person to CD for in this junk we choose city and in this chunk we choose city again cause this cost is cheaper than city B and in this case also in this case we choose City be instead of City em cause 50 is cheaper this 50 is cheaper than 400 so in this case we choose CTB because if we fly ctv then it will be cheaper than city a so in this to case we chose CT be because this is cheaper and in this locus in this token in this to case we choose city a okay city so two people for city a and two people city be okay now we will able to equal number of people to see ta & city equal number of people to see ta & city equal number of people to see ta & city be that is 10 there is 110 so using 110 cost we can able to send four people city a and B to two people to city and two people to city B I hope problem statement is clear to you okay now solution here I will modify the data okay so what I will do here first I will send first I'll send all people to see TJ okay first I will send all people to city air and then I will calculate the cost okay first I will send all people to city a yeah or the place for will send for people to CTA and this will cost 4/7 okay this will cost 4/7 okay this will cost 4/7 okay and now but I have to do yeah I send all people to see today but in our problem statement we are present represent a number of people to different settlements we represent two people we have to send two people to city a and two people to city B so now we need to choose half of them now we need to choose means we have to choose to cost from this for cost okay we have used only to cost okay and now what I will do I will calculate the cost for CTB also so I will calculate the cost city B so if we send all people in city B and there is 2,200 50 and what is interesting okay so now what I will do I will choose the better option with city cost it's cheaper so for this - he puts if we send the people for this - he puts if we send the people for this - he puts if we send the people instead of city it instead of CTN then it will cheaper no not cheaper cause we have to pay extra ten rupees cause this plus ten and if we send for this if we send people to CTP it will cheaper no it's not so we have to pay extra 170 but we have to convert the minimum cost here we have to pay 170 so we will not so will not go to this city because this is extra cost we have to pay extra cost okay now - next so that is this will okay now - next so that is this will okay now - next so that is this will cost 400 woah this is so costly and if you send people to CTV just only 50 rupees okay so it's only 50 so yeah able to save okay so we can able to say 350 so we should go with B because this will this we will if we go to city B then we have will sent three with no and if we go to city B then we have to pay extra next just here we said the cost but in three case we have to pay extra but we have to choose two people we have to send sorry we have to send two people to city B and to reproduce and here we choose the minimum cost minimum one cost from this three cost because we know this is a when this is costlier but we can't choose three people we can't send three people to City a because in this problem statement we there is a rule we have to send equal number of people to different city so here we can go with will choose CTB for this case and in this case and choose city for this and this okay means we will choose CTB for this and we'll choose CTA for this and this six 30 and 20 50 70 and 60 okay so it will cost 60 70 that is 130 and we can able to extract the answer form this also for 70 - 350 and choose the minimum of this 3 - 350 and choose the minimum of this 3 - 350 and choose the minimum of this 3 that is 10 plus 10 that is also 130 so this one that is our desire answer so now I will move to implementation part in our implementation first I will input instead of sorting this I will build a heap Q so in this different list will store the cause difference between CTA and CTP and min-cost we store the store all the cost min-cost we store the store all the cost min-cost we store the store all the cost of CTM if we sent all people in CTL mean cost will hold in different list we append the difference between CTB and sit here and mean cost will hold the cost of CTA now we send our people to see TB also and we will reduce the cost mean cost I already told instead of sorting I will use here heap you to say to improve our time complexity was building cost is or drop in and now I add the mean cost plus Q dot he pop different okay and now I will return mean cost so answer so yeah running successful now I will submit it yeah got accepted thank you fortune this video if you are new to this channel please consider subscribe and don't forget to hit the bell icon
|
Two City Scheduling
|
vertical-order-traversal-of-a-binary-tree
|
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Hard
| null |
284 |
Hello hello everyone welcome to lotus camp and today also let us cover seeking it in this problem the are going to implement the interference from operation theater interface in java subscribe to do half of such scams and this morning you can see water operations can be Performed during and after this is his next and rule veer who has written a letter written form element and problem support and corporation and subscribe open the point to point hello viewers welcome you want and that point to and tell house next point to amrit Same function but instead of returning div returns boolean value from the data let's go into the truth not going all a very simple and now we are going to implement pick per full form or sandy soil of current point which cold be just returned to enter into a key. Dry Air Trigonometry Metal Tractor Less Declaring And Wide Letter Dated Object On That And Anti Who This Point Loot Side Left Side Subscribe A Specific Want To I Just Operator His Next Huge Philosopher Side Friend Will President Rule 10 Minutes It's pointless that this note vitamins tap so no where was under current value swords pet is just under current and first and till Kharar suit piece into water has made through it's going to check the current wali that late note from this next 9 news room Subscribe to current 10-year the current affair has tender moving point off two half current next and finally returning to step down in the next to the current see and hear electronic soon no pleasure watching
|
Peeking Iterator
|
peeking-iterator
|
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
**Input**
\[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 2, 2, 3, false\]
**Explanation**
PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\]
peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\].
peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\].
peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\]
peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer?
|
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
|
Array,Design,Iterator
|
Medium
|
173,251,281
|
1,732 |
That Aapke Ajay Ko Hua Hai Hello Everyone Welcome to New Video in This Video By Going Towards Another Problem from Any Problem as Final Beatitude Problem Subscribe Subscription for 100 Countries Are Given in This Point E Plus One for All IS WELL WISHES RETURN COMED WE HAVE THIS A Now the role is not our selection but some elevation steps are ok in it, there can be something like this, anything like this can happen, for that the mission is to tell us which bike will be at this point. So what is his height ok so please subscribe don't forget to subscribe our channel That I'm Rich It's Really - 525 150 - 0 What's ours this means this 150 - 0 What's ours this means this 150 - 0 What's ours this means this is point number one where but now from here It can be said that it can be done okay so if we here Next Nine Chapter - - - - - - - - - Subscribe Day Test One So now on one how much was the maximum zero suppressed maximum got new got so we Will update it Subscribe here on 102 - - - - - - - - - 64 Yogini - Subscribe here And she is ours So what is the answer Our answer has come One So what will we out One is ours If we return then we will answer this question Let's see how we will set it for, what we will do in this question, we will make ours, which we will keep, it will not be less than 000, just talk and do it, because where is it and from the village, its length and subscribe, inside this, whatever we do ours. Let's do, let's do the net, okay, we will make it sexual, after that, what will we do, whatever is our maximum, I will update it, make the maximum more and whichever of these two, our place value will get finished like and if this is an example, if we subscribe examples. If we wash the paper then what will be the maximum amount and how much good kind, here we will add Ka or village and increase it by two more, a good number has increased, Mexico, so we will add it in our mixture too, so now whatever we like on three, it will wake up. And now, this is our point above, this subscribe button and our mixer, how much was it, compare and this is our subscribe button - - if compare and this is our subscribe button - - if you wear this below, then what is the current of ours? To maximum, how much time to time, which is bigger in 10th maths, what will be the value of 10th maths, then we have plus one, then again it will reach one above i.e. we have plus one, then again it will reach one above i.e. we have plus one, then again it will reach one above i.e. and our divided by - - - - - - - - - - - - - - - 110 so our that subscribe to our channel. So let's subscribe above, do subscribe to our channel, what will become of our space comparative, what will become of our content because here we did not create any disturbance, so let's solve this problem on ourselves, so you tell us first of all. We have to do the first point and the second thing is to do whatever we do now till the village was 2012 Grand daughter in next what we will do we will update it plus the city will inspect and here whatever we do we If we keep it in the village, then we will distribute it from village to village and then whichever of these two is of its kind, it is as if our appointment ends and we return it, then there is a problem, let's see what is the result of the alerts for the example discus. For this our subscribe is to and if we see it then it is our faster than hundred percent solution and that is why it used 22% less and was more of a solution. used 22% less and was more of a solution. used 22% less and was more of a solution. If you have any doubt about this solution then you can post it on comment below. We will reply as soon as possible. Thank you for watching
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
389 |
hey everyone today we are going to solve the video for the question find the difference so you are given two strings s and t string s is generated by random shuffling string s and the 10 to add one more later at a random position returns a letter that was added to T so let's see the example so s is a b c d t is a b c d e output is e because the e is a letter that was addicted so let's see example two so s is an empty string and the t is y so that's why output to e is y in this case Okay so actually there are a lot of ways to solve this question but in reality I mean in gear interview I think we can use this approach so let me explain how we think about the solution and so s equals ABCD and the T equals a b c d e so since T is plus one longer than S so seems like we can use like a subtraction but the problem is T is like a shuffled s plus one character right in this case um this is a like assorted character but the description said um so T is a shuffle the S and the plus one character so um at first we I thought I need to like count both strings but I realized that I only count the number of characters in string t and I keep a hash map like this and because that t is longer than S so all we have to do is after counting T is to just subtract each capital of s from a result of d so let's see how it works and this is a result of the accounting um each character in string T So a b c d e all characters are one right and then after that you get through string s regular one by one and the first Target character is a so if we have a in hashmap so we subtract -1 from so one a so that is zero and one -1 from so one a so that is zero and one -1 from so one a so that is zero and one more important thing is that if we reach 0 so we don't need a air anymore right so after iterate through S string so we can we want to only use the like a left over of key so that's why if we edit the zero so delete a key from hashmap and then move next so B and we have V in hashma so in the zero and uh so reach zero so delete B also our next Target DC so c is now zero and that is still so delete C and also um next Target is D so zero and that is zero so that is d and then after that um we only have e in hashmap so all we have to do is just return on this key so very easy right yeah so that is a basic idea to solve discussions so without being said let's get into the code okay so let's go first of all um initialize a hashmap let's say count and then so count each character in string T So for C in t and the key should be t equal not t c um equal count dot get and find the C and if we don't have a key so therefore the value is itself and every time um plus one right and then after that subtract Counts from the characters in like a string s so for C in s and the count C minus equal 1. and the important thing is that as I explained earlier if count C sorry zero in that case just delete account and see and then after that all we have to do is just return so-called Dot so-called Dot so-called Dot keys and we need to convert the list and then um Nintendo like a pass key actually we only have one key right so that's why we definitely we can get the index zero yeah so that's it so let me submit it yeah it looks good in the time complexity of this solution should be order of s plus d so s is a length of s and T is the length of t and the space complexity is a order of T So T is the length of D so this is for hash map yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
86 |
hello welcome back today let's try to solve another little problem from the lead code delayed silencer it is 6 partition list so we are giving a link to list so we're gonna to output another linked list but it should have some conditions so the partition yeah should be like this the not less than x come before the notes greater than or equal to X but at the same time you should keep the order of the node now let me explain the descriptions for example we have example one we have one four three two five and two and X is three so it means if the value is less than 3 should be at the left side of this rule if look yeah this is the only condition for example this 2 and 2 is less than 3 so it should go to the left side but we need to keep the original order this means the original relative order is one two so here is a one two after that we should also keep the values which is bigger than 3 4 3 5 so here is the four three five so this will also keep this in relative order at the yeah if the value is at the right side for example this one to two is less than 3 at the left side and then at the right side we should also keep the relative order it should be 4 3 and 5. how should we do this yeah you may think maybe we can do it in two Loops so for example for the first loop we're gonna check the value if it is a less than three we're going to just prepare the value use a dummy node pointed to 1 2 and 2. so this is the first iteration yeah because in this way we can keep the relative order and then we're gonna have a second Loop we just set the values is more than equal to three and then we link data to four three and five now we return our result yeah because if we need to keep the relative order normally we can use a two path to solve the problem now let me write the two parts method to solve the problem so we call it a two paths now let's prepare a dummy node so the dummy equals to T pointer should equal to list node why we prepare dummy because this is a can avoid many operations if you don't use dummy what if there's no not how should you return yeah a lot of operations you have to attack if there's a no not it means a noun you have to check this noun if you prepare a dummy you can always return the dummy dot next because the dummy will be fixed and this P pointer will be shifted according two are very loud this P portal just need to connect each of the node and then the people finish its operation we just need to return next just need to return next just need to return next because the pivotal has already ported it to a noun it means we've already used the porter then we return so this is the then we return so this is the then we return so this is the basic initialization for the reporters now we're going to prepare another reporter 2 so equal to hat because we are going to use this head to check the values if it is bigger than 3 or equal to 3 or smaller than 3 but inside the node this dummy node is reported to the head so we're gonna give a zero and had this zero doesn't matter it is a just a value because we will not use it because we're going to return because we're going to return because we're going to return but this head important because we're gonna put this dominant to the head to the first node one pointed to this node then we are going to use the two parts to solve the problem so while head now we are going to use head after that we're going to use another path so for another pass because of the head cannot be used it has already pointed to a noun now for the second part we're going to use this Q order so this is why we use a q equal to hat because we will use it later now let's try to Loop through the head we're gonna set the values from the node if head dot well less than the value X now the P pointer dot next from the beginning the P powder pointed to the dominant now it will put T dot next it will connect it to another list node so which is the list node head dot well because it is less than x we can connect it directly so this is actually the first path after that we're gonna shift the porter to P dot next and no matter with fact this head value or not the headquarters would always be shifted to the next this means it's just a loop so the head should equal to head data next so this is the first Loop now we are going to use the second Loop the first Loop it starts to finish this like this the P pointer pointed to the dummy pointer pointed to one and pointed to two pointed to another two and then it pointed to a noun so this let's already finish to the first Loop now we are going to use the second Loop because it is not pointed to none it should point it to this number four this is not four now we are going to use the second Loop actually it's the same let me copy the code from here but here we cannot use the head anymore because the head pointed to a noun which would use another pointer from the beginning of the head it's also pointed from the beginning so we're going to use a two pointer and we're gonna set the Q dot valve if this is more than and equal to X that means our P Porter here is still the P Quarter because P Potter will connect it to this not four ft poeter so it equal to T doesn't X and here the values to the Q dot well and last the queue should be updated to Q dot next you can see that it's exactly the same first the conditions is different the head dot value less than x and this is a q dot valve more than equal to X and for this P putter it will always be shifted to the next and the two pointer will be substituted to the next after filling to this second Loop second path it means all the node has already been connected like this we just needed to like this we just needed to like this we just needed to now let me run into two SEC if it really works as you can see it works now let me submit it to tag if it can pass all the testing cases actually the time complexity is just on because we use the two parts it's o2n 2N equals to o n thank you for watching that's a bit for the result it's a little bit slow yeah but it's just to prove everything is right yeah you can see in the past and it's pretty fast thank you for watching see you next time
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
1,071 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge so the problem asks us to do the greatest common divisor of two strings so we have S and T and we have the concept where T divides s if and if only s is a series of concatenation of T so basically um concatenating as some value with itself multiple times gives us that string and what the problem asks us to do is we get two strings and we want to return the largest citring that divides both and that's where we have the concept here of carbon divisor but we want the largest possible string okay so if we take a look at the this example here with these two strings well we can just do ABC because it's a concatenation Once here and the twice here right with the second example we can do a b because then we would have something like this and the second we'd have a b naught it's not a concaten it's not a b right so that's not possible but we can do just a b because then we have two concatenated here and we have three concatenated here so it should work with two strings like lead and code here they are different right there is no common string and so in that case we just want to write an energy string in terms of constraint here we have 1000 which basically tells us that an oven solution should work oven squared should be able to pass as well um okay so let's see how we can solve it um okay so how do we solve it so the problem says that we get X which is going to be equal to t plus T right so the thing to notice here is that well let's try all the pre let's just try all the possible uh possibilities right and we don't need to try substrings we just need to try prefixes why is that because it's literally the value is of each string should be a concatenation so here S1 S2 so it should be a concatenation of it so if it's a b then it needs to be a b first in the prefix and then another a b so the X the T value is always starts at the prefix right because it needs to be the entire thing it still be a concatenation of T right and so that means just let's try all the prefixes that's the idea here so try prefixes and the thing is we need to try the prefixes just of one of them we don't need to try with both right we can just pick a prefix from just fix one of the strings let's say S1 and just pick a prefix so pick first the smallest one for example and check if this one is um just a concatenation of it if S2 is equal to t plus T so this would be our t plus T in this case no because it's not a right and so it's not so we try and of course we check also if it's a concatenation for S1 and it's not because the first thing we find is B different so we try a larger prefix a b that's not the case either for that's not a divider of S2 another divider of S1 so we try a bigger one so we try ABC and that's actually a divider of S2 because it's one concatenation and it's a divider of S1 because it's two concatenations and so this one is um the large this one is a divider so we have potentially our T is potentially equal to ABC but we need to find the largest so we keep going and we try here this one is not we try here and you notice something here there is no use in trying anymore because this is bigger than the length of S2 so it will never be the case right but the other thing also to mention even if as let's say was bigger let's say maybe we had S2 was like this right it's better for us to try from the largest link first right because if we do that we don't have to keep checking once we find a candidate divisor because when we find if we try the longest one first and then try the second one the first one we find is the solution right and so that's also something to keep in mind um now the other thing here is that since we are doing prefixes and we need them to be divisible for each it's better to try the shorter string right because if we try the um the largest string we have the thing where once we get here if we there is no need to try this one because it will never be a solution and so it's better to try the smallest one because if we find a valid prefix for both the first one should be the solution right because it's valid for S2 it's valuable S1 so try all prefixes and use smallest length s of S1 and S2 so that's the one we will use to just pick the prefixes of it um okay so those are a couple of observations there another um another observation is also um if the length of the prefix does not divide the length of the string that means it's not a valid County that it's it can be T what do I mean by that so here for example the length is six and here are the length is three right so for us a prefix of length 2 for example that can never be a divisor for S2 because well you'd have the first sub let's say a b would have the perception be a b but then you have one letter and that letter can never be the prefix right and so um that's also another observation is basically for a tea candidate right let's say the length is L right length of t right so if basically N1 which is the length of S1 is not divisible by L or the length of S2 is not divisible by L that means not possible it's not a compounded country that's right and with this I think we should be able to solve the problem right we can just choose the smallest one of these and try all the prefixes going from longer sorry we are picking the smallest one going from the longest to the shorter one and the first time we find one that divides both um we can just return X right and by how do we check divide both well we can just make sure that first the this is not happening because otherwise it's not divisible otherwise we have the length of t we know it's the prefix of S1 S2 sorry the smallest one which is S2 here so we can just pick the that means our X is just um this sub the prefix up to T which is the length we are trying right and then we can just check is X so we can check if x multiplied by the number of occurrences of the pre prefix X what's that's just the length divided by L right because this is the prefix we want to check how many times it occurred in N1 so we just get the divide the length we get the length the number of occuruses right basically we have let's say these occurrences of L right and this is N1 right let's say this is 2. what this tells you is and the length of um of n let's say maybe it's six so this tells you that 6 divided by 3 that you have three portions of X right so that's why we are doing this here so we'll multiply X by N1 divided by L and make sure this is equal to S1 and just check that also X um and 2 divided by L is also equal to S2 and that's pretty much it or we can check also if this is not the case then we continue and so that the last condition is basically um guaranteed that X is a valid um uh common user right um so that's pretty much the idea here now let's code it and make sure it passes test cases um okay so let's cut this solution up so what we need is first we said we want to just have the length of the two strings so this one is the length of S1 let me just rename this to S1 this one to S2 and we need the length of S2 right and then we as I said we want S1 we want to guarantee that S1 is smallest one this is just basically to make it easier uh for us to um to check always the smallest string and so if I'm just going to guarantee that S1 is always the smallest one so N1 and 2 and or we can guarantee that S2 is the smallest one whichever you want I will go with S1 for now and then we return self that we just call this again with the so this is if it's bigger so that we guarantee is the smallest one um we pass s two S1 and this will basically make sure the first parameter is always the smallest one okay so now we can do our actual algorithm so we'll just say the length and do we want to say go in decreasing order as we said through that as soon as we find it we can return it we start out with the full length prefix and we go until 0 which tells us um open one letter and we do we decrement by minus one each time okay and now we want to check if it's the first condition that we mentioned in the overview which is if it's not divisible then that means it's not a solution and this is for either S1 or S2 so if it's not divisible we can just go to the next length and try it right the other condition is if we actually try so what is X x is just the prefix of S1 right of length l so we can just try and see multiplied by what's are the number of concatenations for S1 well we said it's just N1 divided by L if this is different than S1 that means it's not a solution right so if you have ABC and you try to concatenate it by the number of time the number of copies you need and it's not equal let's say maybe you have something like this okay so let's say you have ABC ABD right so we determined that we need three copies of let's say x is equal to ABC we determine that we need three copies right but we need to check actually if they are or equal and so we do ABC multiplied by three copies that we said this is where this returns us and this gives us ABC and then we need to check that it's actually equal to S1 in this case it won't be if it was C here it will right and so that's why we do this and we do a similar thing for S2 so divided by L this is different than S2 and then if this is the case we want to skip and try the next length the next shorter length but otherwise if these two conditions are not happening that means it's actually equal and the length is actually divisible and so this is the solution and since we went from the biggest to largest we know this is the largest one so we'll return it now if we don't find the solution we go through the loop and each time we kept getting that it's not a solution that means it's similar to our third example here and we just need to return energy strain so that's what we do here return empty string um yeah so here we actually need R because if either one is not um it doesn't match then we should return then we should go to the next length right so even if s match it and let's say S2 was ABC ABD if the S2 doesn't match we should continue to the next length right so let's try this and now let's submit and this passes right now in terms of time complexity you are doing only one Loop here right so it's oven and yeah and this is just cause the same function once it calls it only once because once we pass the smallest one we are done okay um yeah so that's pretty much it for today's problem please like And subscribe and see you on the next one bye
|
Greatest Common Divisor of Strings
|
binary-prefix-divisible-by-5
|
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters.
|
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
|
Array
|
Easy
| null |
1,704 |
hey everybody this is Larry this is day 12 of the Leo d challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem today we're getting a Yeezy problem 1704 determine if string halves are alike and it seems like we've done this problem before and maybe I guess me so I probably already have a video out so I'm going to try to do a premium prom after this let's see you're given a string as of even length split the string the two halv of Eco length and let a be the first half and B in the second half two Str are like there the same number of rows and that's it right all right I mean uh yeah it's a really weird problem but not super tough right so I mean there a couple things you can do uh I mean this is all implementation so we just kind of try to figure out what we want to do right um so maybe we have a uh you know uh yeah maybe just like get um get vows right or get R count of some string and then we can return s uh to lower case I think it's too low okay or is it too lower maybe um. count uh I think count returns um a function right maybe I'm am I thinking of something else I don't know right so maybe something like that and then now we're going to do get WS of s the first half uh let's say n is equal length of s then we can do and then just for and this is python stuff um H Oops why did I write it that way uh it's low no this a oh it's low I think I'm thinking of another language maybe even see uh I thought count would return a thing there was something that returns a thing uh I've been so far to function um count oh count return to string or I guess something that's a new thing count Lambda there is like a thing with the Lambda I do but I guess it's just some which is that go a little bit weird or I mean it wouldn't be this way it would be something like for um something like that right uh yeah and let's give a quick submit unless I kind of did something weird should okay uh 1382 day Tri I got it wrong last time how did I get it wrong last time like oh I just didn't do the halfs at all wow Larry just didn't read the problem I guess uh but yeah okay I mean how is this wrong oh because I put s. lower here and then I didn't actually convert s to S lower uh I think I regly remember this during the contest I don't know if that was the contest one but I remember just being really sad about it because that was just such a silly 5 minute penal but any case yeah um this is going to be linear time linear space I think just because of the way that we wrote it but of course you can do it with a counter and it'll be constant space you should be able to doing constant space if you're not lazy but uh yeah uh I mean I'm not going to keep you that long this is a very silly problem hopefully you get it if not let me know in the comments and let me know you know what I should be going over but today at least for this problem that's what I have so I'll see you soon stay good stay healthy to good mental health I'll see you later and take care bye-bye
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
368 |
hello and welcome to my channel so today let's look at the daily challenging question they call the 368 largest the visible subset given such subset of distinct pos positive integers norms return the largest subset answer such that every pair answer i answer j of elements in this subset satisfy the answer i um more the answer j is zero or answer j more the answer i zero if there are multiple solutions return any of them so the input uh nums one two three and the output uh can be either one two or one three so in the one two that each element is a uh is a divisible by two so i like also in the uh in the one three it's the same like a y is divisible by three but the two is not divisible by three so two cannot be put into the one three output and uh similarly one two example two one two four eight so one before it is uh all each element the one two four are all like a factor of eight so they are actually in the same uh sub uh divisible subset so the answer the question is asking you to return the largest divisible subset so the number length is between one and one thousand so this has a like an indication that the uh the n square solution will still work and uh so num size uh this means the num zero will be integer like in the integer range a positive integer like between one the two times uh ten to the power of nine and all the integers in norms are unique so there is no duplicate yeah so this question um we can use the dynamic programming dp approach and uh so this step one is a sword it's it knows step 2 um i don't know yeah we need for the dp we needed to have a uh trans transit function right so we needed to derive this uh um derive this dp array so the dp array we can call the dpi and i is a dpi the largest divisible subset ends with the num xy and also included it needs to include numsai then we can derive the equation so the dpi is a dp dpj um plus one so dpi will be the max dpj plus one for j uh smaller than i and uh norms i more the nouns j is zero so this is the transit function so we need to uh traverse all the enumerate the order js smaller and check if normal j is a uh is a is effect of num zeit and we can update the norms uh dpi uh and also the initial condition this is the transit function and the initial condition is a initial condition is order dpi is there is a one because the smallest the derivative of subset of ending with numsar actually is a minimum is one and uh so this is a like how we call together the max the size of the largest derivative subset so there's a still a little trick that we needed to use to get to print out the largest subset not just a derivable subset but yeah i will show you what in the implementation but the time complexity here is a it will be s graph because there is a double loop for i is a uh from zero to n minus one and the j is uh from zero to uh to i minus one so it will be n square under the time this is the time so and the space is uh it will be om because the dp array will have only like n elements um yeah so now let's start implementing the this firstly i will uh getting the code for the getting the max uh max size of a divisible subset then i will show you how to print it out uh so firstly sorting the norms so define this dp yeah can you end i can't end from the norm's length and dp so then we can use arrays dot field dp1 to initialize all the dp element as a one then next we can start the iterating from i to i minus 12 and the inside loop is uh from j to j i j uh until i minus one so then so here if uh nouns uh i more than norms j is not zero then which means uh it's not satisfying the condition so we just continue um otherwise we can started updating so dp dpi will be math.max math.max math.max dpi so uh dpj plus one so after this uh all done then the dp but i don't know we don't know that uh the maximum or divisible subsider is ending with which index with which elements so we want to we need to check all the end element so we actually can have a max length uh dpi so yeah so this is the to getting them the size of the largest divisible subset but how do we print it to print in that we actually we can use another we can use a helper array called prius which is the same size as the dp so the previous uh using kind of ends and then the press will we will fill it with oil with minus one so what the previous does is it will it so what the previous does is it will record the path to get into the max length okay to getting the getting to the largest divisible subset so um so here if we have updated the dpi we just want to do a check so if it's updated then the previous actually will point the to j previous i will be j so the uh and um yeah and also here if the max length is uh equal to dpi then we need to record the index so we can use another kind of max in max index so which means the max index is at a um at i so after this loop is done the max index will point in the last element of last index of the largest divisible subset and then now we can uh we need to print it out right so we need to have our other answer list we can define an id called uh to assign the index max index value so while id is not minus one then time we can um we can go from id to the previous one press index and then um we can add append the nums id to the answers and because of this one in this loop we are appending the largest element firstly smallest elements uh lastly so we need a reverse uh reverseless answer so that uh this it will be in the order of small to large and then we return the answers so um so let's uh check if this is a code that has anything wrong with the using the oj okay yeah so you know looks uh correct for those two test cases okay cool yeah so uh so the question this question is we use dynamic programming and uh using a 1d dimension dynamic programming array and so the dynamic of tpi will be uh will be actually the size of the largest uh size the size of the largest divisible sunset and with the num size so we have a double um double loop i from uh literally the i to n minus 1 and of j from 0 to i minus 1. so we check uh if the num si is if nouns j is effective num si if it is a vector then we uh we can update the dpi so in then the button still we don't know like which deep which uh index is the largest uh the last element of the largest degree of success so we need to check all the index so here we did that max length and also we have uh we used the previous uh index previously integer array to uh to record the path we got from j to i so this suppress index array will help us to print out the uh all the elements in the largest divisible sub array so let's conclude the time currently the end squares and uh so let's conclude today's session so if you have any question please comment on the video and uh thank you
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
125 |
hey what's up guys it's a nick white tear new attack and coding stuff on twitch and youtube I'm in the libraries there's a lot of people talking around me right now but we're gonna try and do one of these videos really quickly this one this problem is called valenpac valid to palindrome and you'd think it's pretty easy I've done a lot of palindrome videos I did like link lists pound rum and stuff it is really easy it's the same method is the other ones you're using two pointers which is a lot of palindrome problems the only difference about this one is they do throw in this little trick here given a string determine if it is a palindrome and you guys know a palindrome just means a word that spelled backwards the same way as well forwards a racecar would be a racecar backward so that would be a palindrome right so though the way we do this is we just have two pointers one at the beginning and one at the end and we move inwards letter by letter one going backwards through the word one going forward through the word and we make sure the letters are the same so you know we would have this we'd have a pointer here and you know R and R would have to be the same a and a it would have to be the same C and see what F again same and so on that's the method for doing it now for alphanumeric characters only and ignoring cases all we're gonna have to do is basically remove all the punctuation from this string first of all so we're gonna do is we're gonna have a you know we're gonna have this little string you can call whatever you want you could call it you know remove or the you know fixed string let's call it right so we have this thing called fixed string and then we're gonna want to do for char C in s so we're gonna hit a rake through this oh no s to char a I always forget that so you do to char array so we have this array of characters of the string s we iterate through character by character if and then use the character class dot is digits and you pass in the character current character or character dot is letter I think it's letter crap think letter then we can do fixed string add it to our fixed string right cuz that's the stuff we want to look at alphanumeric digits or letter alright so plus equals C right so that's gonna have our fixed string exactly where we want it now the only other thing we had to do was case oh we want to ignore case so there's a built-in to ignore case so there's a built-in to ignore case so there's a built-in method in Java called two lower case so we'll just do fixed string equals fixed string to lower case now we could do Claire our a pointer and B pointer so we'll have a pointer is equal to zero just like I said of pinning a B pointer is equal to now we're gonna be doing this on fixed string now fix string length minus 1 because we're you know use the indices and then we'll do well a pointer is less than or equal to B pointer because we're going until we get to the middle obviously we don't have to traverse the whole thing that's why we use pointers because it cuts the search time down substantially and then all we have to do from here on out is check if fix trip string dot char at a pointer is not equal 6 string dot char at B pointer then there's a problem right that's what I'm saying when we go through if the letters aren't the same at the beginning in the end as we move inwards then that is not a palindrome so we're gonna return false and if we make it through that whole thing will return true and now the only last thing we have to do is increment our a pointer by one each time and decrement our B pliner to move in where it's towards each other in this hopefully will work first time and it does it works perfectly first try yeah what it so one more time what do we do is we take the initial string because we're only looking at alphanumeric letters and lowercase characters or I guess you can make them all up case but we remake the string so that our initial string is s we go through we only grab the letters and numbers we throw it into our new string variable called fixed string then we make all the letters lowercase you could essentially make them uppercase too we just have to have them all in one case because we do not care about case here or ignoring it yep so it still works with uppercase and then you have the a pointer at the beginning and the B pointer at the end you move inwards and you make sure all the letters are the same so we can make sure it's a palindrome and once we get to the middle which is this case we break out and we return true otherwise we'd get a false that's pretty much it pretty straightforward just always be aware that you read the problem when you get problems especially in interviews and stuff because you do want to check for little cases like these like alphanumeric and stuff like that so that you can account for that stuff I think you guys for watching and check out the other problems because I do them all and I'll see you guys
|
Valid Palindrome
|
valid-palindrome
|
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "A man, a plan, a canal: Panama "
**Output:** true
**Explanation:** "amanaplanacanalpanama " is a palindrome.
**Example 2:**
**Input:** s = "race a car "
**Output:** false
**Explanation:** "raceacar " is not a palindrome.
**Example 3:**
**Input:** s = " "
**Output:** true
**Explanation:** s is an empty string " " after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
**Constraints:**
* `1 <= s.length <= 2 * 105`
* `s` consists only of printable ASCII characters.
| null |
Two Pointers,String
|
Easy
|
234,680,2130,2231
|
7 |
guys so in this video we'll look at reverse integer problem so uh in this problem we are given a third bit sign integer and we need to return the reverse of that integer so let's look at these examples so if we are given one two three four five then we need to return five four three two one if we are given minus six seven eight nine then we need to return minus nine seven eight six and if we are written if we are given this number which is the maximum value or 32 bit integer can hold then we need to return zero y zero so let's see this in case if a reverse causes overflow then return zero so if we try to reverse this number obviously the first digits would be like starting digits would be seven four six three which is obviously bigger than this number so a 32-bit integer cannot hold number so a 32-bit integer cannot hold number so a 32-bit integer cannot hold this number so it'll cause overflow so we need to return zero so uh that's the second condition so uh anyways it's still a pretty straightforward easy problem however what makes it interesting is this condition so our algorithm should have should use only 32-bit side integers we should not only 32-bit side integers we should not only 32-bit side integers we should not use long double or float so this is what makes it interesting so let's see how we'll do it and then we'll come back and run our code so uh to solve this reverse integer problem we'll take these two integers one two three four five and the max third bit max positive value as our base case and we'll see how to solve it so as you can imagine uh we'll take uh to solve this problem what we'll do is we'll take the last digit of the number put into the other number and then pick the second last digit multiply that number by 10 and then add that second last digit then keep doing that process and then the numbers would be reversed so uh let's see how we do it so uh this is the formula for it uh we'll just uh ignore the blue part right now and we'll do rest and see uh what this is and then uh finish up so let's see this number so our number is x which is one two three four five right so uh right now our temp and result are zero so now what we do is we take the last digit from x which is x mod 10 so last digit would be 5 and what we do is we do result into 10 plus last widget so temp would be 5 right and then we put temp into results so this would be 5 and then we divide x by 10 so x would be 1 2 3 4 and then we repeat the process we again take the last digit which now would be 4 we do result into 10 plus last digit so result into 10 plus last digit 54. we copied 54 and then we do x divided by 10. so uh just keep doing this process so this will keep happening like 3 will 5 43 x will become 12 then again take the last digit multiply this by 10 and add 2 x divided by 10 and then eventually this will be reversed and x would be zero and then we'll come out of the loop and we'll return result so a simple straight forwarding now the interesting thing that makes it interesting is uh the overflow part so this is where this thing will come in play so let's look at other example and let's see how we'll handle overflow okay so now when we take this number this is how our flow would look like based on our formula so uh initially the numbers are 0 we take last digit we multiply the number by 10 and then add last digit and we keep doing that so until we reach at this stage so uh now let's look at this formula in blue so if you look at these two steps basically what we are doing is we are reversing this step so uh let's take last digit on this side so it will become temp minus last digit and then if we take multiplication by 10 it will become division by 10 so we are doing exactly same thing 10 minus last digit and divide by 10 so we are just taking checking that if the new number that we got if we reverse that all those things does it equal to result again or not so why are we doing that because uh when we're at the last digit of this number uh before this our number is 746384741 and our result is this now uh we know this is like almost like uh reaching the max value of this like if we multiply this by 10 it'll overflow so that's exactly what happens so we get last digit as 2 our result is this so we multiply result by 10 and then we add last digit 2. so what happens is this causes the number to overflow the 32 bits so we get some random junk unexpected value which is not expecting 2 here so now when we try to reverse engineer this number when we say this minus last rigid which is 2 divided by 10 is this equal to this which obviously not then we say return 0. so that's how we check or if overflow happened or not we just reverse engineer the process and we say oh by the way i think overflow happened because the number is not coming matching to this so uh that's how we'll check overflow so uh i do want to mention that what we are doing is we are causing the overflow and then we are checking has the overflow happened uh there is one more way to check overflow even before causing it uh so let's look at that way on how we do that uh i feel that is a better approach because over here we are doing like multiplication and addition to get our number and then we are doing division everything so uh it's an unnecessary step if we can like check beforehand itself whether overflow is going to happen or not so let's see how we'll do that okay so now uh we'll look at other way of checking overflow so basically uh even before overflow happens we'll say that okay overflow will happen now based on the numbers and the condition so let's see how we'll do that so uh this is how basically we'll do that so we'll find out a limit so basically let's say this is our max 32 bit value so now what we do is we divide this by 10 so we simply remove the seven so our limit is two one four seven four eight three six four so now we know that if any number in this process if any number reaches this value like if it's greater than this value and if we are going to multiply 10 to that number it would be more than this so we know that right let's say if my number is let's say if this was 3 1 4 7 4 8 3 6 4 if this is my number in this process and if i multiply this by 10 and plus any last digit i know that it will be greater than this 32-bit signed integer so i when i'm when 32-bit signed integer so i when i'm when 32-bit signed integer so i when i'm when my number reaches this or more than this i can stop my processing and i can say that overflow is going to happen so return zero so uh yeah let's look at this so uh yeah there's just one more condition like if we uh if our number reaches exactly this value like two one four seven four eight three six four then what we need to do is we need to additionally check what is the incoming digit so if incoming digit is seven then we can say yes you can multiply this number by 10 and you can add 7 and you'll get this but if our result is this and incoming digit or the last digit is 8 or 9 then we know that we'll have overflow so basically these will be the two conditions to check if overflow has happened if our result which we are calculating if it's greater than limit or if result is equal to limit but the last digit is greater than this uh seven so then we can say that yes if you keep processing overflow will happen and uh you'll have unexpected results so better return zero so uh there you go so uh yeah you feel free to have implement any approach uh obviously the previous one is easier to code and quicker to code uh this will take uh more time so based on our condition based on your condition uh do whichever you feel comfortable with uh i do want to mention that uh there will be us there will be a special case uh for negative numbers if we for have this approach because uh in case of negative uh value the minimum value that a 32-bit integer the minimum value that a 32-bit integer the minimum value that a 32-bit integer can have is so you notice that there is just one more so instead of seven it's eight so uh overall the approach remains same we just need to make sure that if it's a negative number then we're taking care of this uh last digit and we are making sure that last date is greater than eight so that's all so uh let's look at the code uh let's run the code and make sure that whatever we did uh runs successfully okay so this is our final code we have our main method which is calling the reverse method on these three numbers so uh let's look at our rails method so uh similar to what we discussed on the whiteboard the first approach uh last digit mod 10 and then take temp check if overflows happened if not then copy to result and reduce x by dividing it 10 and then return result so uh let's run it let's make sure we get the expected output and then we'll look at the second approach so uh yeah there's a console line you guys can use it if you want to debug your code so let's make sure that's commented and we got a clean output yeah there you go so uh the numbers that we expected and uh the last one causes overflow so we're returning zero so let's look at the second approach so i've just named it reverse too so let's reverse to reverse two so uh yeah this is the approach of uh checking the overflow before happening so we're going to say that yes if we keep continuing then overflow will happen so uh yeah exactly similar to what we discussed uh we recalculate the limit digit and we check if the result is greater than limit or if it result is equal to limit but the last digit is greater than the limit digit now as we said like if the number is negative in mean value is one greater than by into max value if you ignore the sign so if the number is negative then we are adding one to our limit digit and what we are doing is we are taking absolute value of x so if it's x is negative we remove the negative sign and before returning the result we put the negative sign back so uh exactly similar to what we discussed so let's make sure that this also runs fine and then that should be it so yeah there you go uh expected output so uh that's it for this video guys uh i do have like a java code also over there so both the uh files would be there in the description link to both the files so if you guys like the video learn something new uh give a thumbs up on the video let me know your feedback suggestion in comments and then subscribe for more videos
|
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
|
55 |
Hello friends, today's question is jump game. In this question, we are given an object named Namas and inside it we have to find whether we can go out of the index from Eric's last index while jumping or not. So if from the first index we have to start from zero and the value of zero index is 2 minutes how many jumps can we do or at one position then the first solution will be the time complexity of our recursive solution will be and which is power n, this is very high complexity. If it is internally prospective, then we will optimize it a bit, we will use it for memorization, after memorization, its type will be Tu Ki Power N. At this time also there is a lot of time complexity, so for this we will go to change the Greedy Algo, we will use Cadence Algorithm. If we solve it with Cadence algorithm, its time complexity will be O and space complexity will be O. If you liked our solution then like the video. If you have not subscribed the channel yet then subscribe the channel like this. van
|
Jump Game
|
jump-game
|
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** true
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[3,2,1,0,4\]
**Output:** false
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 105`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
45,1428,2001
|
1,888 |
hey everyone welcome back and let's write some more neat code today so today let's solve minimum number of flips to make the binary string alternating so this is a problem from today's leak code contest and i'm going to show you the big o of n squared time complexity solution and i'm going to show you how you can take that solution eliminate the repeated work and get a sliding window linear time solution and it's a pretty clever solution at least there's some clever ways to code it up so we're given a binary string and we're allowed to make two operations on it let's see our string looks something like this we're allowed to either take each value such as this first one and flip it to a zero that's the type two operation we're allowed to do that's pretty simple right we can just take any of these and then flip them to the opposite value right zero to a one or one to a zero and there's another operation we can also do which is basically take an element from the beginning and move it to the end so if we did that then we would get a new string that looks like this and we can do that operation as many times as we want if we do it again we'll get something like 0 one right so we can do it as many times as we want and notice if we do it two consecutive times in a row if we take both of the characters movement to the end where you know that's basically what we're doing if we do the operation twice we're basically taking a prefix from the string of size 2 and moving it to the end so really there's only n times if we do that operation n total times we'll end up with the exact same string right if we just take all of these values move them to the end we'll get that exact same string right that makes sense so far so in reality this remove operation is basically allowing us to take any prefix from the string and move it to the end the only thing we want to return is the minimum number of type 2 operations that it would take for us to take the input string and make it alternating so for example these two strings are alternating right 1 0 basically every value is the opposite so 1 0 etc right this one's obviously not alternating it has two consecutive zeros so basically we just want the minimum number of type 2 operations so a type 1 operation is free for us right so in this example we're given a input string of size six so the first question you might have is how can you even determine the number of operations it would take to make a string alternating well the there's a lot of ways you might try and i'll tell you right now the easiest way is just think about it in terms of this string is size six there's only two strings of size six that are alternating either it's going to start with a zero in which case this is what the alternating string of size 6 would look like or it's going to start with a 1 in which case this is what it would look like so that's so basically we're going to compare a string s to either of these right see what's the number of differences so for example if we wanted to know how many operations would it take to make this string equal to this one we would just count the number of differences so here you can see this is a difference and that's it so i take two operations for this to become like that well how many operations would it take for this to become like this one it would take one operation two operations three operations and four operations right so clearly it'll take less changes for us to take this one and turn it into that one it'll take two rather than four but what i showed you so far is if we directly take this string s and just try to make it flip as many the minimum number of times but we haven't even tried using a type 1 operation let me show you now what the brute force would be if we did use a type 1 operation that's the n squared solution that i'm going to show you the repeated work we can eliminate so as i previously mentioned for us to take this entire string and count how many operations what's the minimum number of flips it would take for us to turn it into either of these target strings right these are our target strings because these two strings are alternating so we can compute the minimum number of operations flips it would take to do that in o of n time right but we also know this we are allowed to take any prefix from this string move it to the end in which case we would get you know this we'd have that one and move it to the end so this is going to be the new string and then for that same for this new string now we want to do that same operation now check what's the minimum number of flips it would take to turn into one of these two target strings and once again that's also going to be a big o of n operation and not only that but clearly we can try that for every single prefix in the string move it to the end one and then try that same thing again and again so let's say we did a prefix of one and we shifted it to the end right and of course we could do that for every single prefix so now if we're doing it like this we're gonna do the exact same thing that i mentioned we're gonna check okay this first character does it match with this one and do that for every single character and basically we're counting the number of differences right or in other words the number of flips it would take for us to match this target string of course what i just drawed we could do the exact same on the bottom target string as well and of course we're going to try to find the minimum of those two difference counts now my question to you is have you noticed the repeated work that we're doing notice how in the first go-around we notice how in the first go-around we notice how in the first go-around we were taking these six and then comparing it to the first target string and to the second start target string right each value was being compared just like this and now we're doing the exact same thing just we changed the string by one so when you look at these five and we're counting the number of differences either from this alternating string or from this alternating string the number of differences the minimum number of differences from this one will actually be the exact same so why should we have to run through these five elements again when really we just want to know what's the new minimum number of differences for this portion of the string and if we can eliminate this repeated work well then we'll actually only have an o of one operation every time we add a new prefix and this is the part where we're gonna do a little bit of cleverness to make the code a lot easier for us wouldn't it be easier if this string that we're comparing to these two target strings if they actually lined up nicely like if we could just take this and then compare it here well we can do that because we can just take these two alternating target strings and just extend them as much as we need to right so we can take this add some more alternating characters and do the same thing with the other alternating target string so let's just quickly count for this original the first six elements how many differences were there with this alternating string well here's one difference here's a second difference here's a third difference and here's a fourth difference so initially there were four differences with the alternating string that starts at zero how many differences with the alternating string that starts at one well here there's a difference and in no other places are there differences so initially there were two differences so notice how now as we add this character we're doing the same thing for these six elements but clearly if we're counting the number of differences from these five elements with these five elements they stay the exact same except notice how now we're no longer looking at the first element right was there a difference here yes there was a difference here so as we removed that character we basically took the number of differences and decremented it by one right so now the differences are actually three but as you can see over here when we added this element we also added one more difference because these two values are different so actually the number of differences is gonna stay at four even with this new string and of course we would do that exact same thing with the bottom alternating string as well right we would see okay over here we don't have to decrement the number of differences because there was no difference here initially and over here as the character that we added you can see again we didn't add any more differences either so the number of differences here is also going to stay constant at 2. and at this point you can probably see we're just going to be continuing that exact same thing right so now we would take another character from the beginning move it at the end it's a 1 again so next these six elements would be our string so instead of having to manually do this manually take every single portion of the string and add it to the end a clever way to do this that i actually did not come up with i saw it on the leak code disqus section is once again just do what we kind of did down here right we just extended these two alternating strings let's do the same thing up here but instead just take the entire string add it to the end right so this is one zero we'll take one these three ones zero and now as we go through windows of length six right this is one window etc every window is basically gonna be a portion of the string and the other portion of the string which was the prefix moved to the end right so as long as our window is size six we're basically taking a prefix that was originally at the beginning and moving it to the end and we'll do that all the way until we get to the last sliding window of length six and as you can see this sliding window is just the exact same as the original string itself and even these two target strings are the exact same as the target strings from the beginning so that's the main idea once you can kind of see how this repeated work is eliminated coding the solution itself is not that bad i will admit though it's pretty hard to come up with this idea of adding the string to itself since we're doing a sliding window this problem is going to be big o of n complexity so now let's actually code it up so first thing i'm going to do is just get the original length of this string because that's the what the size of our window is going to be then of course i am going to just take it and add it to itself as i mentioned previously and we're also going to want two alternating strings which are basically our target strings right so we know that the two types of alternating strings could either be one that's starting with zero or one that's starting with one and we want both of these target strings to be the same length as this new s string that we built basically twice the length of the original s string so a way to get these values to alternate is basically we can add zero to one of them if i is an even number if it's odd then we'll just add a one so this will make sure that it alternates at every iteration of the loop and for the second alternating string we're basically going to do the opposite over here we want that one to start with a one so i'm going to initialize a result basically just going to give it a default value of the length of s or you could just do float infinity because remember we want this to start out as a big number because ultimately we're trying to minimize the number of flips i'll be keeping track of two variables diff 1 and diff two as i showed in the drawing basically the number of differences or the number of flips it would take for us to take s and make it the same as alternating one that's diff one and alternating two which is diff two since this is a sliding window i'm to keep track of a left pointer and the right pointer is going to be iterating through every single position in the length of s and for every single character we encounter like basically at position r if it's different then alternating one remember we're ultimately just counting the number of differences so if it's different than alternating one at position r then we're going to be incrementing the diff one count right we encountered a new character that has a difference and we're just going to do the exact same thing with the alternating string to alt two if it's a difference then we increment diff two count now if the size of our window is too big of course right if it's greater than six which was in the example but if it's greater than n which was our original size then we're going to want to decrement the left pointer right so let's get the size of the window by right minus left plus 1. if that's greater than n then we have to decrement left right we have to take left or not decrement it we have to take left and shift it over to the right by one which is basically incrementing it but before we increment it we want to make sure to update our diff one and diff two counts so if there was originally a difference in our string at position left between alternating one at position left so if there was a difference between these two now there's no longer going to be a difference right so basically what we can say is we're going to decrement diff one count by one and we're going to do the exact same thing for the second alternating string so just copy paste just update the variables so after this our window should not be too large and the diff counts should be updated so and we're potentially going to be updating our result right but we only want to be updating the result if our window right minus left plus 1 the size of our window is exactly equal to n because initially remember we start out with left and right at index 0 so it's going to be too small of a window we want to make sure it's exactly n if it is that's when we can actually update our result and we want to minimize our results so we're going to take the minimum of itself diff 1 and diff two so as you can see this is basically you know the idea is pretty much a brute force solution but we are eliminating that repeated work by using the sliding window technique and that being said after all that we can just go ahead and return our result i forgot to at this beginning we're not setting alt one and alt two to a single character we're adding a character each time we're adding a zero or adding a one depending on whether it's odd or even right we want those to be alternating so i'm really sorry about that bug hopefully you caught it by yourself so it didn't trip you up too much but as you can see the solution does work it's pretty efficient it is a linear time solution so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Minimum Number of Flips to Make the Binary String Alternating
|
find-nearest-point-that-has-the-same-x-or-y-coordinate
|
You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.
Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._
The string is called **alternating** if no two adjacent characters are equal.
* For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.
**Example 1:**
**Input:** s = "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s = "100011 ".
Then, use the second operation on the third and sixth elements to make s = "101010 ".
**Example 2:**
**Input:** s = "010 "
**Output:** 0
**Explanation**: The string is already alternating.
**Example 3:**
**Input:** s = "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s = "1010 ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
|
Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location.
|
Array
|
Easy
|
1014
|
78 |
today's question the code78 subsets given an integer array numbers of unique elements return all possible subsets the power set the solution set must not contain duplicate subsets return the solution in any order so here we have an example we have a nums array which is one two three and then we just want to output all possible subsets and again these are unique elements constraints num stock length is great they're not equal to one and less than or equal to ten let's have a look at how we'd work this out so we have a numbs array we need to populate a result array and initially we know that every solution is going to contain an empty array so we can just initialize that result array with an empty array to begin with now because it's asking for all possible subsets this will be another recursive solution so we need to loop through nums and we need to recurse through each solution to find all potential solutions let's say we take one okay so we've taken one two and three is left we're going to have a current array which is going to store the values which we take one and as soon as we've taken it we are going to push it into results so we have taken one okay we have two and three left we take two current is updated so at this position current is equal to one two we push directly into results value of current this will give us three left and then we can take three at this position it's going to be nothing left here but current at this position is going to equal one two and three as soon as we add to current we push into results so we have one two three now i've reached the end of this so we backtrack we get to here we have three as a potential solution so we take three and there is nothing else in here so current at this position is one and three as soon as we add three into current we push it into results and then three now we backtrack we check this level there's nowhere else to go so we go back up to this level we move over to two so current is now emptied we take two we have three left current is currently at two so we push two in here we are only moving incrementally through this so we don't include one here because that will include duplicates and then we take three so we add that to current two and three and then we push that into results two and three and then we are at the end of this stage so we backtrack we get to this level we move over to three we take three current is now three because we emptied it whilst backtracking and now we can push this into the result array this is now at the end of this stage so we backtrack and we realize there's nowhere else to go so we exit that for loop and then we just return results so that's the tree structure of how this solution is formed and in terms of time complexity what we have the time is we have n times 2 to the power of n where n is the numbers within the nums array so we have the initial loop here which is going to equal the n and then the subsets all throughout here is going to equal this exponential part since each element could be absent or present and in terms of space we have of n where we are allocating space to the current array and also just to note we do not include the result array in the computation of the space complexity this is ignored so let's try implementing this so as we stated we need a result array and we're going to initialize this as an array containing a single array we can create the function the backtracking recursive function and we can call it with the initial index which is going to be zero and an empty array which is going to be the current value which is going to contain all of the potential solutions as we move through this recursive call so we can call this index and we can call this current within here what we're going to do is we're going to jump straight into the for loop so i is going to be equal to index i is less than nums.length and like we said less than nums.length and like we said less than nums.length and like we said in our explanation we have to push into current and nums at i and then immediately after that we push that value into results and we create a copy of it because we are going to be manipulating current now and then we create the recursive call so dfs we're going to be incrementing index because we want the next potential solution and then we pass in the current value which we just updated in order to make sure that this finds all the solutions we are going to backtrack so just say current.pop backtrack so just say current.pop backtrack so just say current.pop and lastly we need to return result see if that's worked go submit it and there you go
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
188 |
hello everyone welcome to learn overflow in this video we'll discuss today's liquid problem that is the best time to buy sell stock four okay so this is a fourth level problem and obviously there are other three levels problem and i will make a videos on them as well so this is a hard level problem and we'll understand what this question is asking us to do and how we can solve a question like this fine so that's what you will understand so if you're moving on if you haven't subscribed to this channel make sure to subscribe to london workflow for regular lit code videos like this so the question says you were keeping an integer prices where each of the price is the current day price and an integer k okay prices and integer so it's like price i is the price of a given stock on i have today right so that's the normal uh array of what the arrangement so that's simply represent the price of the stock of that day right so we need to find the maximum profit so the idea is to find the maximum profit uh why you can achieve you may complete at most k transactions okay so we may at most go ahead with k number of transactions so that's the key being given to us and with k number transaction we need to find the maximum profit remember this is not exactly key number of transaction this is like at most k number so that basically means less than equal to k so that's a sales value fine so this is the question asking us to and then an important note this is really important so the question uh the in notes is you may engage you may not engage in multiple transactions so what does that mean that you must sell the stuff before you buy so like the process cannot be like you buy a stock then you again buy a stock then you even buy a stock and then you sell all at once so this cannot be possible so the thing is like if you buy a stock you need to sell it next then you can buy again and then you need to sell it next and this uh unit continues again and again right so this is the uh step that should be followed now um let's look at an example uh see the first example given to us this may not be valid for uh to understand all the conditions properly right so uh this still let's understand this question and like this example one simply says that the prices are two four and one okay and it's like if you buy on day one okay so what's the idea is if you uh on day one can you sell okay can you start with selling a day one no because if you start with selling on day one you don't have a buy before that you don't have to stock you cannot say and sell it fine uh like you must buy before you fine yeah so that's the idea then so for day one it's like you cannot sell a stock right on from day two onwards you made stellar stock so it's like further you see on day two the price increases you see the price getting increased so once the price is getting increased you see you can earn a profit out here so what's the profit you can earn and you have profit of two fine and then from day two to day three to see that the price actually gets decreased and you cannot earn even if you have bought it on day one and uh you want to sell it on day three you cannot earn much right so this is the question now for the question if you look ahead with the logic of the k is uh given us two and it says like we can complete at most key transactions so how many transactions we can actually do here we can actually do uh one transaction like y1 2 and 74 and the profit will be two so that's the maximum profit we can add so this is not a proper case that highlights all the corner cases so let's understand with some other cases fine uh let me just erase up this uh totally and down now if you look okay let's go ahead this example fine so let's take a timeline this is the timeline for us right and it says we are at day three uh like day one then that this is at three fine so this is a day one at three and then our price decreases to uh two fine so that's day two we got two and then the price increases to something like uh six fine so that's the six and then our price decreases to something like uh five okay let's just draw this graph it will be much helpful to understand then our price decreases to something like exactly zero fine so that's the zero we have and then our price increases to three back again fine so that's the three we have now uh see exactly what's happening in this okay we uh we can do a maximum transaction of two types okay so it now what are your targets or targets will be somewhere uh if you are doing a maximum of our like max of our like profit maximum profit what we are doing we will look for local minimum and local maxima fine what is the local minimum we have local minima is like two three is not the minimum right it's like uh if we're going considering uh till this point fine let's see uh we have two local minima and we have six that's the local max so what's the price difference is four so that's our profit that we cannot next it's going down so can we already pop it out here no next we need to look when they get whenever it's against going up fine so whatever second going up it can be like uh we can see this up it gives us a profit of something like three so four plus three comes out to be the seven okay so once you draw the diagram it becomes really easy for us to uh understand it okay now the further question is what can be done okay how should our process be looking but if we have already bought our stock on let's say on day one what's the profit that we're going to make a profit of three so if you have bought a stock on day one we cannot buy on day two i mean uh that's what he says like you must sell the stock before you buy again right so here you can understand that we cannot buy our stock on date one rather we need to buy one stock on day two to find out uh the what will be the uh final like to maximize our profit okay because in that case the previous class they don't maximize so what will be our uh states one step we are here with um like no stock in hand fine we can have two things either uh buy like uh i mean either buy okay and move to a state of having stock five hs i mean having stock fine or you can with no stock in hand you can simply uh hold the position like you don't uh you don't buy or sell anything you simply hold down your client position and you simply uh remain in your state that you have no stocks in it right so once you buy a stock you can have two ideas one uh like you can sell the stock fine you can sell your all the stocks because you need to sell all the stocks there's like no you need of like how many stocks you're driving on this road for selling so you can sell the stock or again you can do something like you can hold the stock fine you can hold the stock in the way you can like have a hold over here that you want you will not sell the stock right now you will wait further so this can be your uh situation that may happen fine so what is the i like this it's your state uh diagram okay so either once you have no stock you can hold your current state living in your current state and uh like holding your current stock like with no stop so that will be our after three we are moving to uh we are simply moving to uh two so that's basically we are holding on no stock state that and we are like looking for a price decrease okay and then what else we are then buying our stock at two so that's a state transfer to having our stock and then selling our stock at six five so once we sell our stock at six we are again at the known stock state and then we are uh like uh once our stock is sold at six then what we're doing are we buying at six i like what would be we sold our stock at six so it's no higher routine that you can actually buy a stock after you sell it because you sold it so how why would you buy at six i mean that won't give you a profit right buying at six basically means uh you have already bought a 12 because like if you're sold and bought at a particular position like say you have a sold a stock at six so that gives you profit of things and then you are buying us at six that means you are spending six so what's your net profit becomes zero so that's not a case that we'll be looking at like buy and sell at the same stock price so that would not maximize the profit right now and that basically means you are just holding your current state right so that's not the state we are looking for so once sell the stock we are done with six next we are moving to five so five we are again holding our no stock state because it's like we find the price is going down right now um then we are moving to zero we find the price again went down so uh at zero what we will do we find there's a low price like the no mean local minima is found so at zero we will simply buy a stock fine we just found a minimum so we will zero we buy a stock and further at three we will sell the stock so that gives us the uh kind of uh maximum like profit that gives us a profit well looking at fine now a few things you should know fifth thing is no it's like why i was ignoring the case one this one is the k is two okay and the prices are like the price how many prices are possible it's like how many days are there it's like five day right so how many days a day is like three so in three days like without looking at k how many transactions you can do in this current situation in three days you can actually do like how many transactions uh either you can buy on day one and sale and day two as i said buying and selling on the same days like makes no sense so buy one day one seller day two or buy one day one or sell at day three that's basically one transaction right can you do a second transaction like uh buy a day three and sell at no other days let's go under this right so in a price length of like three does a k value of uh two matters in the window so why is it so look at what's the minimum condition we need for like okay so the idea is how many uh see we need to buy at some price and we need to sell at some different day right so that means if our whole array size must have uh like half the value right so i mean half of the days we buy and half of the day we sell right uh that should be the ideal case so if we do that then what should the k value how many transactions should be possible are we translating if our n be our length of our uh total array then n by two will be our half of that right so half of that you should buy so how many transactions we can do is like our k in case our k is greater than equal to our n by two then does this key have an impact it doesn't have impact because you don't need that number of uh transactions right you simply can go ahead with your current state you don't need that number of transactions it's simply uh the question of uh buy say like best time to buy sell stock uh question number two not question number four like we are at kushner phone but if you look at it to question number two that was the question given to us okay that exactly we need to buy salesforce uh for like whenever the price is possible fine like a number of transactions so that was question number two and if you remember the question number three of this like the other question of question three so question three mentions uh this transaction limit will be two like at most two transactions are only possible for all that is so that is question number uh three now uh here we are just they just change the condition to our k so just look at this idea so if k is greater than equals n by 2 we actually don't care of what k is but if k is less than i mean if k is less than or um n by 2 then the all this thinking all this process comes in right if k is greater than or equal to n by 2 we know that we can perform k number of steps this we are not bothered with that because here it's just like atmosphere right we are not bothered with uh how many transactions are going on okay now what will be our approach to this question like well i hope this is understandable what we are doing in this question now what is our approach so firstly we will have a costly and we'll have a profit of each of the days fine so it will be like we'll check what's the minimum cost that we can uh spend because we if we are earning a profit that means we are also buying some stock that takes tesla costing right so our idea will always be at uh looking at what is the minimum the profit uh sorry minimum the cost we can go ahead and once we are minimizing our cost we will keep looking for maximizing the profit fine so the cost will be minimized and obviously once you maximize the profit we know that uh our selling price is also increasing right maximizing the profit means the difference of cost price and selling prices are increasing right so the selling price is by default increasing so the idea is we should look again and again for minimizing the cost i mean the prices and maximizing the profit right so what we can go ahead with it firstly uh we will simply as it will simply have this uh state diagram right two state one uh that will give us the buys and other that will give us the cells okay you can take it in a different way as also if we're not confident taking the buy answer thinking like this is the cost we are spending for buy and then this is like after sale this is our profit that we are making right you can think it on this way also so like after sales this is the profit like having stock you've sold it so what is this is the profit you actually gain okay and uh you don't have any stock you are buying it okay what is it this is the cost you are spending on it fine so that's the idea so how can it be done fine if you move into the prices that it one by one okay one more one if you move into the prices array and in the price of that for each for like k transactions uh like less than k transaction of key transactions if you go ahead with that what will happen to us we will simply have um uh we'll simply keep checking that our current price a minus one previous profit the previous profit is the amount we have right time for price minus the previous profit should be like the minimum right the minimum of this uh will be our cost right the current price minus uh profit is like the one of the value and the other value is the cost at this position or our current price minus previous profit so that will be that should go ahead with the minimum and the profits will be like current price minus our previously cost what is the previous cost we had so if we subtract this that will be our profit so we know we need to keep checking again to just maximize the profit so this is a pretty easy idea so let's quickly write the code and then you can actually visualize this the thing what i'm trying to say much better so let's quickly write the code okay i think this is like the two million solution a pretty fast solution we get but let's understand this solution okay let's understand what exactly we are doing and what's going on so if you're trying to understand this uh why not add a print statement in between and uh see like what our current steps are doing for us okay so that will be uh much like that will be much easier to understand you know uh so just adding a business statement to just note that the cost of i plus one because this is the cost uh we are doing uh rather like if you are like well we just see the cost for each positions after uh complexity as well what's going on so now further we'll just uh to understand this we'll just add some formatting okay see now if you just look over here what's uh going on in this say we just took a cost and we just stupid profit and we just make our pause to be the max balance and these are the main strengths okay fine now what happened we took each of the prizes in our uh like the given prices that i find uh here in this case this one is going to flip at that fine we're just getting the prices you know given prices at it now what we are going ahead with it like doing with this is uh basically uh something like this see once we have a diagram like what once we put like quarter price then we simply go out going with like i zero to knit going for all the uh transactions possible so we got our current price and we're checking what's the maximum uh we can go ahead with all the transactions we are checking for so uh we got uh i plus one we have the cost of y plus exactly y so cost is k plus one we are just making sure that cos zero is like uh because we need something like profit uh of the previous profit okay i'll tell you why we need this previous profit but since we need this previous profit the futures profit uh previously we had okay so this will help us in something like the current price uh the price we are currently at and minus was previously profit like uh so we are going ahead with i plus one exactly you can see so professor y is like the previous profits we have till now so once we doing this is giving us a current price minus profit is like giving us the idea of how much profit we are making okay uh current price with subtracting the previous profit so that's the uh ideas giving us okay so that's the cost being uh like if our current price is more than our previous profit that means we are just spending that cost okay if you're spending that cost that means uh that's the money being uh going from us right so that's the cost we are finding out so what exactly the formulation we did within the cost of i plus one is like minimum of cost of i plus one what is the cost of y plus one by default is by default max uh integer the max value and then we are doing current price minus profits of i is by default zero because we didn't do anything like a registered field right so graphical y is by default zero so we simply had uh this thing current price was initially three and now you see uh three uh minus profit so y is zero so we've got uh current price being three fine and for the profits uh for the profit we did the maximum of profits y plus one that is the current question profit that is zero by default and or current price minus cost current price being the price at this position minus the cost we spend uh as this person right so it's more or less this right now it's zero fine because we are just spending uh that much money on it now and there's the uh first iteration and like we need to go ahead with uh k equals two right so k equals two at this position so we need to go ahead for two number two articulations on this so what we are printing over here we are printing the cost of y plus one and profits of i plus one after each step like after each uh value of k over here and for each of the current price so in the first row you can see that for current price uh to be the three for current price three this is the uh row getting hit so let's uh understand further so what happened further we again check for the current price uh like cost of i plus one i is at this moment uh two okay like uh i is at this moment one uh and the previous it was zero fine so first of i plus one became uh two so that's basically current price is remains same and profits also profits of i this previous profit we know is like zero for us so that's the price we got three again fine and this way we're just moving ahead with it okay so this is where just keep checking farther keep checking further and there you find but ultimately what happens uh our cost becomes a negative cost becomes negative that means that's like we are not spending money from our pocket right we are just uh buying it so cost becomes negative and thus a profit becomes a huge number profit in uh like positive so that's the idea that we are following to this uh to just uh have a code or to just get a final answer or maximize the problem so this is where this can be idea if you have done uh by like the same question number three if best time to buy sell stock three there i will get two transactions right in the two transactions we were doing something we had the idea of doing uh say uh we just took the first five and then sell first and then we took the second byte and the second set and we're trying to maximize each of them like maximize profit based on the each of them fine so that we did in our uh previous question so here we are doing the same logic okay we are doing the same logic with a k number of steps okay so that's the small change we're doing yes this is the same continuation of question number three that we are having the two uh like the two transactions and we simply uh like keep on checking was the first buy profit and the second byte profit so i'm maximizing them okay so that's the question that's the idea so i hope it's understandable how you can solve this question and if you have any doubt make sure to comment them down as well so if you are worrying about the complexity see the complexity is actually a k number of steps on the right and uh n number of steps n being the length of our prices array okay in number of steps and the box is like 10 into k so that's the complexity you go ahead and talking about the space complexity how much extra space you posted here you simply had a space of k plus 1 and k plus 1 is basically 2 k 2 into k okay that's the complexity of space complexity we have over here okay so that's the space so i hope it's understandable if you have any doubts further make sure to comment them down i'll be happy to help you out as well also like this video and subscribe to this channel for regularly good videos like this so thank you all for watching this video hope to see you soon in my uh next video as well you
|
Best Time to Buy and Sell Stock IV
|
best-time-to-buy-and-sell-stock-iv
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.
Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** k = 2, prices = \[2,4,1\]
**Output:** 2
**Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
**Example 2:**
**Input:** k = 2, prices = \[3,2,6,5,0,3\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
**Constraints:**
* `1 <= k <= 100`
* `1 <= prices.length <= 1000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,123
|
331 |
Hello hello everyone welcome to day 26th August previous notification is amazing free mode of realization of minority in this question Thursday subscribe and subscribe the Channel Distic will need not mean that not interested and moving from the president of tree not to withdraw The Candy Crush look at presentation at his creative prowess and is very interesting question this definitely like this solution verify free mode on this is the like and subscribe The Channel subscribe and subscribe this Video Please subscribe and subscribe let's you would like one right now and If You Know Decide Which Holds Value * Avoid subscribe for More Video Subscribe Mode Turn On This Is Not Vidron Its Wide Subscribe Information Will Come Up With A New Vid Oo That More New Note Se Come Up With No Lifting Or British Egg Cost Old Or New Vacancy Date of Birth liked The Video then subscribe to the Page if you liked The Video then subscribe to the Channel Mode of Ko Chodoon Vacancies Good But You Should Avoid Notification Subscribe Will Reduce subscribe our Channel subscribe Video in To connect with difficulties ki indra alteration show veer visiting char beam normal person mode subscribe to subscribe video ko main 16 mins right for her hai next vihar phase how subscribe and subscribe this video not here in this video not will not mean that subscribe to youtube channel Do n't forget to subscribe as per to and only bannu and will reduce frequency in the mid 2000not vidmate app ke laddu subscribe our channel subscribe to one take game corrupt videos by one get married on both sides of one that in the tree on one Excerpt 12652 Twitter The Amazing Video's Poll Su A Tübingen Lord Will Avoid Appointed Midday 's Descendants And No Deposit Personal Reduce 's Descendants And No Deposit Personal Reduce 's Descendants And No Deposit Personal Reduce Node 20 Politics 2656 Vacancy Reduced By Mid-2012 Mid-2012 Mid-2012 69 Liquid To Do Subscribe subscribe and subscribe the Video then subscribe to the two half Meanwhile make half bansi volume 10 must subscribe and share with ur 1999 and red subscribe Video subscribe 0 are next switch of this is another one in the string software testing one to subscribe Videos - 6a this is happy birthday wishes in the world In this section or that this British Great Power Project there is a belt also a split the input stringer come extracted The Video then subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to subscribe our Ko Anupriya Direction Witch Acid Double Fold Thursday Subscribe button hai hua hai in this brings together and definition of videos like share and subscribe to
|
Verify Preorder Serialization of a Binary Tree
|
verify-preorder-serialization-of-a-binary-tree
|
One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`.
For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node.
Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree.
It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer.
You may assume that the input format is always valid.
* For example, it could never contain two consecutive commas, such as `"1,,3 "`.
**Note:** You are not allowed to reconstruct the tree.
**Example 1:**
**Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
**Output:** true
**Example 2:**
**Input:** preorder = "1,#"
**Output:** false
**Example 3:**
**Input:** preorder = "9,#,#,1"
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`.
| null |
String,Stack,Tree,Binary Tree
|
Medium
| null |
589 |
hey everyone welcome back and today we will be doing another lead code problem five eight nine and array three P or the traversal so this is an easy one given the root of an energy return the prior traversal of its node values and array tree input serialization is represented in the lower order traversal each group of children is separated by null value see the example so this is the level of traversal one three two four five six as our you can say import and there is a null value separating each group of children you can say and what is the pre-order traversal so the pre-order pre-order traversal so the pre-order pre-order traversal so the pre-order traversal is a traversal in the tree that in which the root comes before the Roots come before everything so the root is just appended to our output at the very first and you can say after that we go to the left this is just if you have done a binary tree pre-order traversal so this binary tree pre-order traversal so this binary tree pre-order traversal so this is like this like parent then go to the left then go to the right so there are no left and right but we do have a children list so obviously this is an energy we do not have a binary tree if this was a binary tree then things would have been much easier you can say uh but this is also easy nothing complex here so what you want to do is just go to the left and see that 3 is apparent because 3 heads 3 has two nodes five and six what we'll be doing is just appending the left because obviously five and six are on the left five coming before 6 because 5 is on the left and 6 is on the right that's why 6 is after the five and after coming back you can say from the left subtree what you want to do is check other children's the children so check two check four and just append it to the output if they have no children so that's it so what we'll be doing is first checking if the root is value if the root is not varied we can just return a list empty list and we'll be making a stack and now we know that root is valid we will just append our route and the output is also another list we'll be using while the stack is still there stack has something in it we will be making a temporary variable in which we will just stack pop and append that stack pop in append that stack of value in the output after that we want to update our stack with the children so stack we will be extending it by the out by the time Dot children because this is you can say also a list itself because children is a list three to four and in this case two three four five just representing a list you can say what you will be doing is just reversing them and adding you to the stack so if we pop it we will be getting the very first yes the very first the or the very left element so that's it and after doing this we can just return our output and that's it so what is happening here is if we have a stack like stack a null stack starting from the very front if we see like the root is valid what we'll be doing is just appending our route in the stack so let me just separate it okay now we have an output list and while stack is not null what we will be doing is just popping from the stack and appending to the output in these two steps and in the stack we'll be extending the stack by the reverse of children of 10 so the children of one was three two four will be reversing them and then adding them because we want to if we pop now we'll be getting the left element which was three so we'll be popping 3 and the three is popped like this temp is equal to stack pop and its value is appended in the stack in the output so now we want to update our Stacks so the children of three will also be reversed and added to the stack so it will be like six and five and now again the loop will continue because stack has something in it so five is part and it is output will be like this so we'll be seeing that 5 does not have any children so nothing will happen here and group will again continue popping six does not have a children we will be just appending to the output tempt value and after that we can just top two and add it to the output seeing that 2 does not have any children and four also does not have any children so this is how our output is going to look one three five six two four and that's it if you have any kind of questions you can ask them in the comment and that's it
|
N-ary Tree Preorder Traversal
|
n-ary-tree-preorder-traversal
|
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[1,3,5,6,2,4\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The height of the n-ary tree is less than or equal to `1000`.
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null | null |
Easy
| null |
1,727 |
um hello so summary of largest submatrix with rearrangement summary of the solution um The Main Idea here is that we can do prefix sum with resetting when we get a zero right because for a submatrix we need consecutive ones and so and what we want to do next is maximize the number of ones in each column and so we sort the columns by number of ones so we do the prefix sum and then we sort each row by the number of ones um now to get the um size or the area of the submatrix we can just take the height of the um the height is the number of ones so that would be in our cell itself and then the uh width is going to be just the length of the column so the length basically um the column we are at because we know the previous columns have larger number of ones so they are guaranteed to have a one that's pretty much it um for the solution prefix sum and sorting
|
Largest Submatrix With Rearrangements
|
cat-and-mouse-ii
|
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`.
|
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
|
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
805,949
|
37 |
Loot hello everyone welcome to difficult channel and definition of what do soul and justice should avoid you listen to there problems without it's subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the will the observance is destroyed to solve This question on the newspaper festival subscribe Video airtel live video subscribe to hua tha tubelight kothiyan and only it's heart problem but I don't feel the twelve volunteers for research on baikunth electronic solution vibes subscribe to 200 electronic and subscribe must subscribe to hai to Avinash Start Dresses For What You Want To Listen To The Number Valve Thursday Subscribe Video Subscribe To The Number Subscribe Our Back To The Number To The President Of Queried Solution Suraksha The Problem Lives In Identifying With Its Violation Cases Or Not And Subscribe Or Not Is From the article Jim But You Are Feeling No. 8 This Particular and Mode off that rukma e will rotate and hold for 10 minutes unmute ghalib and videos every day violations of paint that similarly day mixture to this point column 200 columns from it zurich chess board 90 hold value that today 80 columns painted 6 blind systematic norms interesting this Video in this particular problem in this political leaders page hotspot setting violation in this particular sub matrix limits of you very simple equation for money elements of the year in the matrix raw elements from 10 m still accounted for boys in this information will be amazed let's check The volume to subscribe cs6 in the element of the match david that a what do you will divide this love bite servi withdrawal urs that it will give you as normal light setting is equal to 73322 into three do it means starting subscribe what is the subscribe 6 323 liye 60 mig entry points 98 36 com 86 yesterday morning titration from i20 up till it was too late and will check use this for what is the element acid subscribe andher 9621 hit the second subscribe button subscribe to 206 plus wishes 66 will check the belt 6 Vid U Ke Din Will Have Not Equal To One And Alerts Sexual 6 I One White Widow The Body But Six Plus One Models Free British 7 209 The Indices BOA 600 Us Zor Equal To A Newly Updated Number Subscribe Amazon Is Subscribe And subscribe Video Subscribe 6 It's Battery Which S2 That Aunty Six Plus 8 Model Three Listen To Solve Video subscribe this Video Because of the discussion and voting now the board of 600 is not withdrawn it is not possible for this place that now let's move with coding section Doing All This Seems Difficult And On Do A Slight Cooling Section 2 Nutritious Diet It Is Pacific Null And Dot Land And Subscribe With U 200 Electronic And This Method Switching And One More Like Subscribe And That And Acquits Rather Than What Is The Current Directly To Mercedes Pet And Midfielder Characters From North Will Start From Chronic subscribe Video subscribe to advance develop in mid point of mode own do otherwise simply goodbye and subscribe to have FD account rule simplest form of Thursday video from this talk but rather than subscribe The Amazing Loot -Loot subscribe and subscribe the Channel subscribe our that this board art normalized form has given proper arrangement to thriller and mode switch of birth to the element withdrawal from the this is updated on a life enjoy two days session video like share and subscribe channel subscribe with a
|
Sudoku Solver
|
sudoku-solver
|
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**Example 1:**
**Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution.
| null |
Array,Backtracking,Matrix
|
Hard
|
36,1022
|
1,748 |
hi my name is david and today we're going to start an exciting new series where we're going to pair program to solve algorithm problems i know that preparing for interviews solving algorithm problems can be a very frustrating and learning process so my vision for this is to show how fun and exciting solving these algorithm problems can be so today we have our first participant raphael why don't you introduce yourself and tell the people where you're from and what you did before coding hey everyone my name is rafael i'm located in the dmv area in maryland just about 30 minutes outside of dc and before coding um i was actually a touring musician i played keys and produced music i did that for about three years while also working retail like in between gigs and now i'm getting into software engineering awesome so what problem what programming language are you gonna be using um today we're gonna be using java great okay so today's problem is 17.8 17.8 17.8 so look that up great go to it nice awesome so take some time read the problem on your own and then once you understand the problem explain to me how at least one of the examples work and then afterwards you can begin coding and once we finally get a solution we'll go over the space and time complexity for your solution and you may begin now cool so you're given an integer array nums the unique elements of an array are the elements that appear exactly once in the array return the sum of all unique elements okay that sounds pretty good and so we have one two three two so the unique elements are one and three so the sum should be four yep and then for this one we have all repeats so zero and then these are all unique so we add all of them so 15 yeah awesome it looks like you understand cool so how are we gonna do this um so we need to keep like a running some of like yeah we need to keep it running some right that's what we're gonna return yeah but to that sum we can only add the ones that are unique so we have to know okay well is it first thing is like is this array sorted and that's it's not sorted that would be one thing if it was sorted it would be different or we could sort it first that's not what would shortly do for you if it was sorted like what would it do actually oh like um the numbers next to each other would be duplicates no or like we could know that like if i don't know if we would start on two and then look back at one let me start on one and look back at zero um but if the number i'm trying to think which way we would do this would we look ahead or would we look behind we could look ahead uh and then if these two numbers are the same okay so look at let's look at this if it's sorted this one's sorted so if we're on this number and we look ahead um it's not a duplicate so we can add this we're on this number we look ahead it's not duplicates we can add it and then we on this one we look ahead it's not a duplicate so we can add it um yeah so that would allow us to do it in one pass which is pretty good right would it be one but yes because what are you gonna be comparing the current number to the one next to it so what if they're the same okay let me see so if they are the same it would be like so this so we're here we look ahead um we don't add this then we're here we look it's almost like we don't have to look at you already knowing this yeah so can we would it be like we skip again like so skip over the next two so does that make sense like and then we there we're there we look ahead and they're the same again so we don't have to iterate we don't have to count this one we can just skip ahead so it's almost like we could cut it in like okay but then that sounds good but then what about the last one what are you gonna compare that to the one behind it yeah i get i mean it's sloppy right but like if it's like the last one we look behind it okay so yeah another if conditioning yeah so like it would be yeah on the last one like the condition would be if um current element if we're on the last element there to the element to the previous if we're on the last element compared to the previous element that's if when will that happen so that's one condition right so okay so we have the one where it's like where it's this and that works out fine does it change though if it's like an even amount of numbers like if it's an even amount uh so let's say it was like one like this one two oh that was like an odd this is five one so if it's even then we'll go like here check this so we could skip zero we can skip to zero one two let me just go ahead and do this zero one two three four five so what's zero one two three four five representing oh these are the indexes okay so if um so if these two are the same like so we start at zero we compare it to one we compared to the first index they're the same so we don't add anything and then we can skip one and we can go straight to two so it's like we go uh yeah that seems like a word so i'll type that out in words in pseudocode okay so for this case like um so before we even get to the if uh state what are you doing first um like start at zeroth index that we're seeing yes but what programming tool are you doing before you oh like a loop yes yeah loop like uh yeah we're gonna loop so yeah that'll be the first step fill the last element and then like so we start on the first element and then if the current element um if the current element does not equal the next element like um if it doesn't then we're gonna add to some sum i guess outside this we can like initialize sum to zero so if the current element does not equal the next element we can add it to the sum okay else um skip to like the next element or right next element or that's what's a better wreck says like uh index or index like is it plus equals two like how's that sound like because we're at zero and then normally in the loop we would keep going to one like on the next iteration we would go to one but instead we're going to do index plus equals two yes yeah somehow like i don't know how it's going to get coded out but somehow instead of going to where we're going to yeah and then and this we just keep doing that and it seems like it can just be the same thing if the current element does not equal the next element then we can add to the sum else and then we do that all until we get to the last what i'm trying to think is there an edge case where it's like uh like we're here right okay so let's actually walk through this like with this example um so we have one where it's an even amount because i just don't know if like it's gonna make a difference if it's an even amount in the array or an odd right but um so we're here okay we're here yeah we're here um it's not loop to the left summit current element does not equal the next element so we're gonna skip to okay there the current element um e equals the next like they're not unique so we're going to skip to the next one the current equals it the current element is not unique so then this is going to break yeah if we try to just yeah damn that's me oh no that has to be another way so maybe we can't is that another condition too like if we're on well i'm trying to think so you see running through this logic it's to be a lot of edge cases and you know inefficiencies so what data structure do you know if that's good for unique elements oh like a set i mean yeah so we could go through we could just like loop through it once add everything to a set and then get the sum of the set right or like didn't add everything in the set yeah that could be uh should we just do that yeah so check that out what you just said it's option one um option two so um like uh initialize set um uh iterate through array adding each num to the set and then um sum all of the nums and the set sounds like a good plan cool so yeah let's try that way um so okay so we're gonna uh i think it's like uh that's alright some text set um so then we're going gonna loop through and we can just use like a enhanced for loop for this one like before each loop so four and four each num and nums uh we're gonna add the yeah so then we're gonna do set dot add num so we're looping through all the nums adding that num and then at this point we have all unique elements in this set and then we can just i wonder if there's like uh there's like this oh let's see if this step works first so yeah let's print it out i think you can just print um either we have to return something and then let's see what the test case is all right so it should be um what should oh shoot should print out oh i guess it's just gonna print out um one two oh wait hold on all right let's see what happens wait what do you think is going to happen first no this is going to be it's going to return all the element it's going to return one two and three right yeah all the unique ones there you go that's not what we need but we need i mean that's a stepping stone yeah like so what did this do for us what did this uh this step do for us it gave us all like every element in the list once yeah like in the original yeah yes yeah that's unique but it doesn't mean that it's not duplicated in the original input right yeah because like we have one two and three out but we have like a two and two here so we wanna add that what do you mean by dupe okay like um we can't just get the sum from this i thought originally i thought we were gonna get the sum from this but like so look at the example one that's what this case is right yeah the test case is one two yeah so the sum is four okay because we're only adding one and three because one and three are unique uh versus i don't i'm trying to think what's the term like there it is a unique element in the sense that like it just happens but it's like it is duplicating the original so what can we do from here um so maybe the set isn't the right uh data structure yeah it would more so be like i mean we could do i mean another way is like we could do a hash map and then i guess i was trying to think of like a clever way up front but like yeah so we could do a hash map count how many times each element happens and then only like so the key is the element like so the keys for this hash map would be uh one like oh yeah the keys would be one two and three and then the end the value for the hashmap would be um like how many times it occurs so like and then we can just add the ones that have like an occurrence of one so yeah try typing that out so it would be like um so um yeah we're gonna get rid of this and what we're gonna do is um we're gonna it's option three is we're gonna like uh knit a hash map and then iterate through the array um yeah adding each num as a key okay to the hash map yeah adding each number it keeps the dash map and then like if um if yeah so what's the value going to be uh each number as is a pizza value uh starting with a value of one like so the first time we add it um we the value the key is going to be the element and then the value is going to be one and then if the uh key already exists uh increment the value so this will give us like yeah we're getting the counts of every element in the array okay and then at the end um what can you do with this we loop through the hash map um add the sum of all keys with occurrence of one that sounds good what do you think yeah and then lastly uh return to some okay all right let's try it so and it's going to be integer uh hashmap um i guess you could call it like yeah i'm just going to call it hashmap this is like the frequent sometimes they call it like what the frequency counter or whatever um new um okay so we're going to do the same thing as before for each num in nums or nums um dot puts now we got to check before this hashmap.put um put num and then um one but like this is gonna be we gotta do a check here if hashmap dot contains key known if it okay um oh so this actually needs to be yeah so what does it mean when it has the key it's already in the hash map okay so if it's in um then we increment the value so we need to actually update yeah so i need to do um dot get no so this will return the key value that's already in there and so we're updating that key and then uh we're getting the value that's already in there and then we're gonna add one to it nice okay else hashmap put num uh one increment the value else uh um uh i'm seeing first time uh start count yeah so let me talk through this so we have the hashmap where we're iterating through the array and num of nums and then if the hash map we're doing a check first and if the hashmap has this element that we're currently on and we increment the value by updating that key uh with and getting its value getting its current value and then incrementing it by one so increasing the count okay otherwise we are uh putting it in for the first time and we're starting that count at one cool so i guess can i check this and then before you yeah you want to print it out yeah print it out and explain to me what you expect to see in this print oh so between negative one so we should see so the test case is an array of one two three two yeah so we should see like um one with the value of what the key one with the value of two no yeah the key one with the value of one the key to the value of two and the key three with the value of one okay yeah one with value one two it's value two three without yeah so we have nice so what's your next step that you said before we have to count all we have to add the sum um we have to sum all the ones with an occurrence of one yeah so loop through the hash map and add all the sum of all the keys with the currency one so in sum equals so we start off at zero then we can return some here and then we're going to loop through the hash map um before i'm trying to think should we loop through damn i forgot how to do this you can look up the syntax yeah um i know it's like entry four uh yeah i think we're gonna try something like this yeah let me just map dot entry string map element string that get key okay i'm just gonna go ahead and uh hopefully the formatting isn't trash and this just needs to we just need to edit this to the integer map element in hashmap dot entry set so for each like entry and i know in java they're called entry for each entry in the uh in this hash map we're gonna um get the string key map element dot get about i don't need actually don't need the key i just need to see the value so there so i just need to get the value so it's going to be a map element all right get value if element.getvalue so if element.getvalue so if element.getvalue so if the current if the value of the current entry that we're on equals one then we do um sum plus equals hopefully um yeah let me if this doesn't work it's just a since it should just be a syntax thing so we have the sum on the outside okay we're going through every element in the hashmap if the and we're getting the value not the key so if the value of the oh no i'm sure i'm so explain to me what the example like we have look at the output we have yeah okay yeah matt um some yeah so if the value so if this equals one we need to add the key so i actually need to do get key thanks you caught it yeah i was back yeah that's about to be added the it's about the answer is about to be three um cool so sum plus equals the map element so if the value if the occurrence the value is going to be the occurrence equals one then we're going to add the key which should be good let's run it i think we're good to just like all right awesome i don't see what edge cases there could be like okay so let me try to anticipate like so if it's all ones if in this case right it's all uh yeah at the end of this hash map right here is gonna be like uh one and zero one two three and five okay and then here um none of these uh like this is never going to be true so some is never gonna get added to so it should return zero i guess we can just run that's this case real quick nice and then uh so what are the uh if it's just an empty if it's empty um for numb and if it's or okay so then the other edge cases are like if it's empty if there's like nothing right look at the constraints on the left side so gnomes.length oh so always has to so gnomes.length oh so always has to so gnomes.length oh so always has to have at least i actually never know how to like read this but so you said that yeah what if it's an empty but numbs dot meth is as at least one so it's impossible the constraint is that it will never be empty so you wouldn't have to consider about that okay so we just have to think about the case of there just being one if it's one oh i guess we can make this faster right like if the element if um thumbs dot length equals one we can just return nums of zero like returned uh yeah if it's just one element in there like if it was just like one we can just like straight up return one or if it's two yeah we can so we can just like go ahead so that makes it like i guess a little faster for that edge case um and then what's another negatives are fine i'm trying to think yeah we're good right submit great so before you submit remove any prints because those blow it down cool all right so this is sick nice good job thank you man so what's the time and space complexity all right so um tom complexity as the input grows we have to iterate through the whole thing so i'm thinking it should be but i'm thinking like we're reiterating twice on it does that do anything probably uh oh uh it would be o of n like o n plus o of n right which would be o like would it be 2 and so doesn't it doesn't that just like cancel out to just o of n there you go yeah type out time complexity so you we have it as a comment yeah so that's right yeah so there's two end but it rounds down to your oven cool and space complexity is like um as the input grows like this hash map like um yeah we're making this hash map and that hash ramp is gonna grow like the hashmap is gonna be as big as the we're at we're allocating space for that hash map so i guess that's it could potentially be as big as like in the case where it's like 1 through 100 and all unique then that hash map is going to grow 1-100 1-100 1-100 as well so that's all then nice cool nice that was easy yeah that one wasn't that bad
|
Sum of Unique Elements
|
best-team-with-no-conflicts
|
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array.
Return _the **sum** of all the unique elements of_ `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 4
**Explanation:** The unique elements are \[1,3\], and the sum is 4.
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** 0
**Explanation:** There are no unique elements, and the sum is 0.
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 15
**Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
|
Array,Dynamic Programming,Sorting
|
Medium
| null |
1,859 |
hello guys today we are going to discuss the lead code problem which is sorting the sentence which is a very easy problem so first of all we will read the prompt and then we will try to understand what the problem is about it says a sentence is a list of words that are separated by a single space with no leading or trailing spaces so basically this is a sentence there is no space before is whatever the first word is and there is no space after the last word each word consists of lowercase and uppercase english letters so we can have upper or lowercase letters although this is not going to affect our problem in any way a sentence can be shuffled by adding by appending the one index word position uh to each word then rearranging the words and words in the sentence so if i need to shuffle a sentence what i need to do first i need to put the position of that word and then rearrange it so uh if we see here this is the word the position of this is actually one is the position of is two and the position of this word sentence is fourth position and the position of word a is the third position so and then when we need to arrange this sentence we need to arrange based on these indexes the indexes that are appended at the end of each word so we need to append based on this condition okay all right so let's try to understand how we can implement it we are going to implement it by using the selection sort algorithm which basically um do the swapping of two words once only so let's take an example our example is a sentence where is for example and then there is uh the index of this word and then as word sentence with an index so all the words have the index with it all right so um and after the arrange after arranging this sentence this is what we are going to get so forget about uh these words just forget for time being just forget these words and just assume how these words are in an array so the two the first is two and then comes four and then comes one and then comes three so for example if we need to arrange it using a selection sort what are we going to do so we will have two loops one loop is the ith loop that will index the array starting from the first position till the end and there will be a jth loop that is going to basically index um starting from i plus one element till the end so basically what we are in selection so we are going to divide the array in two parts in such a way that after every iteration this part will be the sorted part and this part will be the unsorted part how we are going to do this so we will keep three variables i j and a minimum value minimum index variable okay so the first time uh and uh the first the i will start from zero the j will start from i plus one because you know the indexes are starting from zero one two and three so the i loop will start from zero the j loop always start from i plus 1 position so j will have a 1 value and the minimum when we are going to start our loop we are going to initialize minimum index as to be the ith index like we consider that this value is the minimum value so i say that my minimum value is the zero is zero as well now what we are going to do we one once we started this loop in the jth loop we are going to compare if the element at j position is less than the minimum index value then what you need to do just change this minimum index okay so let's see what i mean to say all right so the loop will start and we will see that what is our minimum is 2 which at the moment the minimum is pointing to 2 this is my minimum right okay i am going to compare that the j is going to run not because this is the i and j always run from this position till the end position right so now what i am going to do is i need to check is the jth element which is 4 is it less than 2 no it is not ok then just pass it now my j will come to this point now i am going to check is this value less than the minimum value so because the minimum is pointing to the zeroth index right so yes the minimum this jth value is less than the minimum value then what you need to do change this minimum to 2 the index value because in minimum we are not going to put the element value we are just putting the index value so now my minimum is 2 it's not it's no more zero value all right now let's move forward so what we need to do is we need to check is this 3 value greater i mean less than the value at minimum so my minimum is pointing at this place right now my j is pointing so let's make j here this is my j now and this is my minimum now i'm canceling minimum from here so minimum is here okay this is my minimum so compare is it uh less than no it is not so keep the minimum and my internal loop is already finished so after the first iteration my minimum is going to get the value 2 now after this loop ends i'm going to compare is i not equal to minimum so if i write minimum here that will be better so i is basically the 0th position minimum is basically the 2th position so basically 0 what it tells me 0 is not equal to 2 okay if so then swap these elements so this is the first time i'm going to do the swapping so after the first iteration this will become 1 and this will become 2 so now you will see that my array is going to be sorted from here the first the element on the left side is going to be sorted and the element on the right side is going to be unsorted so now after the first iteration my 0 is going to be starting from 1 and my j is going to be starting from 2 and i'm going to repeat the same process after this iteration my this part of the area is going to be sorted all right now let's see how we are going to implement it in a code all right let's start so you will be thinking like we are going to have an array but um an array of words how i'm going to traverse that array uh with the values so basically if i repeat the thing we have the sentences right so we have the sentences but we need to operate these words so first of all i need to use the split function and what this print function is going to do it is going to split this whole array into the array of words so when i use the functions plate it will uh make like sorry is 2 will be my first element in the array sentence i mean i'm not going to write it whole so sentence 4 will be my second word in the array and this like this one is my third word in the array and a3 is my fourth word in the array this so when i run the split function this is how what i'm going to get so let's back all right so i'm going to write the first thing is uh i will write the name of the array my new array as shuffle okay shuffle is equal to s which is my um array that is given here s dot split so and then how i'm going to split it with the space so wherever there is a space split the characters so you can use this plate function for any other thing as well but we are splitting based on the spaces all right so shuffle is my array that will have all the words but uh all the sentence is splitted into different elements of the string now i will create an either another um string final or i just write final unless sentence this is the one that we are going to output so at the start the final sentence should it shouldn't have anything now i'm going to start my index for i in range length of shuffle the first thing i need to do is i need to assign minimum index value as i told you the minimum index value will always start from ith i think so it is equal to i and then i'm going to start the inner loop for j in range and from where it should start from i plus 1 position so i plus 1 till length of shuffle is my array so okay now what we need to check if shuffle okay and i am going to i'll just let me write this thing and then i am going to explain you what it does is less than shuffle minimum index eighth position uh the last position so this minus one what does it do so in python what you do it what you do if you want to have the last character you always write the minus one thing right so when i write minus one for an array it will give you the last element of the array so what i'm trying to do is i'm going to for the jth element whatever the element we are talking about for example this element i'm talking about when it is in the shuffle array i'm going to take the last element and then i need to check it with the last element of the second uh of the next element whatever the next element is okay so if the shuffle jth last element is less than minimum index last element if it is so then that means i need to change my minimum index because i have found another index so minimum index is equal to j right so this way you are going to get the minimum index by this loop now we need to check if i is not equal to minimum index that means we have found another minimum index what we need to do you have to swap the values and in python you can swap the values in one line i'm going to show you how you are going to write shuffle minimum index comma shuffle i is equal to and now you are going to write them opposite so it is basically now you don't need any other temp variable so now you are going to write shuffle i comma shuffle minimum index so this way you are going to swipe the values now i got after executing this whole part one of my initial index wherever the i is pointing that index is basically sorted so now i need to add it to the sentence so my final sentence plus equal to whatever the shuffle it index is pointing but i want all the elements sorry i want all the elements except the last element so when we are want uh when whenever i want all the elements but i want to exclude it this is how i'm going to write it and then what you need to do is add a space all right so this is how it is going to add each word except the last corrected to the final sentence all right so now what i need to return the final it's intense but i don't need to add as like i need to remove the space from the last character so what i need to do what should i return i should return everything except the last character let's run it wow it is accepted so let's submit it oh it's showing you 24 but it is sometimes showing 80 percent sometimes it's showing 70 so don't worry this is the efficient solution and i hope that the solution is clear to you and i'll see you next time bye
|
Sorting the Sentence
|
change-minimum-characters-to-satisfy-one-of-three-conditions
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence.
* For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`.
Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_.
**Example 1:**
**Input:** s = "is2 sentence4 This1 a3 "
**Output:** "This is a sentence "
**Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers.
**Example 2:**
**Input:** s = "Myself2 Me1 I4 and3 "
**Output:** "Me Myself and I "
**Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers.
**Constraints:**
* `2 <= s.length <= 200`
* `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`.
* The number of words in `s` is between `1` and `9`.
* The words in `s` are separated by a single space.
* `s` contains no leading or trailing spaces.
1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
|
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
|
Hash Table,String,Counting,Prefix Sum
|
Medium
| null |
103 |
hey everybody how's it going so today we're going to solve the code 103 binary tree is the exact level order traversal so this question wants you to iterate through a binary tree and return the order of the nodes at each level in its exact matter so for example this is what the question wants us to do so we're going to iterate through the binary trend as exact matter something like this so oh sorry so and so kind of like that and then return the order of the notes in that matter in this exact matter so first we're going to hit 3 and then we're going to hit 20 9 15 and 7. so like this all right fair enough so how do we solve this question well there are many ways you could make this a lot more complicated but we're not going to do any of that what we're going to do is we're going to do a simple level order traversal in the tree and then return the order of the nodes in the exact order they appear in the binary tree and add those levels to an array list and then we make a second pass through that array list and then apply the zigzag order later it's no shame to do two iterative passes in a question like this especially when you don't want to make things complicated so when we do uh the normal level order traversal we're going to get the notes 3 9 20 15 and 7. so this is what you get when you do the normal level order traversal so first we go to the root node we add it to its own level and then we add its left and right children to the second level that's nine and twenty and then we go to nine and then we go to twenty we add it to the array list and then nine doesn't have all the children notes attached to it but then 20 does so we add the children of 20 left child and right child to the third level and then we have that as the normal level order traversal so now that we have this it's easier to make a zigzag using the arraylist data structure than using the binary tree data structure so this is going to be the final answer and how do we get to this answer is that we alternate the levels we alternate the order of the levels while traversing this array list so when we get to the first level we know that the order is from left to right so we add the order from left to right and then we get to the second level we know that the order is from right to left so we add that order from right to left we just reverse the order of the collection and then this becomes 29 20 and 9 and then we get to the third level we know that the order is from left to right so we keep alternating the order of the levels as we go through the array list and that's it that's how you solve this question so now let's talk about the time and space complexity of this question so for time complexity we're going through every single node and because of that time complexity is going to be o n and for space complexity we're storing an array list that's going to hold at most n elements in it representing all the elements in the binary tree so space complexity is o of n so that's how you solve this question let's dive into the code the first thing we want to do is declare an array list that's going to hold the list of levels so i'm going to say list a list integer uh let's call an answer this is equal to arraylist and then we want to check for edge cases we just want to say if um root is null if this is the case then what we can do is just return uh answer because there's nothing in it all right so now that we have that we're going to implement um a normal level order to reversal and that means we will need a cube so i'm going to create a q our adq and it's going to hold true notes and let's just call it q i hope that's how you spell it and that would be equal to new array to q okay and we're just going to add the root of the tree note this one to the rq so i'm just going to say q then add group um so i'm just going to declare another list of integer a list of lists of integers that's going to hold the normal level order traversal we might not need this but let's see what happens oh let's just call it levels so now we're going to iterate through the queue and then add the levels to the q because q has a property of first in first out so the lower levels are going to be at the end of the queue so we'll get to them last so what we do is that while the queue is not empty that means we still have elements in the queue we can just get the size of the elements in this level so let's say in size is equal to q that size now that we have that we're going to declare a list of integer that's going to represent this level i'm just going to call it this level uh no arraylist and then we're going to iterate through all the elements in this level in this queue so we're going to say 4 and i is equal to zero i is less than size no times less than size and then we can just do i plus so now we're iterating through all the elements in this level and we're adding them to the list of integer that represents this level so we can just say we get the current level current tree node so let's say truenode current is equal to q not remove so after we remove it's not going to be there any longer so we don't have to worry about it and then we can just say this level that add current that value is it val or value i think it's foul alright cool and now we just want to add the left and right children nodes of this current node into the queue so now if we add it's going to be at the end of the queue so we'll get to that later because we want to go level by level but we don't want to add null nodes so we just want to check if current the left is not equal to null then we add it to the queue so q that add kind of left and then we do the same thing for the right child node as well so if current dot right is not equal to null and just q to add current all right so that's it we have one more thing to do so after going through um this loop and adding all the elements of this level into this arraylist of level we want to add this arraylist into the levels arraylist so we can just say levels that add this level so i think that is it for the normal level order traversal that should do it and then after that we want to iterate through all the levels and then alternate the order of the levels to mimic the zigzag pattern so let's do that so what i'm going to do is i'm going to declare a boolean value that's going to represent the current order of the zigzag that we're going through so for the very first level we're going from left to right so i'm going to call it left to right that's going to be true for the first level and then when we get to the second level we alternate it we go to third level we alternate it and that's how we're going to do it so let's say 4 and i is equal to 0 i is less than i'm going to say levels that size i plus so now we want to get the current level so list of integer this level is equal to levels that get high and so now that we have the current level we're going to determine whether or not it's going to go from left to right or from right to left so if left to right then we do nothing we just add it to the final answer so we just say add this level to final answer you just say answer that add this level and otherwise if it's from right to left then we want to reverse the order of this level to mimic the zigzag pattern so we just say collections dot reverse this level if you want you can write your own um reverse function uh it doesn't really matter if you do you're gonna get the same results so if your interviewer wants you to write your own reverse function you can simply do that with like two pointers and then switching elements as you go but for these interviews you have like 45 minutes or even less to answer a question so don't sweat it and then we can just say answer that add this level so let's not forget to switch the order of the levels after we've added this level so when we get to the next level we want to go from right to left instead of left to right so we want to set left to right we want to flip it was equal to not left to right so this is going to change it from true to false and then in this other function this is going to change it from false to true well i think that is pretty much it after that when we're done with everything we just want to return answer alrighty let's run this and see what happens all right cool it's accepted let's submit this and it's successful so i just noticed that you don't really need to um lists of lists you don't need two of them once you have this level you can directly alternate the order of this level and then return the levels um arraylist as the final answer instead of storing uh this answer that's just a simple optimization that i noticed let's see how it works to implement that we're just going to comment this out because we don't need the answer anymore um if it's from left or right it's already ordered from left or right so we don't have to do anything and then we reverse this level and we don't need the answer anymore and then we change the order from left to right to left and then we just return all levels and let's run this and see what happens all right cool so that's it we can get rid of this answer and then we move this level up here and then return levels so that's it that's how you solve this question if you like this type of content please consider subscribing to the channel comment down below if you have something to say and share this video around the youtube community smash the like button for the youtube algorithm and i'll see you in the next one bye
|
Binary Tree Zigzag Level Order Traversal
|
binary-tree-zigzag-level-order-traversal
|
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102
|
1,647 |
hello and welcome to another video today we're going to be working on minimum deletions to make character frequencies unique and so in this problem you have a string s that's called good if there are no two different characters in s that have the same frequency given a string s return the minimum number of characters you need to delete to make S good the frequency of a character in a string is the number of times it appears in string for example a b a is frequency of two vs frequency of one so an A B it's already good and AAA BBB CC so a has a count of three B has a count of three and C has a count of two so here you would need to either make a or b decrease one of them to make it unique and need to decrease one of them to one which would be you delete two characters that's the answer there and then for this one we have a equals three and then we have b equals two T equals two and E equals one and so here you can delete both C's resulting in the good string e a b note that we only care about characters that are still in the string at the end so if you delete one of these characters either the c or the B because you can't make them one then that would be unique and so you are allowed to delete multiple characters so that is something you are allowed to do like for example let's say you had give you an example here so let's say we had a string like this right A B C then a would have a count of one but you would have a count of one and C would have a count of one so in order to make them unique you need to delete two of the characters so two of their accounts would go to zero but that's fine so that is one little caveat and the problem that they show you in this third example and so the way to do this problem especially in Python is very convenient and the thing you need to know for this problem that is going to make a lot of this easier is if you have a dictionary of letter counts right so if you have a dictionary of accounts of a b and c and so on that is technically oh of one time and O of one space to get so obviously to go through the actual word it's not all of one but if you have a dictionary of letter counts that is O of one space because no matter how big the word is you're only gonna have 26 keys right for every single letter obviously if the key can be every single you know like character possible then that doesn't count but assuming you know our keys are limited to lowercase letters which they are in this case then it's fine and I believe they are limited to lowercase or even lowercase and uppercase you know it's still a constant value so string can be billions and billions of characters but you're still only gonna have 26 keys so making a counter where you just have the for every letter you make a count is free for us and so what we're actually going to do is we are going to make a counter and so let's actually go through this example AAA BBB CC because a b is fine but for AAA BBB CC what we're actually going to do is make a counter so for a in Python a counter is just L the key is the letter and then the count is the or the value is an account of it so we'll have like A3 B3 C3 is or C2 is our counter and we can just make this like we can call it whatever we want right count or something so for count we'll have a we'll have count three B will have count three and c will have count two and that's totally fine now we don't actually care what these characters are we only need to know about the values because we just need to make sure that the values are unique that the counts are unique we don't really care what letters they are like if this was a and b or if this was z and b it would still be the same solution so we really need the values of the counter so we are going to make a counter but then we're going to get the values so our values is we have some letter that we have three of and some letter that we have two of now remember that I said this is basically free and so you know what else is basically free sorting this so sorting 26 Keys is O of one time because it can only be 26 and that's it so we're actually going to sort them as well now obviously in terms of likely Cod efficiency or something it's not you know it's not free but in terms of Big O it is free so making a counter the space is O of one sorting a counter the time is of one and so on right because it's only 26 characters that's the max you can have as many letters as you want still this will only be 26 keys okay so now we sort them now basically what we need to do we need to get to the end goal of all of these need to be unique right you can't have two counts that aren't unique but there is one caveat here they can be unique but you could have multiple zeros right because deleting you know all of one character makes it not count so all of them need to be unique but you can have multiple zeros so the problem basically comes down to how do I make all these unique or have multiple zeros quickly and so what we are actually going to do is pretty straightforward we're gonna have a set and we are simply going to check we're gonna go one character by character and we're just gonna check is that character in our set if not let's add it in and if it is then we need to keep decrementing it to get to a character that's not so for example we need all these to be unique so for two we're going to say is it in our set no it's not so two can be left as is so and then we're going to add two to the set and we're gonna say is three in our set no it's not so we're gonna add three now for this three we are going to decrement it until its value is no longer in our set or at zero so we're going to decrement it to two we're gonna check as two in our set yes it is so we can't have that of two and we're going to decrement it to one is one intercept no it's not and now this is our solution and we just simply keep track of the number of decrements in this case it would be two now let's do the same thing for this other word c e a b a c b okay so for once we make the counter remember we just need the counter to get the values we don't really care about the letters so we have a 3 B is 2 C is two and E is one there we go we're going to get these values and we're going to sort them so our sorted list would look like this right and obviously this wouldn't work because two and two have the same count so we are going to fix that but let's just go through our algorithm as we did it before so we're going to have this set and we're going to go through our values and just check is it in there so we're gonna T is the one in the set no it's not okay is the two in the set no it's not now is this two in the set yes it is so for this 2 it is in the set so we're going to need to decrement once now we have one is one and it said yes it is we decrement to zero and zero is always going to be acceptable and we never need to add it to the set so decrementing to zero like as soon as it's zero we can be done with that number and move on and so far we've made two decrements so our count is two that we made now for this one is three in the set no it's not so we can just add it in and so our total decrement is two and as you can see it is there so that's pretty much it you literally just get the counts which in Python there's a counter that I'll show you that is literally one line and then you get the values you sort them and you just go value by value and you make sure is this value okay or do I need to keep decrementing remember you can't all you can do is delete characters so you're going to keep deleting characters until it's either zero or it's something that we haven't used before to make sure uniqueness now the nice thing like I said this set is O of one space because the most it can ever have is 26 numbers right this sort is O of one time because 26 numbers and when we Loop through the character and we decrement for every character the most we can ever decrement it is 26 times so for every iteration of the loop the most that can ever happen is 26 times which is also of one so the nice thing is by using all these letter things using a letter is much better than like looping through this term because you can only have 26 letters so you can treat that as constant time and space for most of these things so let's uh code it up and it will go over the actual like timing space for this solution so we are we need to get the values in this calendar so we're going to say values equals sorted what sort of does is it sorts something we're going to want to get the counter of s which is just the key value pairs right but we don't want the key value pairs we just want the values so we're saying let's get the counter of s so for example if we had a b c it would be like A1 B2 and so on that's what the counter would give you if you give you a dictionary of these V2 C3 and now the values just gives you an array of all the values so values would give you one two three we want to sort them as well now we are going to have taken values which are going to be a set and that's going to represent all the values we've currently used and every value we need to make sure we haven't used it before and we're going to have a result so then we can have four value whoops oops or value in values we just need to record it somewhere right like original value or something maybe value and then we can say uh yeah we can say while just say value in Taken values we need to keep decreasing it right so we need to say value minus equals one then we need to check what the value is so if the value is non-zero then we need to add it to our non-zero then we need to add it to our non-zero then we need to add it to our set so if value is non-zero then we can set so if value is non-zero then we can set so if value is non-zero then we can add it to our taken values otherwise we don't really need to add it because we don't need to add zero we just stop there right and then we need to add however many subtractions we made and the subtractions we made are going to be original value minus value right so we did some number of subtractions so let's say we had three we need to go down to zero that's three subtraction and so on so number of fractions is the original value minus the value finally had at the end and then finally we need to return Little T no private misspelled as always and let's take a look and you can see it's pretty efficient and that's the nice thing about even though you have all these Loops let's actually go over the time and space here just to explain it one more time so if you think about it this counter so making the counter is actually going to be not of one right because we do have to Loop through the entire string so we do have to Loop through the entire string let's call that o of n but once we get the counter remember it's 26 keys so sorting 26 is of one now we get the set then for every single value and values remember we only have 26 values constant number and then here we also have maximum 26 so it's a for loop it's like a nested for Loop but the upper bounds of each for Loop are only 26 so because it's constant this whole thing you can consider as o of one because like I said no matter how big your string is this can you can only have 26 values and you can only have 26 items in your set so the most you'll ever decrement is 26 times so the biggest thing this can run is 26 times 26 which is like you know 500 which doesn't really matter when your number is like 10 to the ninth or something right it's basically it doesn't matter so the time is actually going to be oven which is just traversing through the string and for the space that's the other nice thing I would argue here so this counter is of one space because like I said only 26 letters these values an array of only 26 maximum taken values set of only 26 numbers maximum so this set is oh one space this counters o one space this value is a one space now if your interviewer did ask you like well if it is an O of one what can you represent it is then you would say like okay yeah so if you don't want me to counter zov one then I would basically have to figure out like how many unique characters are there in here and then the counter would basically be of like let's say unique character is called like you or something then the length of the counter would be you and then the length of values would be you and then sorting it would be like U log U or whatever right if you wanted to talk about that and same thing here it would be U times U for this part for the time and so on but I'm gonna say for my case the time is of N and the space is of one because like I said you could only have 26 characters per Max so that's a constant space and time and yeah that's gonna be it for this problem hopefully you enjoyed it like you saw we have a pretty good solution here and uh yeah if you did like the video then please like it and please subscribe to your channel and I'll see you in the next one thanks for watching
|
Minimum Deletions to Make Character Frequencies Unique
|
can-convert-string-in-k-moves
|
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.
**Example 1:**
**Input:** s = "aab "
**Output:** 0
**Explanation:** `s` is already good.
**Example 2:**
**Input:** s = "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ".
**Example 3:**
**Input:** s = "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters.
|
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
|
Hash Table,String
|
Medium
| null |
9 |
in this video we're going to solve the palindrome number problem on lead code so the problem says given an integer X return true if x is a palindrome and follows otherwise so for example the number 121 is a palindrome because when you reverse it is still 121. 456 is not a pattern draw because when you reverse it is 654 and that's not the original number also negative numbers are not palindromic if you have a number with the last digit being zero it's not going to be a pattern drop either so we're going to discuss two different solutions one using strings and the other one not using strings so this is the solution that uses strings it just converts the number X into a string and it just returns true or false if s is equal to its reversed version let's take a look at the second solution so let's say x is 123 we're going to create two variables one is original X and it's just the same number and the other one is num reverse and you'll see why we do this in a second we're also going to create a table and we're going to fill this table up so here x is 123 we want to get the last digit which is number three so the formula is just modulus by 10 that's going to give you three as for Num reversed I'm going to show you the formula it won't make sense right away but once we fill up this column it will make sense so the formula is you get 0 which is right here num reverse is 0 times 10 plus the last digit 3 and that's going to give you three and then we get rid of the last digit so we want to get rid of the number three in 123 so we floor divide by 10 and that's going to give us 12. we put 12 here and then again we get the last digit which is 2 then we get num reverse which is three so we have three here times 10 plus the last digit which is 2 and that's going to give you 32 and then we get rid of the last digit so we flow divide 10 we get one again we put one here we get the last digit that's also one and then we get num reverse which is 32 times 10 plus the last digit 1 and that's going to give you 321 and then we get rid of the last digit so we end up with zero so once you get zero here we're going to look at the final value in Num reverse and as you can see 321 is not the same as the original X which is 123 and this indicates that 123 is not a palindrome let's do one more example so what if x is 121 you fill up this table and once you reach 0 you look at the last value or num reverse and you see that num reverse is 121 which is the same as the original X and this indicates that 1 121 is indeed a palindrome number so let's quickly talk about the pseudocode while X is greater than zero the last digit is just X modulus by 10 and the num reverse is just num reverse and this number reverse is initially zero times ten plus the last digit and then we get rid of the last digit so just 4 divided by 10. and after the while loop X is going to be zero and we just compare the original x with the num reversed if x is negative then it's not a palindrome number so we just return false if x is zero and this is kind of a special case then we know that 0 is a palindrome number and we just return true and from here on we're only looking at positive numbers so when X is positive and X Mod 10 which is getting the last digit and the last digit is zero then we also know it's not a palindrome number we also copy X into original X and we make num reverse equal to zero then we just paste in the while loop and at the end we compare the original X to number reversed and that's basically it for today if you enjoyed this video don't forget to subscribe if you haven't already and also share this video
|
Palindrome Number
|
palindrome-number
|
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
**Example 3:**
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
**Constraints:**
* `-231 <= x <= 231 - 1`
**Follow up:** Could you solve it without converting the integer to a string?
|
Beware of overflow when you reverse the integer.
|
Math
|
Easy
|
234,1375
|
459 |
hello everyone in this lecture i am going to explain you about repeated substring pattern so here coming to a question given a string as check if it can be constructed by taking a substring of it and appending multiple copies of the substring together so coming to example one here they give an input for the string a b so we need to find out the substring is repeating or not it is showing true explanation it is substring a b repeat twice and here coming to example 2 a b a it is showing false why this a b is not repeating twice the substring was not repeating twice so it is showing false coming to this example 3 in this string they mention abc so it is showing 4 true while it is a substring abc repeated 4 times so here how can we find that input it is a it is true or false now i will explain so here in this class we will create one method repeated substring pattern in this i will mention string str equal to s plus s and here in the written statement i will mention this string name str dot substring sti dot substring here start to n one comma str dot length minus 1 dot contains here this thing is so we'll check it will work or not yeah accepted so here in this class we created one method in this method i just assigned this s plus s to string str and here in this written statement i mentioned string dot substitution what is substring yeah the substring method extracts the character from a string between two specified indices and returns the new substring this method extracts a character in a string between start and not included and itself it will just extract the characters from start to end that's the meaning of substring so here by using this string dot substring i'm i initialize start to end and i'm comparing that with this string s so you can able to find out the string is repeating twice or not the substring is repeating twice or not it will identify in this test case they give an input a b so here i will mention again a b now i will check whether this will be a substring or not yes it is showing true and again i will change this test case if i mention over here a b now we will check it is satisfying to the condition of repeated substituting pattern or not yeah it is showing false i will submit this code now we'll check the result it will be accepting or not yes success so if you have any queries you can mention your doubts in commentary session and please do like and subscribe for more videos thank you
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
1,305 |
hey guys welcome back to another video and today we're going to be solving the leakout question all elements in two binary search trees all right so in this question we're given two binary search trees uh one of them is root one and then root two and we return a list containing all integers from both trees sorted in ascending order okay so let's just start off with what exactly a binary search tree is and how we can start off to solve this question so let's say we're given this binary search tree as an example so what is a binary search tree so it's a in simple words it's a tree based data structure which follows the rule that all the left nodes are smaller than whatever the root is and everything to the right is small is greater than where the root is for example let's take the root as eight and everything to the left of eight should be smaller than eight so over here we have three one six four seven they're all smaller than eight now if you go to the right of eight everything is going to be greater than it so over here we have 10 14 and 13 they're all greater than eight and let's just say one more example so let's take six and let's assume six to be our root so whatever is to the left of six which is four is has to be less than six and it is four is less than six and over here we have seven and obviously seven has to be greater than six and in this case that's true so now what we want to do is we know this follows a certain set of rules which all binary search trees follow and we want to extract that information in such a way that we get all of the nodes values in ascending order so this is how our output is going to look like we're going to have 1 3 4 6 7 8 10 13 14 which is well in ascending order so this is going to be for one of our trees and we're going to do the same thing for another one of our trees so that's what we're going to do but let's just see how we can do for one of our trees and then all we're going to do is we're just going to replicate it for a second time so what we're going to be using is we're going to be using the in order traversal so in an inorder traversal in simple words you go to the left then you go to the root and then after that you go to the right so let's see how that looks like real quick so our first step we're going to start off at our roots over here and we're going to go to the leftmost element so we go to the left here and we end up at the value 1. so why do we go to the leftmost element because the leftmost element is always going to be the smallest element so first we're gonna get our left most element which is well one so now we have one and now we're gonna go to our root so our root has a value of three so now we're gonna add three and now we're gonna go to our right so we're going to be ended we're going to end up at 6 but 6 is actually not a leaf so once we reach 6 we're going to go to its left which is well 4 so we're going to add that and now again we're going to go to the root and the root is six and after that we're going to go to the right which has a value of seven and why are we adding the seven year and why didn't we add six earlier the answer is because seven is a leaf right so there's nothing much seven does not have any children notes so the same way so we're completely done with this part so we're done with the left of eight so in this case we're going to go back to the root which we started off as eight so we're adding eight and now we're going to repeat the same to the right so over here we're going to check if it has any left children it doesn't so we're going to end up adding the value of 10 and then we're going to go to 14 and 14 does have a left child so we're going to add that left child which is 13 and then we're going to end up adding 14 and it doesn't have any right children so we're done and this is how we get our in-order and this is how we get our in-order and this is how we get our in-order traversal and an in-order traversal of a binary and an in-order traversal of a binary and an in-order traversal of a binary search tree is going to end up giving you a list in an ascending order so now let's see how we can write this in code all right so let's start off with our code and one thing that we want to notice is that we already have a class called tree node which is predefined for us so inside of this class we have three attributes we have one which gives us the value we have one which gives us the left uh child and one which gives us the right child okay so what we're going to do is we're going to create a function over here and we're going to call this function in order so we're going to be using this in order to perform an in-order traversal on each of our an in-order traversal on each of our an in-order traversal on each of our binary search trees so what is this going to take as arguments so we're going to give it self and we're going to give it some sort of list and to this list we're going to append our elements one by one so i'll just call this list l and we're also gonna give it uh the node so the node is gonna be the root node so it's either gonna be root one or root two okay so how are we gonna start off with this okay so over here we're gonna have our base case which is gonna check if it's a leaf or if the node even exists so in this case how can we do that so we can do if node is none or in other words we could just type if no if not node so that's the same as checking if the node has a value of none and in that case we're just going to return okay and if that is not the case else we're going to go inside of this else loop and over here we're going to call the self dot in order function so we're going to call this inorder function on itself and we're going to end up giving it the same thing so we want to give the same list which is l and we're going to give it node.left l and we're going to give it node.left l and we're going to give it node.left and the reason we're giving it node.left and the reason we're giving it node.left and the reason we're giving it node.left is because we want to go to the left first so that's why we're giving it node.left so that's why we're giving it node.left so that's why we're giving it node.left and now it's going to perform our in order uh tree and sorry traversal on the left tree left subtree so after we do that we're gonna append that node's value to our list so l dot append and we're going to append the value so node.val okay so and after we do that so node.val okay so and after we do that so node.val okay so and after we do that we want to iterate or go to the right subtree so we're going to call the function again so self.inorder so self.inorder so self.inorder and this time we're going to call it on the right subtree so we're going to give it the same list l and we're going to call it on node.right node.right node.right okay so that should be it and by the ending of this once we're done with this part we're going to reach we're going to have all of our nodes inside of our list l in ascending order so at this point what we're going to do is we're going to return that list so we're going to end up returning l so that's it for our inorder function and let's see how we can kind of work with that inside of our main function so we're going to start off by creating our list so i'll just call this list underscore and this list is going to include all it's going to include the ascending values of both root 1 and root 2. so we could create two different lists but that would actually just take up extra memory which is not really necessary so we can do this all in one list so in the beginning what we're going to do is we're going to call the self.inorder is we're going to call the self.inorder is we're going to call the self.inorder function and we're going to end up calling it on our uh on the first binary search tree so we need to give it the list so in this case list underscore and we want to give it the tree so in this case we're giving it root one so by the end of this we're going to have a list which has all of the nodes values in ascending order for the first binary tree and after that what we're going to do is we're going to call the same function but instead we're going to call it on the second binary tree here and notice how we're doing it on the same list and that just saves up memory so after this we need to sort that list so currently we have a list and half of it is sorted so the first half is sorted and the second half is sorted so now what we want to do is we want to take both of these two sorted halves and make it sorted completely so to do that all we're just going to do is we're going to call return sorted and we're going to give it our list over here so this sorted actually i didn't know about this and it's pretty interesting so what it does is it actually sorts it in a big o of n time and the reason for that is it uses something called tim sort so in this case let me just show you an animation for it i'll put a link to this animation down below so over here you can see that the first half so this part over here is sorted right it's in ascending order and this part over here is also sorted right so we have two parts each of which are sorted and now we want to make it in such a way that together combined they are sorted so let's just run this and everything actually happens in one iteration as you can see so that's what we're going to be doing and uh that actually is inbuilt into python using the sorted function so that's actually really fast and yeah so let's submit this and as you can see our submission is accepted and finally thanks a lot for watching guys do let me know if you have any sort of questions and don't forget to like and subscribe if this video helped you thank you
|
All Elements in Two Binary Search Trees
|
number-of-visible-people-in-a-queue
|
Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8,8\]
**Constraints:**
* The number of nodes in each tree is in the range `[0, 5000]`.
* `-105 <= Node.val <= 105`
|
How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start. Keep popping from the stack the elements in sorted order until a value larger than arr[i] is found, these are the ones that person i can see.
|
Array,Stack,Monotonic Stack
|
Hard
|
1909,2227
|
1,902 |
guys welcome back to another video this is educational code forces R 159 du2 and we're going to solve the first problem that is binary imbalance let's see what the problem States so we were given a string s it is consisting of uh only numbers like 0o and one so they are also telling that uh like 0 and 1 means it can be 0 1 0 anything or 1 one like that so in one operation they are telling that you need to choose an index I between the first index and the uh length of the string minus one that index the last one then uh you have to take two consecutive characters two consecutive positions and check for uh the what the equality of the strings so if both of them are equal then you can insert one suppose if both of them are equal you can insert one if both of the characters are different you can insert zero so if both of the characters are different you can insert Zer here okay and in this also suppose if you have inserted zero here this one and zero can also give birth to a new zero so the one and zero is different so you can also put one more zero here but what is our end goal is we can perform this operation any number of times and we have to report that is it possible for us to uh make the number of zeros in the string greater than the number of ones in the string so let's see this with the help of an example what are all the possible scenarios there can be scenarios where all the numbers are zero right all the characters are zero all the characters are one and there can be mix also 0 1 uh 0 1 like it can keep on going and uh so let's check for the first one so our condition is if number of zeros are greater than number of ones then you have to print yes else you have to print no okay now so they also said that it should be strictly greater it's not greater than or equal to it is strictly greater so if the number of zeros are already greater I can simply print yes right I don't have to perform any operation now is it possible for me to make the number of zeros greater here they already told that if both of them are same you can put only one you can never get a zero out of this if all the numbers are one so this is no let's see here how many ones are 1 2 3 4 5 6 7 ones are here and four zeros are only here so number of zeros are greater than number of one no right so is it possible for us to make a new zero it is possible because here if you see 0 and one it is different so you can add zero here 0 and one again different you can add a zero here similarly 0 and one is different you can add Zer here again 0 one is different you can add a zero here now count 1 2 3 4 5 6 7 8 it became eight right so if you want you can add how much number of zeros you want you can it will be zero so even if it is like only 0 1 one everything this 0o and one can give birth to a new zero this Z and one can give birth to a new zero the number of zeros can be more so from this we understand that if all the numbers are one the this condition is never possible or else it is possible so in the example also if all the numbers are zero it is possible if all the numbers are one it is not possible if all the if any of the number is one and any of the number is zero also it is possible so how do we do the code is uh very easy like initially we can default it to no and then in the for Loop we can say that if any one zero comes in the string then I can simply uh assume the answer is yes and come out because we know that we already proved it so we also know that this is the solution that is being submitted and accepted so if you have any doubts please let me know in the comments and until then see you in the next video thank you so much
|
Depth of BST Given Insertion Order
|
car-fleet-ii
|
You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
* `order[0]` will be the **root** of the binary search tree.
* All subsequent elements are inserted as the **child** of **any** existing node such that the binary search tree properties hold.
Return _the **depth** of the binary search tree_.
A binary tree's **depth** is the number of **nodes** along the **longest path** from the root node down to the farthest leaf node.
**Example 1:**
**Input:** order = \[2,1,4,3\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 2:**
**Input:** order = \[2,1,3,4\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 3:**
**Input:** order = \[1,2,3,4\]
**Output:** 4
**Explanation:** The binary search tree has a depth of 4 with path 1->2->3->4.
**Constraints:**
* `n == order.length`
* `1 <= n <= 105`
* `order` is a permutation of integers between `1` and `n`.
|
We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration. We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection.
|
Array,Math,Stack,Heap (Priority Queue),Monotonic Stack
|
Hard
|
883,2317
|
413 |
hey everybody this is larry this is day three of the leeco daddy march challenge hit the like button hit the subscribe button join me on discord let me know what you think what is this huh um but yeah uh so today it's been a little bit of a hectic day so hope you don't mind the weird setup i'm in a new place again because um how to say this but basically i think i ran into a scam on airbnb um the airbnb host um well one thing is that apparently it's not legal uh airbnb is not legal in colombia which i did not know but um so yeah so they basically held me captive because the security guard uh wouldn't let me out until i don't know there's a lot of things i was basically could not get out of my old apartment for about like a couple of hours uh until i think it would be i don't know the exact details to be honest because a friend handled it for me so i don't speak spanish so uh so yeah so it was kind of a stressful mess i guess um but i'm here now uh but i think like airbnb security was good and i don't know they dealt with it in a good way and we were finally able to leave so but now i'm in another uh hotel in medellin um yeah so now we're here it's been a fun day but i am here and if you want to check that out hit that uh up on instagrams uh i am a little bit couple of days behind on honestly so yeah uh anyway so today's prom is and that's what you came here for hopefully you enjoyed that little side story uh be careful when you're doing airbnb in colombia apparently um but yeah it's a 413 of arithmetic slices an individual way it's going to work we take what you can just say three inches with difference between two okay so given an your right numbers return the number of sub arrays okay so this one should not be that bad because i think so i think the one the first observation that i would make is that um when you have sub arrays like this for example well this one is just a very basic example right one two three and four and then the idea is that if your longest sub array and this is sub a way not to be confused with subsequence if you have a sub array of length uh two or sorry of length four that you can do the math because um because you can just do the math on like the number of uh um sub ways that added on right so basically for example in this case uh one way that you can think about it is that um yeah so you have so when you get to one two and three you have okay just one sub array right and then now you notice that you can extend that to four well the four means that you have a length of four um on this on a sub array that means that well um you can do the math but that means that there's one it so length of four means one sub array of length three and one sub array of length four right and you kind of generalize it of course let's say this five then length of five means one sub array of length three one sub array of length four and one sub array of length five so that's basically um some of this idea and from that you know it just becomes checking out or like as you continuously build your sub array um to check out like the length and then just keep track so it's a lot of things that i call bookkeeping which is just another way of saying you know just keeping track of where things going and stuff like that right um not too bad i mean this is a medium after all so yeah so that's kind of uh i think we can we have enough to kind of dig into it um let's see so let's just say we have the total is going to zero streak as you go to um maybe we start with zero for now um and then maybe last delta just to kind of have it up um so yeah so then i know that this isn't okay fine maybe we don't do it that way so n is equal to the length of nums and then now we have for i in range of n minus one say um so then we can compare you know uh so previous is you go to num sub i uh and then current is you go to num sub i plus one say um in this case now we have okay if okay so delta is equal to current minus previous if last delta is equal to delta then we set this and of course in this case we always set streak to two as the default case now that we see it because maybe two number we can um you know if every two number is always going to be two anyway um yeah and then now yeah and then else l streak is equal to two because now the two numbers define a new streak right so this is gucci and of course uh in this case last delta is you go to delta you could also put it here it doesn't really matter obviously it doesn't change because it's the same and then now total we add as we said this is just streak minus two because uh a streak of length three has one a string a streak of link four has two dot and of course we want to make sure that this is positive because of street so i guess we always said streak as you go to two this is always going to be positive but i like to make sure i suppose and after that we just return total and that should be maybe it this is actually kind of crappy examples so we want to have slightly more tighter examples as well uh and then maybe something like i don't know something like that i don't know right like you can make things up as well um and of course this is gonna be n square um and the answer is gonna be n square ish in growth so um i say that because if you use a language that isn't python um just to kind of see how uh how many uh you know like you need to use long i guess that's what i'm trying to say um but yeah this still looks good and it looks varied enough for me to grow maybe i should try negative numbers as well because i've been going up the steps uh but otherwise i feel i'm confident about this in general so yeah maybe there's some bass case that i'm missing but for that otherwise let's give it a submit now there you go 702 days of streak um yeah so one thing that i'm really bad at least on this video it's kind of articulating the um the complexity i usually do actually think about it complexly before i implement it um this one is going to be linear and when i see or think about linear as a solution i go okay then i don't really have to think about complexity because it's linear right or maybe another way of saying it is i already thought about it so yeah in this case we have over one space because we just have a couple of variables um and all of and time because this is just linear going a for loop looking at each element and his neighbor right so yeah um that's all i have for this one uh let me know what you think this is day three so we'll you know we have a 700 two day streak so we're not going to end it now i hope unless something happens it's not going but uh so yeah let me know what you think come join us on discord come you know join our group and uh and just do discord together i'll see y'all later um yeah stay good stay healthy to good mental health i'll see you later bye
|
Arithmetic Slices
|
arithmetic-slices
|
An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences.
Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 3
**Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 5000`
* `-1000 <= nums[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
446,1752
|
1,898 |
hey what's up guys uh this is chung here so this time uh lead code 1898 maximum number of removable characters i'm gonna upload this one okay so you're given like two strings s and p right where p is a subsequence of s and you're also given like a distinct zero index integer array removable containing a subset of indices of s and your task is to choose an integer k right such that after removing the first k uh first k indices right from this removable from this uh s uh after removing those you know p is still like a subset of s right so and you need to return the maximum k you can choose such that after removing the first case indices from this uh from this sub from removal and then piece do a subsequence of s right so for example we have this abc acb so the psab and the removable indices are is it's like this right three the third index three one and zero so in this case we can remove the first two indices because as you guys can see uh after removing the first uh index uh the third one and the first one you know it's still like a super set of p right but if we remove the second one sorry but if we keep removing the uh does it the first one you know then basically this a b c a c b so if we remove the third one and the second one the so three third one is this one right zero one two three this one is gone and the first one the index one is gone right as you guys can see this one accb is still like super set off a b but if we keep removing if we're removing a in this case now c b is not a super set of a b that's why the answer is two right so that's basically the idea you know and there are some like other examples so the constraints are like constraints like 10 to the power of 5 right i mean this problem you know i spend a lot of time trying to figure out like an optimal like a better solution because you know i think all of you knows that you know given like uh as an uh s and p we can check if p is a subset of s in off in time right so basically we use like a two pointer technique right we have this kind of uh s here and then we have another a p here basically we have a p one pointing to here and then we have p two pointing to this p all right so but never basically the p one keeps moving forward and whenever we see a matching character with the p2 basically moving forward by one right so by the end p1 reaches the end we check if p2 also reach the end if it is and then it's a subset otherwise it's false right and this is the o of n time complexity right so but given the 10 the constraints is 10 to the power of 5 you know if we check the removals uh one by one basically we check if we remove the first one right after removing the first one you know it's going to take like of end time if we check the first two it's going to take another o of n right so and then so on so forth basically if we do it in that way it's going to be a o of n square time complexity right so you know that's why i spent a lot of time trying to find like a pattern to see if we there's like a o of n time complexity where you know if we can find a way of maybe smartly or more efficiently to it to detect this kind of uh the position here right um but you know it turned out i couldn't find a better way of doing it so in the end it turned out you know it's a binary search problem you know surprise huh because you know it's basically so what is the uh what is this increasing or decreasing trend here right so basically the more you remove the uh the more unlike the more unlikely you will the p will be a subset of s right because since we're always removing from the first one until some low position right basically the more the so basically the bigger the k is you know uh the subset the chance of sub subset is smaller right so basically by the time k is increasing and the subset the chance of subset is decreasing so there has to be a like intersection here right where this is the biggest k right basically after this one you know if k keep increasing like a 2k plus k plus one and then the subset basically did this check function right sub p will not be a subset of s so in the end there's no fancy algorithm here you know like if we can find like a better algorithm you know but maybe efficiently or smartly somehow use this kind of thing to skip something in us but i had at least for me it didn't work out for me that's why you know in the end we have to go back to like a more basic uh improvement which is a binary search right like i said since we have this kind of increasing and decreasing trend here it's a candidate of binary search right where the uh basically we keep incr we binary search this k here right and then we're gonna have like a helper function right so the helper function we have a middle point here right and since we're getting this uh we're getting we're searching the maximum right so i think i have already talked about few binary search problems since we're getting the maximum it means that you know l will be equals to mid middle when the when this helper function is true right otherwise it's going to be uh going to be the right equals to middle minus 1 right and the hyper functions is just the given the middle which means that we're going to remove the first from zero to middle index can p still be the in can still p still be the subset of s so that's it all right and since we have the binary search you know let's write the binary search template first basically we have the end it's going to be a length of removal right so the left equals to zero right r equals to n minus one because in my case uh this middle means that from index 0 to this index to this middle index so middle is included that's why i use r is equal to n minus 1 here and while as r is smaller than this one right basically is going to be the plus r minus l plus 1 this one right and then we have a if can remove right so basically uh i'll call it helper function you know or um okay so let's can remove so we pass in the middle right basically this one checks if by removing zero to e to middle index if p is still in the subset of s then we know okay uh l is going to be the middle else r is going to be the middle minus one right and since we're getting the maximum right the maximum will be l is equal to middle otherwise if we're getting the meat the minimum it'll be r equals to middle in this case but since we're getting the l we're assigning the middle to l we need to do a plus one here right so because this one otherwise you know if l is equal to zero and r is equal to one right so if we don't do plot plus one here you know as you guys can see the middle will be stuck at zero forever right that's why we need to do a plus one so here we return the uh the l plus one because we are returning the uh we're returning how many case we can remove and this l and r it's uh it's zero base but k this is one based right that's why we're going to remove l plus one but there's one uh more thing we need to be careful here is because remember this template so what the system is telling us it means that you know we're assuming there is an answer between the l and r right so which means that no but you know there's a but it could also be the answer is zero means that you know the uh we cannot remove anyone right because as you guys can see so even l is equal to zero we're still returning one means that we're assuming by looking at this one we're assuming there's always an answer right there but between this zero and n minus one i mean for most of the binary search that's the case but for this one you know at least the way i write it you know it could also be a case that you know the binary search will not give us any result which is the zero case so in this case uh we can simply do a uh one more check here basically we return the l plus one you know whenever this l is equal to r we do a one we do one more check so this one right and then else zero right that's the easy fix here and then the only thing left is that can remove helper function right can remove it's going to be the middle so this one is pretty straightforward right so it's like a similar it's a very standard uh subset algorithm plus a lead one more condition basically i have a j is equal to zero so this one is a pointer of p right and then since we have we need to remove something so which means we're gonna remove set here right it's going to be a set of removable right of this first middle index right see i'm doing this kind of set so that i can check the existence within one time so and then the algorithm so we look through the first uh n1 so this is going to be a length of s right and one and then n two is going to be a length of p okay so here we look through the remove the first pointer so if i is not in the remove set okay and as i is equal to the pj then we re increase we move the second pointer forward and then if the j is equal to n2 we return true right otherwise return false in the end so yeah i think that's it if i run the code what oh yeah so this slice is already like a list okay submit cool so it passed right because as you guys can see so the time complexity for this one you know the binary search this one is log and the can remove here this is a often right so that's why it's all as unlock and solution here and it will pass yeah i think that's it right i mean it's an interesting problem but you know i see why people give it a lot of downloads here because i think a lot of people might have done the same similar thing as i was trying to do right basically trying to find like uh a new algorithm that can solve this problem you know this uh can check p if the subset of s uh this is removable within o of n time but it turned out there's no such algorithm that's why we have to go back to the very basic improvements which is the binary search okay right because the uh the k in the increasing of k will cause the current remove going down that's why we can use binary search cool i think that's it thank you for watching this video guys and stay tuned see you guys soon bye
|
Maximum Number of Removable Characters
|
leetflex-banned-accounts
|
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**).
You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters from `s` using the **first** `k` indices in `removable`, `p` is still a **subsequence** of `s`. More formally, you will mark the character at `s[removable[i]]` for each `0 <= i < k`, then remove all marked characters and check if `p` is still a subsequence.
Return _the **maximum**_ `k` _you can choose such that_ `p` _is still a **subsequence** of_ `s` _after the removals_.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
**Example 1:**
**Input:** s = "abcacb ", p = "ab ", removable = \[3,1,0\]
**Output:** 2
**Explanation**: After removing the characters at indices 3 and 1, "a**b**c**a**cb " becomes "accb ".
"ab " is a subsequence of "**a**cc**b** ".
If we remove the characters at indices 3, 1, and 0, "**ab**c**a**cb " becomes "ccb ", and "ab " is no longer a subsequence.
Hence, the maximum k is 2.
**Example 2:**
**Input:** s = "abcbddddd ", p = "abcd ", removable = \[3,2,1,4,5,6\]
**Output:** 1
**Explanation**: After removing the character at index 3, "abc**b**ddddd " becomes "abcddddd ".
"abcd " is a subsequence of "**abcd**dddd ".
**Example 3:**
**Input:** s = "abcab ", p = "abc ", removable = \[0,1,2,3,4\]
**Output:** 0
**Explanation**: If you remove the first index in the array removable, "abc " is no longer a subsequence.
**Constraints:**
* `1 <= p.length <= s.length <= 105`
* `0 <= removable.length < s.length`
* `0 <= removable[i] < s.length`
* `p` is a **subsequence** of `s`.
* `s` and `p` both consist of lowercase English letters.
* The elements in `removable` are **distinct**.
| null |
Database
|
Medium
| null |
206 |
so we are given a linked list and we are given the hair of the singly linked list and we act are asked to reverse the list so basically what I'll be doing is we are flipping the arrows here so we flip the arrows from five to four from four to three to two to one then we get our reverse link list now what's what could be the logic behind slot meat I'll show you the logic that I use and basically this logic is used by most of us like many of us and this is like the very popular logic and if any of you are using something new then please let me know in the comments below okay so we are given our hat and we know the end of the root I mean like the end of the link list always points to null right even though we cannot see because it's null so the next of the last note always points to know so here you here also um one is actually pointing to null now we that is what we want to do here right so what I'm gonna do is I take a variable previous so I Define a variable previous I um put a value null here and then I take my head and then um what I want is my head next of my head that is of current value 1 next to point two null right so head that next I'm just writing in the sort form head that next equals to so I'll put point it to my previous value okay so that this is what I what uh I will have to do to point one To None now let's see so what I'm gonna I'm doing here is I have my heat I Define a previous let me just use variable p is equals to null and then here my head next of my head is pointing to previous so what I do is I point it to here now see here what's the problem here um so once I change the next of my head to point to something else I lose the track of my other data so I lose this data here now there is no way I can access this data because there is no variable pointing to this data right so before I actually change my next pointer to point to the previous value what I'm gonna do is I need to create a variable next so next before pointing it so next I'll just write n and then next should be the next of the head so this is how we actually store the next of the head and now I have the next of the head I have the previous value now I change my pointer of hate to point it to the previous value so this will actually be removed automatically and next what I'm gonna do is I'm going to iterate the same thing again so now my previous becomes my head so this is my previous now and my head becomes the next value here and my next becomes the next of my hate so now I'll do the same thing again I'm repeating this thing again so what I did is after my head next I um my previous value becomes my hate and then my head becomes my next and then now I'm repeating this thing again so I keep on repeating this whole thing foreign of next becomes the previous so this will point in this direction and then my previous becomes head so now my previous becomes my head and my head becomes the next note and my next note becomes the next of the head so you could see we are doing the same thing repeatedly right uh you could see like this could be uh this is a Sub sub placed and I did the same thing with this list I reverse list and now I'm gonna do the same thing with this thing as well right so I'm just all I'm doing is Shifting my previous and my head and the next is just the next of the head so let me dive into the code so we are gonna build a recursive function and one thing the age case so um when my head um let me just show you the edge case um when I have done all of these and these right so at that at this time my head is here this is my previous and this is my next and then I move my head here before that I actually move my previous to my head and then my head to the next and mine next is equals to another right and then I change the arrow here and then again my previous becomes equals to head my head becomes the next and my next is yet to Define determine but here look here um if I try to calculate my next which is equals to A next of head I'll get an error so when my head is equals to null that is when I stop and then I return my answer and my answer is stored in the previous right so that is where what my age case will be so when my head is null I return my previous I'm just gonna change modify the whole function previous and initially previous will be no as I told you earlier I defined previous to be not right so that is what I will be doing here and then now um my previous is now so now my I have my head now I need to Define my next so that I have the next right now I have my previous I had my next and hit and I have my next now I'm gonna change the next of the hair to previous and then my pre and then I'm just gonna call the function again I review ers r-e-b-e I review ers r-e-b-e I review ers r-e-b-e oops reverse list so my head new head is the next right new head is the next and I shift my previews to head so this is what I do oops my new head is my next and my head is my previous is my head now and my head is the next that is what I did here right I changed my previous two head and my head to next so that is what I'm doing my hair is next my previous is the head and then finally um returning that value yeah cool let us check some more Rich cases I mean some more test cases great um let's submit it now talking about the time complexity is off and because we are traversing through all of the notes right so it's off and the space complexity is off one because we are not using any space at all okay have a great day guys
|
Reverse Linked List
|
reverse-linked-list
|
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[5,4,3,2,1\]
**Example 2:**
**Input:** head = \[1,2\]
**Output:** \[2,1\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is the range `[0, 5000]`.
* `-5000 <= Node.val <= 5000`
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
| null |
Linked List,Recursion
|
Easy
|
92,156,234,2196,2236
|
152 |
we are going to solve maximum products sub array problem today it's a medium kind of problem on lead course it's a problem related to array so let's look for our problem statement we are given an integer array nums and we need to find out a sub array within the array that is the largest product and we need to return the product and we know a sub array is a contiguous subsequence of the array so the Brute Force way of solving this problem is to generate all the possible sub array and find the product for each sub array and return the maximum among all of those so let's try to generate all the possible sub array for the given array so initially our sub array is empty it's not containing any element so initially it's containing only one element that is two so this is our sub array and its product is 2. now we extended our sub array to contain two elements 0 and 1 and its product is six now we extended our sub array to three elements and its product is -12 elements and its product is -12 elements and its product is -12 now our sub array is containing the entire elements of array and its product is minus 48. now we are going to generate all the sub array now there is no more sub array possible so the maximum value among all of these sub array is 6 so we are going to Output 6 as our result so here we are getting 6 as our output so what will be the time complexity in this way so the time complexity will be o n Square just for generating all the sub array plus the cost of multiplication for each sub array let's call it C so the overall time complexity will be o n Square which is quite big for a sub array problem because when there is a problem related to finding a sub array inside array we can solve it in linear time now let's try to find a solution in linear time so the problematic path here is a negative number if everything is positive this problem is quite simple we can find a solution in over time just by multiplying all the elements but the difficulty came when we are having a negative number so we need to take care of this negative numbers because these negative numbers are going to play a very important role I am saying this because when we multiply two negative quantity we get a positive quantity so that's why we need to take extra precaution when we are dealing with a negative quantity because the negative quantity can multiply to a big negative quantity and make it a positive quantity so we need to take care of this fact that when a negative quantity multiply with a bigger negative quantity it turns out to be a bigger positive quantity suppose we are given two values one is positive let's say five and other is minus 10. so we are given these two values let's say a is this one and B is any of these two numbers is going to multiply with the unknown number and we need to find out the max product at this point we can't discard this minus 10 here because we don't know what is this next upcoming next element is if it's a negative element then it can multiply with this negative value and result in a Max product and if it's a positive value it could be get multiplied with this positive number and is going to give us the max product so we need to have these two elements we can't discard one that this is a negative thing so I will discard this one because this is not going to give us a Max product because this statement is wrong because the next item which we are going to multiply in any of these two values could be either positive or negative so if it's positive it's okay it will be multiplied with the biggest element from A and B and give us the max product if it's negative it's going to multiply with the negative element and give us a Max product so for our sub Arrow also we are going to maintain these two things if our sub array is ending at some index let's say X so we are going to maintain what is the maximum product sub array ending at this x index let's say positive Z and what is the minimum products ending at index X so let's say it's minus Z so we are going to keep track of both the product so that when we are going to extend this sub array if the next item is positive then also it's okay for us because we are keeping the track of positive product if it's negative then also it's fine for us we are able to find the next product ending at X Plus 1 because we have the both the information positive and negative whatever the sign of this X Plus 1 element we are going to get our maximum product somewhere possible till X Plus 1 so for finding that maximum product sub array we need to keep track of these positive and negative products so let's solve one example let's suppose we are given this sub array now initially our Max and min is going to contain 1 because initially our sub array is containing no elements so that's why this both are one and our result is going to contain minus infinity now we are going to start our Loop so we are going to consider first item that is -2 so the maximum product sub array -2 so the maximum product sub array -2 so the maximum product sub array ending at index 0 is -2 by taking the maximum of Max into is -2 by taking the maximum of Max into is -2 by taking the maximum of Max into the current element and Min into the current element comma the element itself so if any of these thing is giving us positive quantity we are going to take that so this thing is going to get updated with -2 and this will also become -2 and with -2 and this will also become -2 and with -2 and this will also become -2 and this will also become -2 this will also become -2 this will also become -2 now we are going to go for next item so that is C so what is the maximum product possible here this will be only 3 only this the barrier itself so this is going to become 3 and this Max is also going to be 3 and this Min is going to be -6 so the and this Min is going to be -6 so the and this Min is going to be -6 so the maximum product sub array ending at index 1 is 3 and the minimum products the barrel ending at index 1 is -6 -6 -6 consider the next item so that is minus 2 so we are going to update our result variable using our formula so this will be 12. and now our Max product will be updated to 12 because the negative quantity minus 6 and this negative quantity minus 2 multiplied to give us the bigger positive number so that's why our Max product is 12 and the main product is -6 now we are going to look for our next -6 now we are going to look for our next -6 now we are going to look for our next item so the next item is four so the maximum product will be 12 into 4 that is 48 so we are going to update it with 48 now this Max will also be get updated to 48 and this minus 6 is the smallest possible now the smallest possible will be this one that is minus 24 so this will be updated with minus 24. so the 48 is the our biggest possible so what we are doing here we are just trying to keep track of the min main product and the max product of sub array ending at that index so that we can easily find out what will be the maximum product possible at the next index so this is how we are going to tackle our negative numbers now there is one extra catch here for this zero number if we are getting 0 we are going to just update our Max to 1 and Min to 1 because this if it's the 0 we are not going to append this in our current sub array so we are going to start our sub array from the next item so that's why we are going to append our Max and Min to 1. so what will be the time complexity here so the time complexity will be o n just one traversal and the space complexity will be o1 so we are going to start our coding we need two variables to keep track for the maximum product and the minimum product initially both are one now one is our result variable which is going to keep the product of the maximum product sub array so it will be initialized with infinity now let's start our traversal of the array so we need to tackle the zero case then we need to reset our Max and Min variable otherwise we need to calculate our maximum product and minimum product including the current item in our sub array now we need to update our Max and Min variables so max p is equal to Max of temp either the product of previous sub array minimum previous product into the current item so that is stored in Min p and it could be just the current item itself similarly we need to update our Min variable now we need to update our result now we need to return our result variables so that's our code let's run our code okay so it's giving us correct output let's run for example test cases okay so it's giving us incorrect because here we need to update our result variables so result is equal to Max of result and 0. now let's run our code once again yeah so it's given us correct thing let's submit our code okay so it got submitted bit efficient and space complexity is also good so yeah that's it for today I hope you found this video useful see you next time
|
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
|
309 |
hello and welcome back to the channel so today we are discussing lead code problem 309 and this is one of the many variations of stock Buy sell problem I've also added one hard level variation of stock buy and sell on the website so I added on the website because it is a blog post type of a tutorial and it is not possible to add blog post on YouTube so just in case you're not aware we also have a website hosting different study resources and everything on the website is also completely free of cost so just in case if you want to check out so let's quickly go through the problem statement first so you're given in Array prices where prices I is the price of a given stock on the ith day Now find the maximum profit you can achieve you may complete as many transactions as you like that is buy one and sell one share of the stock multiple times with the following restrictions after you sell your stock you cannot buy on the next day so there's a one day cooldown period and also as a note it is given that you may not engage in multiple transactions simultaneously so which means that once you buy a stock you cannot perform another buy operation so once you have bought a stock you need to sell it wait for one more day and then buy another stock let's try to solve it using an example assuming that we have a prices array which looks something like this now let's try to analyze the situation at cell 5. so there are three possibilities at any particular cell two possibilities are that you take no action at a cell or you buy the stock at that cell in both the cases you would not be making any new profit a profit can only be made when a stock is sold since you are not making any profit at cell 5 when you're performing any operation other than selling the stock so the profit till Cell 5 is going to be equal to whatever profit you have earned till cell 4 so profit till this point is going to be equal to profit till this point now the third possibility is that you sell your stock for five rupees in order to sell your stock for five rupees you first need to buy the stock somewhere so let's say that you bought your stock at 4. so in this particular case when you're buying your stock at four what will be the total profit that is possible so the total profit that is possible it is going to be profit that you've earned till 2. plus the profit you have earned in this transaction so the profit till 5 is going to be profit till 2 plus 5 minus 4 which is the profit you've earned in this particular transaction so why are we taking profit till 2 that is because in the question it is given that we have a one day cooldown period so if we would have made any new profit at 3 that implies that we would have actually sold our stock on three and if we would have sold our stock on three we cannot buy it at 4 we would have to wait one day at least to buy this stock so buying a stock at 4 implies that we did not sell it on three and if we did not sell it on 3 that implies that we did not earn any new profit on three that implies that whatever profit we have earned we have only until two so in order to buy at 4 we have to take profit till 2 only because that implies that we did not make any profit at 3. similarly another profit is that you bought your stock at three So when you buy your stock at three the total profit is going to be profit till 1 plus the profit in this transaction so again profit till 1 because we have a one day cooling period again similarly the logic can be extended when you buy your stock at two So when you buy your stock at 2 profit till 0 plus the profit earned in this particular transaction now for the remaining cases we can only have one transaction it is not possible to have multiple transactions because if we are buying our stock at one it is impossible to complete a transaction before this so when we are buying at one the only possible profit is the profit we are going to get in this transaction which is 5 minus one similarly when we are buying at zero the only possible profit is the profit for this transaction which is going to be 5 minus zero so out of these five possibilities whichever is going to give the maximum answer that is actually going to be the maximum profit which is possible till 5. now this logic applies to all cell and the profit for a cell as you can see is only dependent on the cells on its lift so if we start calculating the profit from left to right and as we calculate we keep storing the profits and directly use the calculated profit to calculate profits for cells on the right we would be essentially using tabulation DP method for solving this problem so let's see how it works in our code so we have taken a helper array this array is basically going to store the maximum profit till that particular cell now as we discussed we are calculating the profit left to right for each cell and there were three possibilities that we discussed out of those two possibilities did not give any additional profit or did not add to the profit and therefore if we are performing those two operations at a particular cell then the profit at the cell will be equal to the profit till the previous cell so essentially this particular statement is taking care of those two operations so when we are not making any new profit at this particular cell The Profit at the current cell is equal to the profit at the previous cell so that is why we are just storing the value now in this particular Loop we are checking the case where we are actually making a profit at this particular cell by selling our stock at this cell so in case if we are able to make more profit by selling at this particular cell the value will be updated in DP of I so again when we are selling at this particular cell we can buy the stock at any previous cell so we have to consider all the cases we have to consider buying stock at every possible will sell on the left so we are taking each cell on the left one by one and we are assuming that we are buying the stock at that particular cell so the profit will actually have two contributions so first contribution will be from the current transaction selling at I and buying at J that will be the first contribution to our profit and the second contribution to our profit was the profit that we made till the previous day and as you can see that we have left one day in between because that is going to account for the cooldown period so leaving one day as the cooldown period and then checking that what was the maximum possible profit till that particular cell so these are the two contributions to the profit now adding these two contributions if this total profit comes out to be greater then the profit that we have achieved till now we are going to update the profit value in the cell now the answer variable actually stores the final answer or the maximum possible profit in all particular cases so while we are calculating the different possible profits we are actually also updating our answer because this is going to finally store it the maximum possible for the entire array and once we have calculated the maximum possible for the entire array towards the end we are just returning that answer now talking about the time and space complexity is Big O of n because we are using in helper array of size n and time complexity is bigger of n Square so for every cell we are checking all cells on its left so for the first cell there will be one operation for the second cell there will be two operations for third cell three operations and so on so the total operations are going to be n into n plus one by two so which gives the time complexity as big of n Square so if you have understood this problem do check out the hard level bonus problem as well and with this we can end this video here thanks for watching bye
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
278 |
welcome ladies and gentlemen boys and girls today we're going to solve one of the coolest questions which is first bad person so basically what the question is saying like you are working in a product manager company okay you develop a new product unfortunately the version is not good it fails the quality check okay so you have to check which uh you have to check the previous version all the version after the bad version okay so basically what they're saying let's just say we are working in a google let's just say okay we will work in google okay so it's saying like we develop something let's say android ios so for example if the android ios version let's say 1.4 is bad okay so version let's say 1.4 is bad okay so version let's say 1.4 is bad okay so let's force impressive my version 4 is bad but if we produce any version after this if i produce version 5 version 6 they all will be bad because there is a defect in version 4 so the after this version already will be effect and before this one then let's say we have version 1 version 2 and version 3. they all will be good why because the first defect occurs in version four okay so there's another question thing like we have to detect in which uh first version the defect has come so if you look at this input they're saying n equals to five so the n is five it means we have five versions version one version two version three version four version five okay so it's saying like the defect occurs in uh version four so we have to written the full version okay so that's how it looks so now you're asking like how we're gonna solve this question so for this question we will use two approaches one is linear search which you could exit the time limit and another is binary search which will go faster than any anything else because this is go o of just takes off and so hopefully this will go 100 okay so let's just see how we're going to solve this question so i have the question is understanding what the question is saying so i give you a little good example if you don't then don't worry then i will explain you like explain you the dragon of the code right so let me just erase everything over here and so first of all like uh we are working on the linear search so first of all i will show you the linear search approach okay so just in case you want to know okay all right so first of all what i'll do i will simply run a for loop from end i equals to one okay because if you look at over here they are saying uh the version start from one till n okay so i will run this flow from i one to i less than n okay but i will increment and i will call on if condition i will say is bad version now say what that is okay so basically like how can you detect like whether the version is bad known so they called it they are they have given an api called bool is bad version so this bad version api helps us to detect which version is bad okay so we just have to put the connection over here and it will detect which one is the first one which one is bad also i will say is bad version and it's my n so if you know if it's i so whatever the first better version i will find i will just simply write it over here i okay uh and really have written something over here as well so i will simply return and over here okay for instance like because you know if we don't written that it will give an error right so let me just run this code and let's see it's gonna working or not and here we go so it's accepting the run time is one millisecond if the test case are very worse if you look at over here the constraints can be go up to about 30 31 i hope so this will go time limit accident i hope so and taking your time let's see and have you guys so it's good time limit access for this input okay so as i told you like a linear is not an optimal approach to solve this question so what i will do we will use binary search to solve this question now you say like dude how the binary search will help okay so let's just say we have something like uh like i told you like we have uh version of like one two three four five six seven eight okay and we you know how we use the binding research if you know so we created even low over here and we could have one high over here and then we will calculate our mid okay so this mid will be this one so it is even so it can be this one either this one okay let's say we go to this one and our version defect is the number fifth so this is our fifth one then it defected let's say so i would say like it uh defect is fifth okay so now how we're going to calculate we will first roll calculated mid and we will check so like which is mid we will check is made is a defect version or not so we will say no midi is not a different version then what i will do i will stop looking at this one because it means like if midi is not a default version then you know what did it mean so it means like before the mid there is no effect percent so which means the further wait there is no difference so many the defect version can be after the middle okay so what i will do i will just simply move my low okay i will simply move my low from over here to a mid plus one over here okay i hope you know how the binary search work if you don't know then check out the video of binary search i have created okay all right so i move over here low so now i will again calculate the mid so we have how many uh one two three four the mid will come or something over here so yeah maybe let me just move my mid okay so the mid will go something over here if i'm not wrong yeah uh one two three four by two even though let's say we will come over here anyone okay then i will again check is made is on the defect whether i will say yes millions of on the defect question so what will happen my high will move from over here so it means like after my minute there is all the depak version so what i will do i will take my middle uh i will take my high from the end to put it with the low so mid minus one till mid minus one so you know like low is equals to mid plus one and high is equals to mid minus one if you don't worry i will show you in the code don't worry okay then what i will do i will i have these two values now okay remaining so these all the rest of them are ignored so they will not ignore now so i will calculate the mid again and i will find my mid will come over here because two by two is one so i will again calculate i have everything calculated in the mid my main will come over here now okay so right now i will check is my middle is on the first bad version i will say yes it is on the first person so this is the first bad version and i will simply return it okay so i hope this thing is kind of like how we gonna do this so let's just start solving our question right okay so first of all what i have to do i will create one my interlope which is initially at zero and i will get my end high which is at n right and one i will create my first bad version i will call it fbv which is initially minus one let's say okay so i will run my loop and i will say while low is less than equals too high then my root loop will run and in this one i will calculate my middle so it will be uh low plus i divided by two okay that's how we calculate but let's say uh if for say like if our uh constants are very bad then i will just optimize it a little bit more okay it's not like this and here we go so now what i will do i will create one if condition i will check if i will call my bad version so i will simply put it over this bad version is made if it's about if we are on the bad if it's true then about it means my first bad version will be equals to mid then it means like i hope so we find the first better version and i will decrease my height from the i will take with my back from it because after my mid it means like everyone on everyone are damaging everyone are defected one so i will just simply uh put high plus to mid minus one so let's say that's not over that's not the first uh defect wasn't the referendum might be before that then what i will do i have to uh because like before that what i will do like i have to move my low as well so i will move my laws because like before my middle there is all our good version so it means like there is no possibility of a bad version so low equals to mid plus one all right guys and uh finally we have to return first bad version okay i hopefully the code is in the code is very simple based on binances i hope so you know binary searches let me just run this one as well and taking a time a little bit depending on the server speed is going saying 10 mm i think we did a little mistake okay now okay so now it's something i think by because of the bracket so i just remove the brackets now i hope so it will work now let me just submit it finger close let's say it will go correctly and here you guys so this one is in this one we are delivering the time consider offloading so it depends on the server speed so sometimes if you see like it is runtime you will see there definitely difference over here okay so that this in this one i think uh in this one yeah in this one i got the uh run time of 96 98.29 so you i got the uh run time of 96 98.29 so you i got the uh run time of 96 98.29 so you see so like it depends on the server also never mind okay so i hope that both approaches are killed you like how we did it so if you still have any doubt then just do let me know in the comment section i will definitely one of these to you and if you don't understand this video i'm suggesting try to watch this video again you definitely gonna understand so ladies and gentlemen i just want to say thank you very much for watching this video i will see you in the next one till then take care bye and i love you guys please hit the like button if you like this video alright bye
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
5 |
hello friends welcome to joy of life so today we are going to look at another medium level problem from lead code the problem number is 5 longest palindromic substring so given a string s return the longest palindromic substring in s so you'll be given with a string as you see in the example over here so here is one of the input string baba d so there are two palindromes which are of size three of course there are smaller palindrome than that but the biggest one we can see is bab and aba right both are of size three as you can see so you have to you can return either of the ones so bab or aba both are valid answers so we need to identify the longest one and we need to return that back right so the string could be of size 1000 characters also so there is a possibility that you get a very big string wherein you have multiple palindromes and essentially what happens in a brute force algorithm for a problem like this in lead queries that you will often get the timeout right so we are going to see an approach which is pretty much optimized and we are going to come up with the code as well for the same so here is another example that you need to understand over here that we you have a string like a and c right so a single character by default is a palindrome right if i take the character a it is a from both front and back right it's the same right so here we have two balance a and c both are of size one you can return either so here the output is eight but we see that there is no harm in uh sending c back but yeah we have to return the longest one so in this case above as well what we have seen is that there are this b and a itself is also a palindrome right so this b a d these are all single character palindromes as well but the longest one we see is that bab so we need to re return b a b or a b a either of the one which are of size three right so yeah we are going to check out the solution but as i always recommend do give it a try yourself to come try to solve the problem at least try the brute force approach and then we are going to see the optimized approach over here there are multiple ways to solve it and we are going to check more than one solution for it maybe i'll create two separate videos for the same but uh let's head over to lead code and check out the solution so in the previous problem we have seen this uh solution over here right which was a pretty decent solution where we started from the middle and we moved towards both then to come up with the solution right so in this video we are going to check out another solution which is a dynamic programming solution and we are going to see how it works in all the details and though it is not as efficient as this one because that's once again order of n square solution but having said that what we do over there is we do not check for the palindrome again and again right we don't here also we have started from the middle we have expanded we have checked and done so many things right we are not going to do all those things in a dynamic programming problem we are going to understand the trick behind the same why we are how we can eliminate completely the checking off of the palindrome part and how we can leverage on the sub problems and come up with the solution right so in this solution what we are going to do is since its order of n square solution that means we are going to check all the possible strengths that is present over here right but how we are going to save time on that let's understand that part right so we have to get the same example once again over here right so it's a so what we are going to do is we are going to create a so-called dynamic programming create a so-called dynamic programming create a so-called dynamic programming table that's uh the typical part but we are going to understand the thought process and every minute details behind what we are doing why we are doing how we are doing we are going to cover everything we are not going to leave anything behind right so let's understand the thought process behind this dynamic table how why and why how we are creating it right so these are all the possible substrings that's possible from the string b a d so there are five string that's possible from b starting with b like b a b like b then b a d right so there are these are the five strings and if you start with one then you can have eight and a b then a b eight and a b a d and so on right so there will be five then four then three then two and then finally one so these are the all sub strings right and that is why we have order of n square right because we are generating all of them right so let's understand this table in much more details this dynamic table so what it does is it tells me the starting index and the end index so if i have to mark over here so let's say this is my start index and these are my end index so this cell signifies that 0 to so this cell over here the one you the one that is highlighted right so this cell over here signifies that it's this uh the substring starts at zero ends at two so zero to two means b a b right so zero to two if you check over here so this is zero this is two so zero to two means b a b right so c o 0 to 2 so this cell signifies this substring this cell b this cell over here signifies 0 means only this cell similarly signifies the starting index 0 and the end index is 3 so b a b so it's denoted by this character this cell over here starting index three which is a and ending index is a three which is the same index and this is a d like that so essentially what happens is these indexes like starting one ending zero we never we cannot ever have a substring like that right so this is invalid right we cannot have a cell like this right similarly all these cells over here becomes a invalid cell so as we have discussed earlier we know that the single character is always a palindrome so what we can say that starting at zero ending at zero it's a palindrome yes it's a valid round true it's a palindrome starting at index one ending at index one means a single character it's also a palindrome so all these cells starting and ending at the same index becomes our palindrome right we can say that easily so what we are basically doing is over here we are establishing our base cases right in a dynamic problem we first establish the base cases and then we build on top of the base cases right so a single character is our base case and two characters is also our base case so what we are going to do over here is we are going to check that is b and this a so 0 and 1 right over here 0 starting at 0 ending at 1 so starting at 0 ending at 1 is b same as a so we are just comparing a single character and we see that it's not so we are going to put a false so let's put the false one with a different color so that it becomes easier for us to identify is b and a same no is b and it's is a and b same no is b and a same no is a and d same no so now we have established our base cases and now what we are going to do is we are going to fill up the rest of this table and we are going to see how we are going to fill this up so let's talk about the odd and the event even cases and understand like how they differ in a parallel so if i give you a string right a and ask you is it a palindrome you will probably say yes true it's a palindrome so if i ask you cac is a palindrome so probably will tell me that yes it is apparent drum now for even what do we need to do i will give you two strings over here right and i ask you is it a palindrome so you will check both and say it's a palindrome right and for odd the base case is a single character for even the base case is double character right so that's why what we have done is we have filled up both right not only one row so we have two base cases one is for a single character so that was for odd and the double character that is for the even size palindrome right so now let's build on top of this one so i you said cse is a balindrome so if i give you a b and a b what will you say you will say it's a palindrome so let's say it keeps growing and growing so basically if you look at the pattern if you know that this is a palindrome if you know this is a palindrome and these two characters are same the new ones are same that means this is also a palindrome you don't need to check this part if you already know the answer right same thing goes over here in our table and same thing happens here on so right you know a and a is a palindrome so if i give you a cs cnc and ask you don't need to check a and a because you know no now the only thing is these two has to match that's it right so that's all the sub problem is all about so if you take a palindrome like a b c d c b a so i have first one this is a palindrome then i check this i did not check the middle because i know the middle is already true i again check these two i know the middle is already true so that's how you are capitalizing on your sub problem that's why you are using your sub problem so over here now when you come over here so when you check this a and d right you don't have to check from a is matching or not and all that so the moment you see that a and b so you're going to put a f right away and do keep in mind we are going to fill it up bottom up because the bottom most line over here has been completely filled because of the nature the bottom two lines are completely filled because of this principle because however big your string is your last two substring categories will be one and two characters only the higher you go the more number of substring you will end up having right so over here the moment i see a and d is not same i'm going to say i'm not going to check anything else it's not a balance right so let's move on so let's understand this cell in a little more details so what does the cell signifies it starts from the a and it ends at a right so this a is the first index a and this is the third index it's not the same a okay so it's basically the substring that we are talking about is a b a right so again we are going to check that first index and third index is it same yes they are same a and a is the same so my condition over here is these two the edge two characters i have checked and that is true now whatever is in the middle i need to verify that one and how do i verify that one basically i have to just check for this cell over here right so let me put the index for this cells so this is one this is two and this is three so if i remove what i am left with is a two and a two right this is a two and a two so i just reduce three by one and increase one by one right because if you remember however big we have a string let's say this is a string right i know this is palindrome right i first knew this is palindrome then i knew this is palindrome now i know this is palindrome so had this been a what i need to do is i have to check the substring zero plus one and six minus one so basically one two five and here what will happen we have to check two and where is we will go to the cell to two which is already being calculated for us we are going to get the value and do a end between them so i see this is also true right so what will happen is this cell over here will get the value directly so this cell will get this true value from here right again for a and d what we see is that it's not the same a and d is not the same so we are getting a false over here going to this cell over here so what is this cell is b so let me put it over here so this cell signifies b a b right so this b and this b is matching again they are of not the same index so now i'll reduce one from two and increase one from zero so i will go to the cell one and get the value so one i see a value which is true so i know that this value is going to be true and these two will definitely be false because a and b is not the same so we are getting a false over here and b and d is not the same so we are getting a false over here now the problem is very simple to figure out the biggest palindrome that we have so we leverage the same loop in order to find out where we have seen the biggest root right so over here i have seen in the cell 2 so i know that this starts from zero so this is the biggest palindrome i have seen here similarly over here at index three i have seen but it starts from one so they are basically of the same size so this guy over here and this guy over here is of the same size so we know that so we can take either of the one and we can say that this is the biggest palindrome that we have seen so far so in this solution that we have discussed if you see the substrings that we have generated right what do we need in order to generate that so in order to generate this kind of strings what do we need is two loops one is i starting from zero and then going all the way through the string right so basically what we are doing is we are iterating over the string twice right the entire string twice and that two in a less nested fashion so this is going to give you order of n square but still why it is better than a knife solution is because we are not doing a check on the string right so that is providing us with some advantage that we don't have to compare the entire string because we are kind of pre-computing the result so each one of pre-computing the result so each one of pre-computing the result so each one of this cell over here is a sub problem right each one of this cell over here is sub problem so if you give me the string baba and ask me what is the maximum size palindrom ballin palindromic substring present in it still i can tell you the answer because i have solved all the problem along its way right i found the answer for everything every possible substring and we have built on top of it right so that's why you we gain certain advantage over here though this is not a very optimized solution right the optimized solution we have already discussed and i will leave a link to the description to the other problem in this video as well so the basic intention of making this video is to give you a very good insight on the dynamic programming part how dynamic programming can help us in finding the palindromic sub substrings as well right so i hope you got the concept and we are going to look at another example if you think that you want to continue watching another complex example wherein we have multiple uh paranormic substring of different lengths maybe say length 3 and length 4 and how we are finding out how we are dealing with the events even number of characters in a palindromic substring though it's the same there is nothing going to be different on that solution as well but what i recommend if you want to check out if you have time do check it out if you don't have time then use the timeline bar below and skip over to the coding part and check out the code for the same so here i have taken a complex example but we are going to run a little faster and we are just going to touch upon the important parts where we might face some doubts so again once again if we if your indexes are like 1 to 0 and all those indexes we are going to cut them off because we cannot have a substring with the first index greater than the second index right so we are cutting them off so this is why when you can see this is four right the first index is higher than the second index so these are all eliminated and what we know this diagonal is just the single characters like right 0 to 0 1 2 3 and all that up to 7 these are all single characters and single characters are always true so this is our base case for the odd number of characters right now we have to set the base case for our even number of characters where we have two characters only so what we are going to do we are going to just compare this p with c with b we are not going to check anything else we are just going to compare these two characters that's it there's two characters starting this and ending so if you see all these cells over here they have one different 0 1 2 3 4 5 and so on right so let's fill that up so p and c is different so this is going to be false this c and p is different over here right so this is also false this p and b is different so this is also false this b and this s is different that's false this s and this s is same so keep in mind that we might have true cases also all right so this is true moving on this s and this b is different so this is false this is now false so we have established our base cases and we are going to solve from the top down uh so from so we are going to solve now from top up right so first two last two rows are always completely filled we don't need to take care because the last string is of one character and the second last substring is of two characters that's always true and we don't need to do anything for that right so we'll continue over here so we check directly s and x they're different so it's false so this s and b it's false this s and x is false so i hope you are getting the point that when we are talking about this cell we are talking about the substring starting from the fastest to the b to the last b so ssb such thing we are talking about right so each of the cell they map to a particular substring over here so this b and this s is different so once again a false now we are about to hit an interesting case so this is the first b and this is the last v so we are talking about bssb and let's see how this evaluates to be true so b and b is true right now since b and b is true so our substring is bssb so b and b we have seen that it is true right and let's put down the index is three this is six this is four and five of course so what we need to check is we have to reduce from the left boundary one and the right boundary because this is the value we are manually checking right now we have to see what is the value in the index four five so four is here and five is here and we see that it is true what does the four five value signifies it signifies the value ss so you can see here s was true ss was also true so 4 5 is true and 3 and 6 are same right so we can say that this is a palindrome over here so moving on b and x is not same so it is false so over here p and s is not same so it is false this is false because none of them are p right so we can mark them for once now coming to this in index one then we see that c and b not same c and s not same c and b not same c and x not same so these will all become false right now we come to this cell and you can see that this is the value of p c p zero starting from zero ending at two so what happens once again p c p starting at 0 ending at 2 0 1 2 so we are going to check 0 and 2 and if we reduce 2 by 1 and increase 0 by 1 what we get is one so we are going to see what is there in one it's a true we have in one so we can certainly say that this is also a palindrome over here right and what and the rest of the things we see that p is p and b different s and p different b and x different so you can see that we have found a palindrome so now so 2 minus 0 plus 1 why do we do the plus one because we are doing a zero best indexing right we have to increment by one so the size is this guy over here he has a size of three this palindrome is of size three over here we have six minus three plus one so 6 minus 3 plus 1 6 minus 3 and this is 4 right so we can say this is 4 right so every time we put a true we can calculate the value check the length and store it so 4 is the best size and if i store the index that is this cell denoted right so we have three two six is nothing but bssp we can just put the answer there so let's move over to lead code and check out the solution there so what we are going to do as you have seen in the solution is you we have a matrix or a dp table which is of a boolean nature right because it was all boolean we have been storing true or false over there so we are going to create a boolean two-dimensional array and uh two-dimensional array and uh two-dimensional array and uh let's call it our table where we will have the data and what would be the size of this table this would be the size of your string right so we are going to put s dot length right so this is going to be our table and what we are going to do is now we need to return the longest valence so let's call that as a result that will be finding out and at the end we'll be returning that right and now what we are going to do is first we'll be filling up our base cases so base cases is the single character and the double character string that we have talked about so i am going to start the first loop over here so this loop over here i can just have a single loop right because we know that we have to deal with the first two indexes from i right so for zero for while i is zero we have to deal with zero one well i is one we have to deal with one and 2 while i is 2 we have to deal with 2 and 3 and so on so i don't need two loops over here so what i am going to do is i am going to put into the table of i and i so what we can say is that i and i is always true right so this is for the first case where we have the single character so we certainly know that's going to be true anyways the result we have initialized to a blank let's not do that let's initialize this with uh with the first character of the string right because that's also a palindrome right so starting from index 0 and let's pick up one character and now what we are going to do is we are going to check for the second character so basically even if you look at this so there are few edge cases over here that you need to cover up in this second character basically right so one is that for the last character for the last substring you won't have a second character also right you don't have a place to put that so you might end up having some array index out of bound exception so it's better that you put a check over here so that you don't end up hitting that so checking for s dot length is not sufficient we have to check for s dot length minus one right we have to reduce one index because i am going to put the value in table i and i plus one right over here so that's why i have to impose a minus one over here so that i know that there are at least one more cell present over there right so now here what we are going to do is we are going to compare both the characters so basically character at i okay so we are just checking the ith character and the next character that's what also we have done over here that we have checked this and put that right for the base case so when s and s is same we put it true so we can just simply say over here that i plus 1 is equals to care at i and care at i plus 1 so whatever it is we are going to store it right and it might happen that your string is of two characters and in that case what do you need to do is if you find a true over here if this cell over here gives you a true in that case you have to change your result right so we are going to do that we are going to put if this is true so we are starting from the ith index and ending at i plus 2 index we are just picking up two characters nothing else what we are going to do is so we are getting it only when it is a palindrome also right so we need to update the result over here we are going to check the length of both so string dot length if it is greater than the result that we have if it is better than its length in that case i am going to go ahead and update my result right to str so this is where i have established my base cases so both the cases the odd one the even one and also updated the result that's also very important these first diagonals has been populated now we have to do a bottom up right and fill up the rest of the table so how we are going to do the bottom up is we are going to start again the loop but this time what i am going to do is we are going to start from s dot length minus 2 right because the last two row is already filled and i should be greater than or equal to zero and i plus so this loop will ensure that i am going from bottom to the uh to up and then i have a j and j will move from left to right that's how we are filled up let's do that so we will start from i plus 2 because i know i and i plus 1 has already been done right so for this we know that i and i plus 1 is already done so we will start from i plus 2 right and we will be less than s dot length so we'll go the entire length of the string and j plus and now what we are going to do is we are going to update our table and we are going to put the values i and j and what we are going to do is we are going to first check both the characters are same or not two characters are same so what we have been doing so we are checking by reducing the left boundary and reducing the right boundary right and so how we can find those index is basically we need to go to so what we are doing over here so let's understand from here once again so here we have we are going to the cell four and five so we are reducing the row we are increasing the row by one right so whatever is wherever is my i am doing a plus one and coming down to the next row because the result will surely be on the next row because that's a sub problem and we are doing a bottom up right so if i'm here my result would be somewhere here right because this is my substring definitely because this is cut off this is i am feeling so this over here is my substring exactly so if i am here this is my substring so if you see in this case also that if i am here i was checking for this one so if you remember over here when we are feeling for this cell three and six right so what we are feeling for the cell three and six right so what we did we checked for four and five right that means one row down one row left don't memorize the pattern but try and understand the rational why we are coming one level down because if i come one level down and o and one level to my left so if i come one cell down and go once a left what i will have is basically the shorter substring so the moment i change the row from 4 to 5 i am incrementing this value right the starting position of the string so this left edge is getting cut off right and the moment i am moving towards my left that means i am checking for my previous character so two characters are going off the moment i am coming one cell down and going one cell left right so you got the point right just to enter it again one cell down means i am checking the shorter substring the shortest substring so if you see over here the biggest substring over here is b so if i talk about this cell over here so this is b s b x right this is the maximum but the next one if you see it starts from s right so ssbx so the moment you increment i you are cutting the left and the moment you go left you are cutting the right so one cell down one cell left right so the same thing we are going to do over here we are going to do a i plus one means one cell down j minus one j minus 1 one cell to the left right so we got our desired value over here now we are going to do the same thing again that we did over here right so pretty much the same thing we'll do over here so let's get it over here so instead of i plus one what i'm going to do is i'm going to say it's j right and we are going to get the value of i plus uh like we will be starting from i and we will be ending at j plus one so that plus one is always for the zero base index right and we get the result in str and again str dot length is greater than result.length we are going to update the result.length we are going to update the result.length we are going to update the result and at the end we are going to have the desired result that we want let's run the code i'm not too hopeful i'll be surely making some errors i knew it basically this will be i minus i shouldn't be increasing it right we are going up right so finally it worked let's submit and check for a broader range of test cases we have 46 469 milliseconds over here so if you remember we have 23 or 26 millisecond on our previous submission right it was that was far better so once again the main intention was to give you the idea on how we can solve such a problem using dynamic programming as well right so of course the solution is not recommended this is just for your understanding purpose to get some idea on the dynamic programming how we solve the sub problem and come up with the solution but it is of course better than your naive solution wherein you will be comparing all the substring again and again so it is pretty close to your 9 solution wherein we have order of n square but at the same time we are leveraging the dynamic programming concept over here in order to not calculate the palindrome or not computing is it a palindrome or not again and saving a lot of time so your knife solution might hit up out of time or out of memory kind of problem but this solution is will not hit such a criteria over here right so this solution has a order of n square complexity both in terms of space and time because we are creating a 2d array of n square right it will have if you have n number of elements it will have n by n size of matrix that you need to populate right and you will definitely need two loops over here so this is your n square part right this is order of n because we are just having one loop over here but this one though we are saving two rows that doesn't count it's a constant you drop the constant and you take n only right n minus two so n minus two is also n right i hope you got the solution so once again this was completely for your understanding purpose i hope you got the concept uh concept of how dynamic program is helping us over here probably this will give you some idea wherein you can implement this kind of solution to some other problem but this is not meant for this problem once again okay so do let me know what do you think about the solution so don't judge me by the complexity part of this problem i am not responsible for it was just to give you idea on how things works in dynamic programming right i will leave a link to the linear solution wherein we have 20 23 or 26 millisecond performance which was better than almost 90 percent of the submissions so yeah that's all from this video do share and subscribe if you haven't done so also give a like if you think the solution was helpful and that's all from this video and see you guys stay home stay safe and take care bye
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
930 |
hey everybody this is Larry this is day 14 of the Leo day challenge hit the like button hit the Subscribe button join me on Discord if I could click on it uh let me know what you think about today's prom binary subarray with sum H seems like I haven't done this one before and we get to do it on this new UI where I will complain a lot as usual so hit the like button hit the Subscribe button join in Discord and all these good things might have already said it but you know like uh like UI it is booking so I don't know anyway all right what are we doing so given a binary array nums and an integer go return the number of non Mt sub array with a sum go a sub array is a contiguous some part of aray oh okay I saw a matrix here that's why I was like what do you mean okay so the number of nonempty subarrays with go is equal to two so you have um hm yeah I mean I think there are a couple ways you can do it I think my intuition my initial intuition to be honest is going to be sliding window and I think you could do it but it's just a little bit um um you can make a lot of mistakes with sliding windows with this one just from kind of Jud gauging the way that like how you move and stuff like this uh and definitely if you want to challenge yourself definitely should do that looking at the constraints of course I mean I actually looked at constraints first but well I didn't even look at it but to be honest I was just like okay well if this is n Square it's just a dumb question right uh so I didn't even really look at it so I was just assuming that I to get to offn uh but yeah the way that I would think about it is I mean there a couple ways you can do it to be honest there is um and I'll go over oh let me get got to put away my eggs all right well X will be not cold sorry friends I am very kind of confused and after the gym today but uh yeah so there a couple of techniques you can do one is sliding window possibly I'm not 100% sold on window possibly I'm not 100% sold on window possibly I'm not 100% sold on this one I wouldn't do it and that I'm not going to do it uh with sliding window possibly there's another thing that I don't know what the name of this technique is I just kind of um uh the way that I think about it is just um Counting contributions I think maybe the way that I count counting contributions and the way that I do this is um is just kind of count how many possible so let's say you know you're going from left to right you're looking at one digit at a time or number at a time and you just try to figure out how many times is this the right end point or the left end point but from symmetry reason the right end point how many arrays are there that ends here so that's basically the subar is and here and then of course there's also prefix sum which I think I'm just going to do a prefix sum so uh yeah uh and kind of these two tied together for this PR so uh yeah and yeah I'll go with the prefix sum I think this is a question that I got a couple of times on the link list problem a couple of days ago the one that I really struggled on and for that one I was uh to be honest just too tired to really explain it and that was my apologies I mean that took like an hour so uh hope you know you understand I was just like H that one was really weird in a way and I was just wrong to be honest with that PR I it kind of I don't know it is what it is but yeah um but yeah the idea here is that okay let's calculate the prefix sum what is prefix sum is just having an array that contains all the elements from zero to the if Index right so we can write something like this um but actually let me take out drawing real quick yeah let me draw real quick um hand God also like New York is like warm the last couple of days uh and it is Springtime so allergy season is my point and it's a little bit of funky but yeah uh I mean you could skip ahead a little bit if you already know what prefix sum is but and this is a binary array so that makes it a little bit easier to kind of illustrate I'm just writing random things um and then the prefix sum of course is just you know let's say we start zero because you have zero elements right this is the no element and then 0 1 2 3 44 right so then now what the prefix sum means that uh for this index it gets the sum of all these elements right with this index it gets all the sum of all these elements right and then the idea here is let's say we at this element let change the color real quick right and then now what does that mean that means that okay we're trying to find um some subarray in which let's say for I don't know K is equal to two or whatever name is right we're trying to find the go is equal to two what does that mean that means that um that means that this Subway so let's go let's see 1 2 3 4 5 six so that's P sub six right let say piece of six right let me write it a little bit up so P sub six is equal to I don't know what's it a Sub 0 plus a sub 1 plus a sub 2 plus a sub 3 plus a sub 4 plus a sub 5 plus a sub 6 say right and here we're trying to figure out okay we're trying to end here then that means that we have some change color again we're trying to find some subset or subarray here either here or something like this some we don't know which how many or which one uh is youal to sums to go right so then now you another way to WR that is that you know uh well let's say we figured out that um A2 to A6 is equal to go what does that mean and another way to write the rest of this of course is just that this is of course P sub one right because well that's just the prefix sum so then now you could write P of X Plus P sub one plus the go right I WR G for go and that's pretty much the idea is that now you're trying to find how many prefix sum is so then now uh and then maybe you could rewrite this as some uh variable P sub X for some number of x's or maybe I don't know right and then now you know what go is because it's in the input you know what P sub six is because that's what you're calculating so then now you have I'm going to write up here in a confusing way G is equal to oh sorry G uh minus P6 is equal to some p subx and then now we try to figure out how many times this is true right and that's pretty much the idea for this one for prefix sum and it's it ties very much into um the link list form that I didn't go over so hopefully this is a makeup for that yeah so and then for x and nums um and then maybe a f for frequency right and now um yeah prefix do appen the last number plus X so this is just keeps on going you know and then F of prefix this is the new number of course so don't confuse these two uh we increment by one but before that um and maybe before this I guess it doesn't matter before that now we have so um prefix the new one the new uh last prefix sum that we calculated maybe I could write this in a cleaner way I think this is very confusing all right you're right so then maybe like the new one so I'm just going to last is you go do this right and then this is still you go to last okay so then now um yeah so last minus some pre some previous prefix sum is equal to go okay so then now we add previous on this side oh uh yeah H or minus last wait yeah this is right so minus go on this side uh plus I don't know how I think I might have had it wrong before that's why and then yeah so then now this is what we're looking for and then and that's just going to be an F of this thing so then now count we can just count the number of times we've seen it before um in theory if you really want to uh kind of Shake It Out you could keep track you can make this like a list or something keep track of the indexes and then kind of visualize your way for it but uh yeah should be good where's the submit button oh it's up here I this new UI and now we get to see my code choice for some reason except we have to click on read more uh but yeah uh that's pretty much it turns out oh yeah and I guess like it turns out you don't even really need this right because I just kind of have to prefix some here for visualization but really you could you know you can see that we don't use any of the numbers except for the last number and we updated here I just want to uh put the prefix some for visualization but uh yeah this is an linear Loop this is linear space this is also linear space but you could get rid of that one but in other case it's linear time linear space and that's all we have for this one let me know what you think uh did this have to solve I don't remember if I solved it this I don't remember if I've solved this before to be honest uh but I well cuz I don't this new UI but uh but yeah that's all I have for this one let me know what you think and yeah you think about the link list from uh from a couple days ago this is basically the same idea um except for that now uh the goal here would have been zero so then that's why you know it's structured that way um yeah uh that's all I have for this one let me know what you think stay good stay healthy toal Health I'll see you all later and take care bye-bye
|
Binary Subarrays With Sum
|
all-possible-full-binary-trees
|
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0,1\]
\[**1,0,1,0**,1\]
\[1,**0,1,0,1**\]
\[1,0,**1,0,1**\]
**Example 2:**
**Input:** nums = \[0,0,0,0,0\], goal = 0
**Output:** 15
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `nums[i]` is either `0` or `1`.
* `0 <= goal <= nums.length`
| null |
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
|
Medium
| null |
763 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you've not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever post a new video so without any further ado let's get started problem is partition labels we are given a string and we want to partition that string into as many parts as possible so that each letter appears in at most one part so for example if in there is a string right there is a string and we need to divide that string into multiple parts and if in one part we have let's say letter a so in another parts like in any other part a letter cannot be there so a single letter should be only in one part okay so if a is in the first part then a cannot be in any other parts note that partition is done so that after concatenating all the parts in order the resulting string should be s which was given initially so we cannot like move here and there let us we cannot move here and there obviously okay so we need to uh partition the string return the list of integers representing the size of these parts okay let's see this test case so here i have written this test case this is the test case i have done the indexing so here first part we have to divide this see what are the observations from the problem what are the observations we have to divide the string we have to partition the string in make as many parts as possible okay divide the string we have to divide the string in as many parts as possible in maximum parts so see if this is a string we have to increase the number of parts right we have to have as many parts as possible obviously then one part should be as small as possible it should be as small as possible so that if this part is small then there will be more letters for the other parts so then there could be more parts if one part is only very big then obviously there will be less letters for the other parts hence the number of parts may get reduced so one thing which we have to keep in mind is that every part should be as small as possible okay this is one thing so other observation which we can get from the problem is that uh that each letter should appear at most once so every letter one other observation is that every letter each letter should occur only in one part okay for example what will be the parts here one part will be this one from here till here a till a this will be one part okay second part will be this one from d till this e okay and third part will be this one from this h till j so these will be the three parts which are possible now how these parts are valid see here if f is there in this part f is there so f is not in this one also an f is not in this one also okay if a is here in the first part then a is not here also and a is not here also fine so this is valid so first part is this one second is this and third is this so here this is the first second and third part and in the output we have to return the length of these parts length so this has length nine one two three four five six there are nine letters here it has a four seven letters and then there are eight letters in this one eight seven and nine so output will be nine seven and eight so it should be the length of the path okay i hope you understood this uh like the problem you have understood the problem now let's see how we can approach it okay so see guys one observation which we can get is this that c over here if a c like if a is the first letter now how long can this partition go it will go till the last occurrence of a because a can only in a can only be in one part right so if a is in this part in this first part then last occurrence of a till here this should be at least the first part because a can only be in first part okay similarly uh if b is here if we are taking this b letter then the last occurrence of b this is so till here at least still here the first part will be but since a is here so till here the first part will be similarly over here if e is here so last occurrence of e is here meaning at least still here the second part will be because e is in the second part so this e cannot go in third part it should be in second part only so that's why this will be the second part till the last see till the last occurrence of e so if you now if you think right we need to know the last occurrence of every letter okay so for that to show the last occurrence of each letter we'll be using a hash map or an unordered map okay we'll be using a hash map let's see how we can do it so i'm raising this everything i'm erasing i'm just keeping the indexes okay so see just do one thing uh for this test case let's create a hash map and for each letter we'll be storing the last index of occurrence of that letter so this is the hash map first of all we'll start traversing from the we will start traversing the string so here a will be there so a is last zero so here this is the letter and value is the index okay then we have we'll go to b so b's index will store as 1 then we will go to a again so a's index will now change to 2 now again we go to b's index will change to 3 so c then c's index will be 4 then we will go to again b so b's index is now five okay then a's index will change to six then c's index will change to seven and then again there is a so a's index will be eight so c a is the last index is eight similarly for d also we'll be doing these will be e oh sorry these will be nine then it will be e's will be 10 then f's will be 11 then e is there is will be 12 oh sorry here it will change to 12 and then gs is 13 so g is not there in the map we'll add it at 30 index then it will be d again so these will be 14 get updated and ease will be 15 so ease will be 15 then h will be 16 similarly see i's will be 17 so i is last occurrence is here so i'm writing that only 22 and then j will be there so i'm writing here j will be what 18 and i is 22 okay so here if it's not visible h is 16 and then k we have case is the 20 okay and l is 21 so this is all the last occurrences of each letter fine so we have found out the last occurrence of each letter after that what we will do we have to have the parts right we have to have the parts so for that we'll be taking three variables one will be previous the pre like previous will be storing the starting of the part starting index so this previous will be starting index of a part whatever part is this previous variable will be storing the starting index then we'll have the max i this max i will be the ending index of the part and answer vector we will be having answer vector or array list this will be storing the lengths of these so this all the lengths of the parts this will be storing so previous is the starting index and max is the ending index of a part okay so what i'm doing is initially we will be giving see initially value will give previous as minus one max is let's give it a zero okay so now what we will do will traverse this here so see what is a is last index is what 8 right so max i will be what max i will be max of whatever the current maxi is comma the last occurrence let's say this is my let's take this is my mp map so last occurrence of the letter whatever letter we are at so five okay so max i is max of zero comma map of s of i is what a is so five this is s string so a is last index is what eight so eight will be here so max i will be it meaning at least till here first part will be why it will be because a can be in one part only and if a is occurring till here like its last index is this one so this should be in the first part because a cannot be in any other parts as in the question it's mentioned that a letter can be only in one part okay so again similarly we'll go to b what is b's last index it's five okay so max i right now it's 8 only so it's not it not get updated then again we'll go to a is last index is what again 8 max is 8 only so no need to update then b again same thing 5 no need to update c 7 but max is already 8 no need to update again b again a c and again c now here we go to a now it's very important thing guys see now it's la right now i is here right i is here mac a's last index is what it and i is equal to 8 so when your max i is equal to i meaning this is the last occurrence of any letter in the part so at max this could be the part so this is your first part that is when if your max i is equal to i then what you will do you will store this here is your previous right previous is your minus one so you will calculate the length and you will store it in answer if this is the case okay let me show you the code also you will better understand see first of all we have taken a map java code will be in the description and python could also so what we are doing is we have taken this here we have taken this map and we are storing these letters okay and we are just storing the last index so this is for the last index then we are taking these three variables and then here we are storing max i is equal to max i and last index this thing we are doing if they are equal then we calculate the length that is max i minus previous so max is what 8 minus previous is minus 1 so 8 plus 1 is 9 so 9 is stored in answer okay 9 is stored in answer and after that previous becomes the max i becomes previous so now our previous will be equal to max i which is eight and then again we'll continue so this is the first part okay now let's go further now let me change this thing so here now i will come here at d so these last index is what last these last index is 14 so max will be max i will be max of max i currently it's 8 comma last index of letter s of 5 which is d so it's 14 so obviously 14 will be the max i know so max i will get updated in 14. so at least till here it will be the second part at least it could be ahead also but at least as of now it will be till here ending is 14 index then we'll go here is what 15 now see it will get updated so max i will be what max of currently max is 14 comma mps of i mp s of i is what e m p of e is what 15 so now 14 what is maximum 14 50 15. so now max i is 50 so at least till here it will be the second half so this will change this is your 14 and this is oops this is a 14 and this is a 15 okay so now we'll go ahead i will go here at f what's last index of f 11 it's not greater than max of i no need to change e then again go g is also 13 no need then d e so now see now e's last index is what 50 which is equal to i that is max of i is equal to i so we'll go in this condition we'll calculate the length what's length max i is what 15 minus previous is what 8 so this will be 7 so 7 will be added in the answer array okay so 7 is on added in the answer array now what will happen max i will become previous so this is now the starting of the this is the starting of the next partition so we are taking like previous is one index before the starting of the uh partition right so previous is one index before the starting of partition so here the previous will now become 15 and uh this will go ahead so i will come here at h max i h is what h is 16 max i will get updated it will become 16 and then i so similarly i j i will update my side to 22 then j will be 18 no need to update h k i again and j so j i by mistakenly have written in 18 it's 23 here so 23 will be the last index and till here this will be the third partition so 23 minus the previous is 15 so this will give us 8. so 8 will be added in the answer so this is how this approach is working i hope you understood this and the code let me know in the comments with any doubt time complexity is o of n where n is the size of the string okay so time complexity is o of n and space is also of n because we are storing these in the hash map so if you found the video helpful please like it subscribe to my channel and i'll see in the next video
|
Partition Labels
|
special-binary-string
|
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.
Return _a list of integers representing the size of these parts_.
**Example 1:**
**Input:** s = "ababcbacadefegdehijhklij "
**Output:** \[9,7,8\]
**Explanation:**
The partition is "ababcbaca ", "defegde ", "hijhklij ".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts.
**Example 2:**
**Input:** s = "eccbbbbdec "
**Output:** \[10\]
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1).
A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached.
Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached.
If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is:
reverse_sorted(F(M1), F(M2), ..., F(Mk)).
However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
|
String,Recursion
|
Hard
|
678
|
114 |
hello guys welcome back to take those and in this video we will see how to flatten a binary to a linked list this is from tree and a linked list problem based on tree traversal this is from lead code number 114 we will discuss all the important interview follow-up the important interview follow-up the important interview follow-up problems which you might get after having solved this question so stay tuned till the end of the video are you ready to take your programming skills to the next level well you are at the right place Welcome to our data structures and algorithms live interview training program interview those get ready to dive deep into the world of efficient coding and problem solving in interview those you will get a solid understanding of key data structures such as array stack queue he Breeze and along with that you will also Master powerful algorithms based on maths geometry graph and dynamic programming what sets interview those apart from other courses is the live interactive format you won't just be watching the pre-recorded just be watching the pre-recorded just be watching the pre-recorded sessions but you will join me along with other passionate Learners in real time where we will be covering the Concepts together imagine having the opportunity to ask questions engage in discussion and collaborate with your fellow Learners it's a supportive Community where we all grow together but it doesn't stop there we will dive into Hands-On coding exercises solving real Hands-On coding exercises solving real Hands-On coding exercises solving real world problems and you will get to work with the interview assignments that will showcase your newfound expertise taking interview dose has already been a game changer for a lot of students and working professionals it didn't just help them to improve their coding skills but also boosted their confidence for tackling complex problems the live interactive sessions make all the difference unlock your coding potential by taking the first step forward contact us on WhatsApp for more details let us now look at the problem statement in this problem given the root of the binary tree flatten the tree into a linked list the link list should use the same tree node where the right pointer should behave like the next pointer in a linked list and the left pointer should always be null the linked list should be in the same order as the pre-order in the same order as the pre-order in the same order as the pre-order yourself so they have made it Easy by providing the tree traversal technique if we are given a tree and a example linked list then first thing we need to do is we have to identify about what is the tree traversal which we do on the tree so that I get the same order in the linked list seeing from left to right now in this problem they have made it Easy by saying it is a pre-order Easy by saying it is a pre-order Easy by saying it is a pre-order traversal if they had not mentioned about this then we had to compare the list by using three traversals pre-order list by using three traversals pre-order list by using three traversals pre-order in order and post order and generally the problem comes in one of these orders so we had to check by applying this on the tree and see if the linked list follows one of this order so the first step is to find out the tree traversal technique in this case they have given it as pre-order it as pre-order it as pre-order now once you know it is the pre-order now once you know it is the pre-order now once you know it is the pre-order then you can simply do the pre-order then you can simply do the pre-order then you can simply do the pre-order traversal on the tree let's see this so if you do the pre-order traversal you if you do the pre-order traversal you if you do the pre-order traversal you get one two three and then you get four and then you get five and after that six so whenever you reach a node for the first time you have to write it or print it I have already made a video on the easiest way to do three traversals I'll share the link in the description below now once you have understood about the tree traversal technique the second thing to do is to actually convert this tree into a linked list so the word flattening means you have to do this without taking up extra space like you do not have to make a new linked list out of this but you just have to convert this tree into a linked list structure so if you can see here the left pointers are in red and I have made all of them as null and only the right pointers are pointing to the next nodes so this is effectively a single linked list right it is not a double linked list it is a single linked list because the left pointers are useless here now let us look at the solution approach of how we should solve these type of problems I am taking the same example and we will have to see I mean what all variables do we need actually to flatten a tree now in this case first I will make the Assumption of the variables and later on after seeing the entire solution you will understand about why did we actually maintain those variables so we need a previous node variable we need a current node variable and we need a right subtree root variable okay so this will be named as r at this point of time you just assume that we are taking three variables even if you don't know you will get to know once we are done with the entire processing let's see now how to convert this structure into a linked list so initially your linked list is empty since we are maintaining pre-order the since we are maintaining pre-order the since we are maintaining pre-order the first node of the pre-order traversal is first node of the pre-order traversal is first node of the pre-order traversal is the root node hence the current will be 1. previous is null If the previous was a non-null variable then actually the a non-null variable then actually the a non-null variable then actually the next pointer of the previous must point to the current node so first thing which we need to do is to check if the previous is null or non-known in this previous is null or non-known in this previous is null or non-known in this case it is null so we don't do anything now we will just assume that this is the first node of the linked list and hence while moving on to the next node what is the next node it is the left pointer so you see that the left pointer is non-null hence the current must move to non-null hence the current must move to non-null hence the current must move to 2 now once you are moving to 2 the first thing which you need to do is the current node will now become the previous node so before updating the current node you will have to update the previous and assign it to the new current value which is 1. and then even before moving on to 2 we have to save this right subtree because if we come back to one how do we know what is the next subtree to be processed hence we will have to save this link as well so the link will be saved by using an R pointer and that will be the currents right node so this is R which is the third variable right subtree root now we have everything in place the previous node is this one the current is or was already one and the right is pointing to 5 now we can safely go to the left subtree node which is 2. now again we will have to repeat the process first thing you need to check is the previous existing yes the previous is existing right so what we need to do is the previous is Right pointer must be pointing to the current node because that is acting like the next pointer okay so what is the previous is Right node it is actually pointing to 5 so this will be d-linked and it will be this will be d-linked and it will be this will be d-linked and it will be re-linked to this too re-linked to this too re-linked to this too and then write the line of making this left pointer equivalent to null so this left corner will become null this is the change we are making and you see that if we make this kind of change then if we go back in the recursion to 1 since we have d-linked the sub tree since we have d-linked the sub tree since we have d-linked the sub tree rooted at 5 we will never be able to process it hence we will be using this third variable R which will actually save the right subtree so that even if we delink this still we will be able to come back to 5 and process the right subtree I think now it should be clear so once we are done processing the previous node we will have to update the previous node so previous will be this node again and again a new R pointer will be taken this R pointer is a separate one it will be made as a separate variable in the call stack so whenever we make a recursion call we will Define this variable R within the recursion call hence it will be created and in every call of recursion and those all copies will be separate so this R and this R is different now we have everything in place we have the previous in place now our current can go to the left node three this is our current node now again we will do the same kind of processing we will see if the previous node is non-null yes it if the previous node is non-null yes it if the previous node is non-null yes it is non-null so make the right pointer is non-null so make the right pointer is non-null so make the right pointer point to this current node which is 3 and hence this will be d-linked and then and hence this will be d-linked and then and hence this will be d-linked and then make the left pointer equals to null right so this will be deleted as well and now again do the same kind of update so make a r pointer come here the r pointer will be null make the previous pointer come to the current and then make the current go to this value which is null now this is the base case when the current is null then we will have to return from the recursion so we will have to backtrack so when we are backtracking then we will reach back to 3 and when we are back to 3 then we will be processing the r pointer so we will make the next recursion call by using R when I go to R the r is also null so again this is hitting the base case and we will return to 3. now we are done processing both the left and the right subtree hence we will go back in recursion and if we go back then we are going back to this too when we are at this 2 going back that is reaching to 2 for the second time then we know that the left subtree is already done hence we are reaching 2 for the second time now we should process the right subtree and I know that I had saved the right child using the r pointer so basically I'm I will be calling the same function by using R pointer so now our current will be here at 4 my previous is at this value right all these previouses were updated my previous is at this value there is only one copy of previous okay multiple copies are not generated multiple copies of R will get generated because this is declared inside the recursion call using a normal variable okay in this case you will have to check if the previous is non-null yes it is the previous is non-null yes it is the previous is non-null yes it is non-null so make the right pointer point non-null so make the right pointer point non-null so make the right pointer point to this node make the left pointer null as it is given and now you update the previous node to this node which is the current node and you have to save the r pointer here again and make the current go to the left side so this is where the current will be right so you see that this is becoming a little clumsy but I hope you will be able to understand now what we need to do again the current is hitting a base case so you will return back to 4 process this R again this will hit the base case because this is now so return back to 4. and then go back to 2 Go back to 1. now one has been reached for the second time hence you will recur and make the call for R so here you have current now at 5. your previous is at four now check if the previous is null no it is not null so make the right pointer point to this five okay and make the left corner null it is already null and now you update the previous to this Note 5 and save R here create an r and save this six and make the current to the left call so the left call is already null hence you will return back from here and make a call to the right side so now your current will be here and again you repeat the same process the previous is null no it is not null so make the right pointer point to this 6 yes it is already pointing to 6 make the left pointer null it is null and now make the previous as this node make here R which is null and now make current go to the left side so this is null so it will return back make a call to R it will return back to 6 it will go back to five go back to 1 and you are done if you see how the structure has changed then you see that the first node will be 1. and then you have the left pointer as null right pointer is pointing to two its left pointer is null the right pointer is pointing to 3 its left monitor is also null as you can see here the right pointer of this is pointing to 4 its left corner is null right now the force right pointer is pointing to 5 its left corner is again null pointing to six this left Point original and this right pointer is also null this is the expected structure which we wanted and these are the three variables which actually helped me to get the single linked list in the pre-order single linked list in the pre-order single linked list in the pre-order traversal so I hope you must have understood about why do we need all these variables I think the code will clarify all your doubts you must have understood that previous node is required just to link all the nodes in the given pre-order then the current the given pre-order then the current the given pre-order then the current node will actually tell you what node are we looking at in the given pre-order are we looking at in the given pre-order are we looking at in the given pre-order and then the right subtree root is important because once we are going to the left subtree then maybe the right pointer will get changed and it will make a new structure hence the right subtree can be totally d-linked so we subtree can be totally d-linked so we subtree can be totally d-linked so we will have to save it so that once we reach back in recursion we can actually process the right subtree so all these variables are very important now the time complexity is order of n since we are reaching to node three times maximum and the space complexity is order of n because we are solving this by recursion and the tree can be a skew tree now let us look at the code and once we come back we will look at all possible follow-up problems this is the code for follow-up problems this is the code for follow-up problems this is the code for our given problem we are given the root node I am defining the previous as null so if this is having just a single copy it is not like previous will be created in every recursion call no it just has a single copy we are making the pre-order single copy we are making the pre-order single copy we are making the pre-order Call and in the pre-order you see that Call and in the pre-order you see that Call and in the pre-order you see that the root node I mean the right pointer node is always getting created this means every recursion call will have a separate R pointer which will be pointing to the right child okay so the first line is if the current is null then basically you return this is the base case second case is If the previous exists that means if the current is not the first node then the previous is Right pointer must point to the current node and the previous is left pointer must be made null so this is the update we need to make and then once we are at a current node we will have to save the right pointer in R so that we can go to the left subtree and start processing and your previous must also be updated with the current value because current will now get an updated value and it will go to the left and once we return back in recursion line number 24 will hit and then we will move to the r pointer which is the right side and start processing the right subtree rooted at this current node so this is the entire code for the problem let us now look at all possible follow-up now look at all possible follow-up now look at all possible follow-up problems so the first possible follow-up problems so the first possible follow-up problems so the first possible follow-up problem can be flat in a binary tree to a linked list using in order traversal so this is a single linked list question we were asked using the pre-order but we were asked using the pre-order but we were asked using the pre-order but you can be asked using in order traversal or post order traversal and even the traversal order may not be mentioned but an example will be given and you have to figure out what kind of traversal is used the next type of question can be you can be asked to flatten a binary tree to a doubly linked list where the left pointer will be at the previous pointer and the right pointer will be the next pointer or you can be asked to make a circular linked list now in this example if you wanted to make it a circular linked list you can make the next pointer of the tail point to the Head node and this is how you can make a circular linked list so that was a circular uh single linked list but you can be also asked to make circular doubly linked list and you can combine this with all these different type of traversals in order pre-order post or anything right pre-order post or anything right pre-order post or anything right so I have already given some of the diagrams in order linked list post order link list how they will look like and doubly linked list right so you can go through them these are the important possible follow-up problems if you need possible follow-up problems if you need possible follow-up problems if you need the PDF of this video lecture then do follow us on telegram we will share the PDF on telegram do follow us on Instagram to get interview tips and strategies on how to crack top companies see you guys in the next video thank you
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
62 |
hi everyone today we are going to describe the question unique pass so there are robots on M by n uh grid and then the robot is initially located at the top left corner here and then agree to zero and the robot tries to move to the bottom right corner here and that the robot can only move either down or right at any point in time so given the two integers M and N Returns the number of possible unique passes and that the robot can take to reach the bottom and the right corner here so let's see the example so you are given like m equals three and n equals seven so we get this kind of a 2 degree and output is 25 because uh yeah um I'm explaining the deteriorated but uh the robot camera break it down or right oops so after we all we calculate All Passes so that should be 28 so that's why we should return 28 in this case before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get a code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example so m equals 3 and n equals 4. and this is a start point and the robot is now here and the goal is here so to solve this question and it's obvious um we can have only one way to get to these page places like a horizontally and a part three because the description said this robot can move only right or down so there's no place here uh like from left side and there's no place like above here so that's why we can only one way to get to these expresses so that's why first of all we should add one to all its places like this and okay so let's think about here so um this robot can move only right or down so if this robot take like a right fast then this robot move here and then if this robot want to get to here there is only one way to get to uh here like a down move down so and if this robot move down first and then if this robot want to get to reach here there's only one way because uh this robot uh can only like a right or down so that's why um total number of us to get to here should be one plus one and two right it's obvious like uh like this or this it's obvious and let's think about uh this place so if this robot want to get to this place so robot move from this place or from this place because uh yeah as I explained like many times so this robot can move only light or down this robot cannot move like left so that's why um so the total number of paths to get to this place should be 1 plus 2 and the total three so let's check like uh this is a one-way is a one-way is a one-way and uh like this is the one way and then total three and uh so let's think about the displays uh actually the same thing um so robot can move from here over here so that's why one plus three and four right so this place uh there is a three ways and so that's why when we move like this um there is like a three pass and then um from each place and there's only one way right like this so that's why one plus three and four yeah so I will like speed up so this place um same thing like a two plus one and three and then for this place three plus three and six and then go right here so four plus six and a total of ten and then we should return this number so in this case uh it's a unique pass total number of unique paths should be 10. yeah so that is a basic idea to solve this question okay so let's write a code first of all and create a 2d grid so grid equal so this is a little bit complicated but uh all places are initialized with one for x coordinate so that means this direction and uh or X in lens and that should be n foreign and how can we do that just pull y in Lynch and M so then we can create that activity grid and uh after that uh start it creating select four Y in range start from one and two M so uh why we start from one because uh we I as I explained earlier we know that all H braces uh one so we don't have to calculate these eight places so that's why we start from one and uh also for X image so start from 1 to n so that's why we can start from like a one so one should be here and then um up the grid and y and X equal um great and first of all um like our number from above like a y minus one and X plus put and uh other number from our left side so y and x minus 1. yeah actually that's it after that just return grid and then minus one and the minus one because we have to return the unique bus uh in the gold price yeah so let me submit it yeah looks good and the time complexity of this solution should be order of M multiply n because we visit all places once and the space complexity should be order of M multiply n so same as a Time complexity because we create a two degree tier but um I'll show you one more code and actually we can improve time complexity to um on actually we don't need this to delete so also you have Okay so let's write the optimized solution so we know that this robot coming from left side or from above because this robot can only move light over water down so that's why first of all keep above row equal 1 multiply n and then start iteration so for underscore in range and the M minus 1. so m is are like a number of Mega vertical um position and then y minus 1 because we already have above row here so we start from middle row in this case so that's why we need to reduce the number of iteration so that's why we need to minus one and then create a current flow initialized with one multiply n and then we need a one more for Loop so for I in length and then start from 1 to n so y we start from one so as I explained earlier we don't have to calculate about these like HK Rhys because uh definitely one way as I explained earlier so that's why we start from one and then update current low and the position should be I equal and the other two numbers so first of all from left side so current low I minus 1 plus and a number from above so above below and uh the position should be I right same and then after that update above row with current row because uh when we finish the calculation of this row we go down this row and there so that's why um next above row should be current row yeah it's obvious and then after that just return above below and a minus one so we initialized current law in the for Loop so we can't reach this variable so that's why we use above row and then last value should be the total number of unique paths in this case 10. yeah so let me submit it yeah looks good and a very good um space complexity like a bit 97 percent that's because uh we keep the unique path with the array okay two arrays and so space complexity should be to end but we can eliminate the constant number so overall time complexity should be order of n in this case yeah so that's all I have for you today so if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
1,291 |
Hello everyone welcome to my channel code sari with mike so today we are going to do video number 81 of our playlist lead code number 91 is ok medium mark but very simple two approachable look sequential digits name is question ka n integer zar has sequential Digits If and only if each digit in the number is one more than the previous digit For example look at this it is a sequential digit why because this digit is one more than its previous digit After this look at another option 1 2 3 4 5 6 7 All these sequences are sequential digits because each digit is one more than its previous digit Return a sorted list of all the integers in the range low to high inclusive of those that have sequential digits OK Does this mean that you should have given low and high, all the sequential digits that are there between low and high, sorry, sequential numbers are integers, right, the number in which sequential digit is present is to be sent to you in a sorted fashion, okay like 100 and 300 to you. This is low, this is high, these are the two numbers in between which are sequential digits, apart from this there are no other numbers, see how one becomes 1 2 3, see this is the number between low and high, okay what else? It can be 2 3 4 and it can be 3 45 but 345 see if it is more than high then we have to tell only the answer between low high low and high so the answer will be 1 2 3 and 2 3 4 ok So right now let me tell you one thing that I have already seen such questions and I always solve them in the same way, so I know what is the most respectful way to solve it. There are many similar problems, I remember one example. Coming, a phone number is given in digits, you have to make possible phone numbers like this, isn't this the kind of question, I have solved it in the past, always try BFS in questions with digits like this, ok. So let's see how will be the thought process of someone that we should make BFS here, so first understand some facts yourself, you must have guessed that the single digit number like one became two became three. It is done then it is done 5 6 7 8 No it is not there, all these will not come in our answer because our take whatever is there is given in the question itself, take whatever is there, it is starting from greater than equal to 10, okay Yes, but yes, these people can help me in getting the answer, like one who is there can help me, how will I take one, I have caught one, I will tell one, brother, what is your last digit, he will say, my last digit is one, there is one two in front of me. Add it, okay, in the same way, I will catch two, I will say two, brother, my last digit is two, so add three in front of me, then see this also, the sequential number has come, this is also a sequential number, if I caught three, then he will say 'tr', make it 34. Four will tell me, make me caught three, then he will say 'tr', make it 34. Four will tell me, make me caught three, then he will say 'tr', make it 34. Four will tell me, make me 45. F will tell me, make me 56. Six will tell me, make me 67. Okay. Sen, what will you say to me? You can make 78. 8 will tell me, you can make 89. Okay, but what will nine say? After nine, just a big number. If there is 10, then you will write 10 here, this is a wrong number, Nai means what is the meaning of sequential digit, that the digit after one digit should be bigger than that, but if one comes, then this is wrong, Nai. If you can't help in our answer, then ignore nine, it's fine, but these people have helped me, haven't they? One helped me to reach the number one, two helped me to reach the number 23, and more after this. These people can help me, look at t, if I catch it can take me to 1 2 3. Why look, I caught vat, I asked him brother, what is your last digit, then he is saying, my last digit is 2. So what is the next number after two, if it is three, then append three, okay here, this way it can help me, 2 3, its last digit is three, so add a four after that, okay here, 34. I have caught 34, what is its last digit, is it four, just add one digit five after it, then it is okay, so we will catch it like this, so see, our answer is coming and going and we will just keep checking which one. -Who is between my low and high? which one. -Who is between my low and high? which one. -Who is between my low and high? Okay, what is the benefit of this? You are getting the answer in sorted fashion every time. Look, this is the answer I got from 1 2 3 4 5 6 7 8. Look, these people are already crazy. 12 23 34 Everything is sorted, then when I have collected answers from these people, then these people are also sorted. See, isn't this the advantage of it? Okay, so see how BFS helps me because see the fashion in which these people came, first one came, then two. Then came three, I processed them in the same fashion, first caught one, brought the answer, then caught two, brought the answer, caught three, brought the answer, caught four, brought the answer and so on, after that look here, first caught two, then here caught 23. So, when can this order happen, when will you use a why? Let's say in the beginning, 1 2 3 4 5 6 7 8, I had putted, right, I had putted these people, nine, so we will putt. No, nine, I can't get the answer, okay, so one by one, first I caught one, I took out one, popped one, I am asking one, brother, what is your last digit, so one, first check that one. Whatever is there, is it the number between low and high? Otherwise, I said to one, okay, no problem, your last digit is one, no, I will make a number from you, if not, then how will you find out the last digit of one, module 10. If you do this then you will get a reminder, the last digit is ok and let me check that it is the last digit, so which digit will be just one bigger digit than this, 1 will be P, that is, if it is T, then I have appended it here, how will you append it. One was mine, earlier it was My number was one, okay, my number was one, so we will do 1 * 10 and whatever is number was one, so we will do 1 * 10 and whatever is number was one, so we will do 1 * 10 and whatever is my last digit, if we get 2, it becomes 12, this is how I made it 12, okay, now it seems valid to me. So see, I will push 12 here, why am I seeing, this process is happening in the same order, okay, then next time I will pop 12, okay, what is the last digit of 12, let me write the last digit of 12, what is two? How to find 12 modulo 10, then we got 2. Now if we have 2, then which digit is just after 2. The last digit is Pw i.e. if tha is there, then we will last digit is Pw i.e. if tha is there, then we will last digit is Pw i.e. if tha is there, then we will append thi. How will we append it? 12 * 10 + 3, then it is done. 123 Then we will 12 * 10 + 3, then it is done. 123 Then we will 12 * 10 + 3, then it is done. 123 Then we will push 123 here till now it is clear ok now let's see by doing a small dry run which was our input and see how it is working so see why I will put one two in the beginning itself. Because only from these people I can start the number, these people can give me possible answers, I will not put 4 5 6 7 8 Naan, because look, if I take out nine, I will pop it, then what is the last digit of nine is fine. Which digit comes just after this? 9 + 1 that is Which digit comes just after this? 9 + 1 that is Which digit comes just after this? 9 + 1 that is 10. So if you append 10 a little bit here, after nine then one will come. If you append 10 here then the digit after nine becomes small then it is valid. If it is not there, then I will not put nine. Okay, I have put only eight. Now let's start my processing. I first took out one and popped it. So one has been popped. Okay, I took out one. Now I will first check what one? Yes, it is the number between low and high, no, then I will say one, no problem, you give me a number with sequential digits, then one will say, okay, take out my last digit, not the last digit, modulo 10, the last digit is one, okay. So now that means the next digit is going to be one more than this i.e. LD be one more than this i.e. LD be one more than this i.e. LD is PW, so what will happen is two, so append two here, otherwise I have put two here, 12, okay, now it is okay. I have put 12 here, ok now this task is over, only one could give the answer, isn't there a little three after one, is n't it, after one there can only be two and there is no possibility, so that's it There was a possibility, I tried it, I got 12, I put it here, okay now I popped two, first check whether two is my answer or not, it is between low and high, otherwise this is my answer. If it is not there, then I have taken out the last digit of two and the last digit is P1, what will happen that is th, so append thi to 23, so I have appended 23 here, simply I will take out three here and pop it again. What is the last digit of three, which is three and which digit is just one more than just three, which is four, so I will append 34 here, it is clear till now, keep doing this, see our why, it will look something like this, look, it will look something like this. Isn't it because all these must have been popped, 4 to 45 must have been found, F to 56 must have been found, 6 to 67, 7 to 78, 8 to 89, these 12, so here it is, 12 23 34, I had written it earlier, so look at our Something like this will be made but till now we have not got even a single answer, okay then I will take them out again, okay, first of all, I will take out this one, then take out 12, okay, I have popped it from q, now look at 12. Take 12, mine is not a number between low and high, so this cannot be my answer, so I will ask 12, brother, what is your last digit, then 12 will say, my last digit is 12 and if you do 10, you will get two, the last digit is two. D + 1 Let's see how much is three, D + 1 Let's see how much is three, D + 1 Let's see how much is three, so okay, append three, I have 123, one number has come, okay, so here I have appended 123, okay, now it is the turn of 23, I have popped 23 from here. Okay, what is the last digit of 23, see, 23 module 10, that is th, which is its next greater digit, which is four, so here I have appended 2 3 4, so now 2 3 4, I have put it here, okay till now it is clear. Like this, we will pop these people and keep inserting them at the back. So see how our Ku will look now. So see something like this will have been created. Look, got 1 2 3, got 2, got 34, popped 34, got 345, got 45, popped 456, got 56. Popped 567, got 67, 678, 78, 789, now I will show you 89, popped 89, looked at its last digit from here, what is the last digit, it is nine, so just take out one greater than digit from it, d + 1. Brother, this is take out one greater than digit from it, d + 1. Brother, this is take out one greater than digit from it, d + 1. Brother, this is 10, will you append 10 here, will you append 10 a little, the next digit should be greater than nine, okay, so this is my last digit, right? What is there after doing + 1. my last digit, right? What is there after doing + 1. my last digit, right? What is there after doing + 1. If it is more than nine, then obviously it is valid. There will be no number, okay, so I have processed 89 but I have not input anything. Okay, so our q will finally look something like this, it is clear till here, okay, now I pop all of them one by one, again I pop 123. Popped, I ask, first of all, tell me whether you are the answer or not. Yes, this is the answer because it is between low and high. Okay, so I added 123 to my result. Okay, now again from 123, I will ask, brother, 123, what is your last digit, then he will say, 'Okay, so just one say, 'Okay, so just one say, 'Okay, so just one digit bigger than three has to be appended here, four but why are you appending it? Look, this is more than high, isn't it? Look at me. If it is only 300 then I will not append it, is n't it? Similarly, I popped 234, first I asked, brother, you are the answer, it said yes, I am a valid answer because I am the value between low and high, okay so 2 3 I added 4 to the answer, now I see 2 3 4, can it give me another number, is it the one with sequential digits, its last digit is four is just a big digit, five is appended here, but 2 3 4 5 Which is more than my high, so why wouldn't I push this too? Similarly, 345. Look, 345, so brother, it itself is more than high, is n't it itself is more than high, so it is obvious, this is not my answer. 456 567 is also higher than high 678 is also higher than high 789 is also higher than high So why is our MT done and nothing is pushed So our while loop ended here BFS and our answer has come It is okay here, remember that this is a method of manipulating digits and getting new numbers. In such problems, BFS works like a charm. Always remember to always use BFS in such problems where you have to manipulate digits. A jumping There was a question named number which I had solved long ago in Gus for Gax and I used the same method in that too but I cannot remember exactly what that question was but in that too it was something similar that by making a plow in the digit a Had to bring it after doing the next digit, there was BFS there too. Okay, so it triggered me exactly from there itself. This question is going to be formed exactly with BFS, so this is the most respectful approach to this problem. Isn't it quite simple? There is also a dry run, if you want, you can pause the video and code it yourself, but I will code it and show you, okay, now let's come to the second approach, okay, which is a very good work around, I will show you and yes second. Before coming into the approach, let me tell you its time complex T. The time of first and second and the value between high and high are due to the fact that A is the number of sequential digits. Okay, so of A. Our time complex will be of A only, where A is What I am saying is the total number of sequential digits is neither between low and high nor is it approx. Maiden. Okay, what is the worst case that all the numbers between high and low will come in the queue, but this is possible obviously. It is not there, so approximately I told O of N. Now let's come to the second approach, whose name is Hey Brother Approach, why is it okay because brother, do n't write this in the interview, it is okay in the interview, if he asks brother and more. Tell me the best and very constant time approach. Tell me the approach with oven time. Only then go for this approach, otherwise this is a kind of work- this approach, otherwise this is a kind of work- this approach, otherwise this is a kind of work- around approach and this is the first approach and this is a generalized approach which will help you in other questions also like this. Okay, so now let's look at our second approach. The second approach is very simple, you had to remember only one thing in it, that if you see it, then you already know the answer that which sequential digits are possible in our integer. Look at what is possible in this world. One, you know that if you start from one, you will get two. Okay, if you start from two, you will get 23. Okay, if you start from th, then start from 3, 4. Start from two. 45 56 These two- 4. Start from two. 45 56 These two- 4. Start from two. 45 56 These two- I am telling you about the two digit ones, okay after 56, it cannot be 6, 7, 8, 9, 10. Right, this is not a valid answer, it is of two digits, after that look, it can be 1, 2, 3, or 2, 3, 4. Maybe 3 4 5 Maybe 4 5 6 Maybe Similarly, keep going, ok, write four digits like this, 1 2 3 4 1 2 Sorry 2 3 4 5 And so on as far as you can go and accept. How much further can you go? You can go till 1 2 3 4 5 6 7 8 9. You can go even further than this. Let's say you have gone till 1 2 3 4 5 6 78. Till 2 3 4 5 6 7 8 9. You see, this eight is of eight digits, now one of no date is also possible, see which one is the only possible one, 1 2 3 4 5 6 78 No, this one is of no digit, so see, there are so many possibilities in two digits, three digits. There are so many possibilities in four digits, so many and so on, there are so many possibilities in eight digits, if there are so many possibilities in nine digits, then brother, there are only so many possible answers, isn't it? Whatever falls under low and high, that is your answer. As it is so simple, put it in the vector of ant, and just iterate over it and mark the number which is between low and high, like let's say 100 and 300. So is this smaller than my low? Yes then continue because low and low need to be bigger than the low. All these are also smaller than the low. Our low was 100. What was 100 and my high was 300. So continue all these. Tooth. Yes 1 2 3 Look, a valid answer is found because look, it is bigger than low and smaller than high, so one answer is found. 2 3 4 Also a valid answer is found, look. 3 45 As soon as I found it, and look, it is bigger than high. Just break here, there is no need to go further because you will get bigger numbers in the future. Okay, as soon as a number is bigger than the highest number, break it. You will have got the answer. 1 2 3 and 2 3 4 is quite simple. There is an approach and see, we have taken this constant space, and its size is also constant, so there will be no time off for iterating on it, because it is a constant time, there is a constant space, it has a fixed amount of numbers, if you iterate on it, then only one time will be charged, obviously. Okay, the space is also a constant because it is a fixed number and will never vary. There are only so many possibilities, it cannot be more than this. Okay, this is a very clever approach. In the interview, tell this approach only if he asks about it. Don't tell him about this one first, that's right. It will not work if you make it with this approach. The most standard and most respectable approach is BFS. Okay, so let's code both and finish it. So let's code exactly the same as just explained. What was the first and standard approach, BFS? K is through, so what did I say in the beginning that I will put it from ev to a because only these people can find out my answer. D is push i, so now let's create our result vector and the same old BFS code. We will keep solving this until we get q dot MT. Popped it from the dot front. Okay, we popped it here. Now look, we have to check that the temp that I have got now should be greater than equal to low. What is the lesson and the lesson should be equal to high, right? Only then it can come in our result. The result is a back temp. Okay, now what can this temp give me? We have to find out, so what did we ask from the temp that your What is the last digit? Temp module 10. Okay and now we have to check that the last digit is pluv, it should be lesson equal to 9 right because there is yes on it, we cannot take a number bigger than no by any one digit. For this, we will push dot, whatever digit has come, we will add the last digit plus it and in the current temp, see how we will do it, I told you, we will push temp * 10 plus the last digit, will push temp * 10 plus the last digit, will push temp * 10 plus the last digit, then we will get our next number, that is, due to the value. That is, if my temp was 12 then we will get the next number 12 23. Okay, in the last we do not have to do anything, we have to return the result. Okay, after submitting it, let's see, we should be able to pass all the test cases, see this, accept. Once this is done, you come to the second approach, but let me tell you one thing that you can further make it smaller. Look at this code, how if the temp I have got is greater than high, then the next one is If you get a big number, then you can break this Y-loo there itself, get a big number, then you can break this Y-loo there itself, get a big number, then you can break this Y-loo there itself, okay, but I have written the standard code so that you do n't have to think too much, okay, so now coming to our O-off-W approach, to our O-off-W approach, to our O-off-W approach, I will reset it. And what I have done is that I have stored all the possible numbers, all the sequential numbers, okay, so just make your vector of int result, okay, int A, how many were possible dot size, so many possible, so that I can see this. Can't be more na means that is a fixed number y which is a na y is a fixed number right for int a i 0 a i lesson a p ok if the current number that I am looking at is ok if that If it is less than low then it is okay to continue because I want a greater lesson, greater than is equal to low and lesson is equal to high or whatever is possible, if it is greater than high then there is no point in going further. Because those will be even bigger numbers and if it is not so, he is not among these two, then yes, he can be my answer, result, push underscore back, all possible, okay, return result in the last, okay then. Its complex number is Right A which is a fixed number, okay, you will definitely get numbers with more sequential digits than this, otherwise I hope I was able to help. Any doubt please raise it in the comment section. All try to help or out. See you. Next video thank you
|
Sequential Digits
|
immediate-food-delivery-i
|
An integer has _sequential digits_ if and only if each digit in the number is one more than the previous digit.
Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits.
**Example 1:**
**Input:** low = 100, high = 300
**Output:** \[123,234\]
**Example 2:**
**Input:** low = 1000, high = 13000
**Output:** \[1234,2345,3456,4567,5678,6789,12345\]
**Constraints:**
* `10 <= low <= high <= 10^9`
| null |
Database
|
Easy
| null |
299 |
hello guys today we are going to look at the problem called poles and cows on lead code it is a famous google question so the question says you are playing the following bulls and cows game with your friend you write down a number and ask your friend to guess what the number is each time your friend makes a guess you provide a hint that indicates how many digits in the set gas matches your secret number exactly in both digit and position which is called the poles and how many digits match the secret number but the position is wrong called the cows so the approach to this question is that we have to compute the poles first and then the Thals later why so I'll give you an example assume that this is the actual number double nine five seven and the guess made is seven nine seven so if we are computing at the same time I mean the poles and the cows at the same time in the same for loop then here we might compute this 7 as a cow but in reality it is not a cow it's a pole the last two sevens in both the actual number and the guests so we might so the actual computation for this problem for this number for this problem should be there are one pole here one bull here so two poles and we will compute this cow as single ha right but if we are doing the computation in the same for loop for both the Bulls and the cows we might end up doing something like this 2 goals and 2 cows which is wrong right so let's go ahead and write down the solution for this problem so first we will initialize our variables for the bolt on the cow zero now we will compute for the pole first so we'll start iterating over thee yes string so I will enumerate over it so I will iterate over the index and the value at the same time so index common down in enumerate guess we'll check if the number and secret string at this index not in not naam index is exactly this number that we are looking at then we have a increment in the both it's a fools if it is not exactly the same then we just continue right we have our bowls computed using this for loop now we'll go on and compute for the cows for that I'll create a counter dictionary for the secret string so count on this whole secret is nothing but the counter dictionary for the secret strings and now we'll again iterate over the guess string to compute for the cows so if the num that we see right now is in count secret it's present in that dictionary then we just look at the value for that key so if count secret sub num is greater than 0 then we have a increment in our cows variable and we have to obtain the value for this particular key as well we have to pick three mint because a decrement by one because we have already considered it as a single instance of a cow the else part will be just be continued because it doesn't have the number of instances left to be computed as a cow right and the else part for the outer if also needs to be continued so now you guys will say that hey what is now you have actually computed the balls in the cows again so that will just update our cows by removing those bolts that's it and what we have to return is the format where we have the poles count we have the a for the balls then we have the cows count and we have the P for the Cubs let me go ahead go through it again once we have the Bulls and the cows variable initialized then we have been deer trading over the guest string and we check if the number that we are looking at right now at that index is it the same in secret as well then we have our pull computed now we create a counter dictionary for the secret strength now we again start iterating over KS to compute for our cows that number is in the counter dictionary for the secret then we check if the value for that key is greater than zero then we increment our count and at the same time we have update the value for that key in the count secret counter dictionary and after doing for all the numbers in okay this should be gas it should not be counter dictionary wait a second what did I do no sorry I thought it was a for loop okay it should be count succeed right sorry now we will update our cows count because it has the balls count as well computed in it so we just remove that and we will turn this strength which is required so let's just run this okay there's a failure because we have poles instead of poor we have success here let's submit this give the success there now I would like to tell you guys one more way that I actually just realized that we can do is instead of this whole if and else here so what I can do is I can create a counter dictionary for the guess as well the counter guess and pen and let and we should trade over the count dictionary for the gas and check that number is in secret instead of doing this whole if and else here what I can do is take the minimum of both the dictionaries for that particular key so our cows will be the minimum of count secret sub now come can yes sub let me run this success is submitted success so let's discuss the time and space complexity for the solution constant time operation this is Big O or big mm whatever notation you want to use N or M for guess N or M would be the number of characters in this guess string constant time operations then these both are big all and Big O of N and Big O of M each of these separately so right now tyll right now we have Big O of n plus Big O of and so Big O of n plus M here Big O of N or Big O of M and then these are constant time operations so the whole solution is Big O of n plus M the space would be we have to count addition ladies so Big O of n plus M again and do we have anything else no support the time and space complexities are the same in this solution Big O of n plus and thank you
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
930 |
Hello Everyone And Welcome Back To My Channel Algorithm Why Today I Am Going To Write The Core And Also Explain You All The Algorithm To Solve This Binary All Are With Some Problem Which Is There In Lead Code It Is Also Present In The Sliding Window And Two Pointer Section of Too Many DSA Sheet Which Makes It a Pretty Important Problem for Interviews And Now a Day I Have Noticed That the Interviewers Are Not Going to Very Complexity But They Are Trying to Go to Ten Topic Sach As Two Pointer Sliding Window Greedy Algorithms and Binary Search to check the logic of the candidate So this is a good problem to practice problem solving So let's start it by taking the name of Shri Krishna, in this problem we will be given an integer named names and one Integer will be given as goal. We have to tell how many such sub-arrays are possible in this number whose many such sub-arrays are possible in this number whose many such sub-arrays are possible in this number whose elements when summed is equal to goal. Well, if we see in this array, goal is given, then if this sub-array is given then goal is given, then if this sub-array is given then goal is given, then if this sub-array is given then If we look at the array 10 then the sum of its elements will be two, then again 10 will also be two, then 01 will also be two and again 10 will be 2. Okay, so we have to tell the count of sub arrays, how many sub arrays are there whose sum is Ok, so there can be multiple ways to solve this. Of course, the first thing that comes to mind is that we take out all the sub-raises o of n and then o that we take out all the sub-raises o of n and then o that we take out all the sub-raises o of n and then o of n. Calculate the sum and check whether it is equal to the round or not. If it is ok then it comes to o of n. Due to this, the complex problem which is not good at all can be reduced to the value of a scr if we remove all the arrays at the same time. If we keep calculating the sum and checking, then this is also not a good solution. Off a screen is not a good time complexity. Now how can we reduce it to off a. Firstly, there is the prefix sum method in which we take every prefix. We extract the sum, that is, on every index and then store how many number of indexes the particular prefix is even, then what remains in it, whatever prefix is even, then what remains in it, whatever prefix is even, then what remains in it, whatever remains, that prefix remains even, it itself and the values, what remains is the count of indexes on which That prefix sum has come till now, so by using it we can find out the count of sub areas whose sum should be equal to the goal. Okay, but we are not going to do it with this technique, we are going to use the technique of at most. Okay. So, to understand the technique of At Most, we will try to do a dry run on this example. Okay, so this is our example and this is it. Okay, now what happens in At Most? Basically, we figure out Count of Sub Arrays whose even number is at most two means if the even number is coming to zero of any sub array then it will also be loaded, it is ok in that one, at the most particular, whatever our number is, it is ok in that if If even one is coming from any sub array then it will also be included then we will first find out the count of sub arrays whose sum is at most round is ok and then we will find out the count of sub arrays whose even is at most round -1 ok So the is at most round -1 ok So the is at most round -1 ok So the count of sub arrays whose sum is at most is round from the round. If we subtract the count of sub arrays whose sum is at most round is round minus and then what will happen is that we will be left with such sub arrays whose sum is at most round and Atmost is also a goal because we have removed atmost goal minus and from it, so now whatever is equal will be atmost goal only, so when atmost and atmost are equal to goals, then that means we have all the arrays which Sum is exactly round, okay, so by doing this we can find out all the arrays whose sum is at most round, then this is the formula to find it is okay, both these things are done with the same function, we will be able to find out all the arrays with sum at most round and Sub array with sum at most col my let's see what we are going to do in that function okay so we are going to take four variables this is the end which will basically be inside a for loop okay and this is the start count and sum we If we start separately, then how are we going to find out that equal to at most goal? Let's see, we will take a window, okay, it will be a window, it will start from the beginning, including start and end at the end, including end. Okay, so let's start the window like Yes, we will add all the elements of the window to the sum, okay, so when the end is zero and the start is zero, then there is only one element in the window, that is one, so we will add it to the sum, it will become one, okay then. After that we will check whether this sum is equal to the round or less than the round. Sorry, if it is equal or less, then what we will do is that in this window, starting from the last element, every sub is possible, okay from the last element. Now we have to start, I will tell you how and why you are doing it, but for now, just note that starting from the last element, we will add all the possible arrays to the count in that window, that is the If the size of the window is ok, then we will add the size of the window to the count. How to calculate the size of the window: end mine start + How to calculate the size of the window: end mine start + How to calculate the size of the window: end mine start + 1. Okay, so now the count we have is one and end we have taken the first one. I mean, for the row eight element, we had calculated the sum, so we will change the start from row to one. Okay, now when we come to the first index, the size of our window has become two. Okay, two elements have arrived and Even, we still have one because 1 p 0 is one. Now we will see whether again it is less than or equal to the goal. Yes, if it is equal, then in the count again we will add the size of the window that is to add. Okay hat size. Why are we adding off the window because we are seeing that all the sub-arrays starting from the last element are all the sub-arrays starting from the last element are all the sub-arrays starting from the last element are in that particular window, that is the value that we are adding to the count and we are doing this because We are starting from the last element because we have already added all the arrays before that. Okay, because when we are at zero, all the arrays before that are that one. They were starting from 1, we had already added them to the account. Okay, so if we add this two, then this count will become three. Okay, so 1 is 2 is 3. For this window, now and again there will be an increase of one. From will become two. Okay, so now the window that has become is 10. Okay, now what is the even in this window is two. Now we will add one to it. Okay, so if it is less than or equal to two, then what will we do? Again if we add a plus to it, the window size will become three to six. Okay, now we will go to the next index from two to three. Okay, so the even will remain two. Again, this window size will become four, so add four to six. Then it will become 10. Okay, now when we move from zero to four, the even number will become three. This is the time to decrease the window size from the beginning. Okay, because now it is more than the round and we have to Only such sub-arrays have to be taken out and we have to Only such sub-arrays have to be taken out and we have to Only such sub-arrays have to be taken out whose sum at most is round, okay or at most, and K is round in this case, now round will be minus and also, okay, so what will we do now that this window size has become like this. If the window size of five elements was created then we will remove it from the starting, we will remove one element from the starting. Okay, so this was the window size from the start, we will change it from zero to one, that means we have removed the first element and when we remove the first element. So if the subx again becomes two out of the even, then what will be the window size? From here, the sum of these four elements is now the sum of these four elements is again two, which is equal to the round or is smaller, less than equal to two, then again. We will add the window size plus in the count, that is the number of sub- number of sub- number of sub- arrays which are being created starting from the last index till the first element of the window, whose sum will come at most round or at most k, then it will become 10 + 4 14, most k, then it will become 10 + 4 14, most k, then it will become 10 + 4 14, okay. And this will end up being 5 after which the loop will end up ok so sum sub is equal to sum at most round how much has come 14 ok and with the same technique we will get sum at most round -1 which in this case will get sum at most round -1 which in this case will get sum at most round -1 which in this case will come out to be 10 Okay, so 14 - 10, we will return 4. come out to be 10 Okay, so 14 - 10, we will return 4. In this part example, which is also our answer, okay, so now we have understood it, now let's code it quickly, it is not very difficult to code, just find a function. Will remain in which we will calculate the sub-ranges of at most i mean at most Will remain in which we will calculate the sub-ranges of at most i mean at most Will remain in which we will calculate the sub-ranges of at most i mean at most which will have their sum, so let's start writing this private int at most's int numbers then int goal, now we will take a sum so that we can find the sum on the index. I am taking the answer because it is the answer according to this function then we will take a start which will be zero then we will start for int i is equal to zero int and i equal to 0 i mean then and should be less than names dot length and then end Plus plus this is doing it at basically we will add to the sum for each index then numbers at end ok then while sum is greater than round if sum is greater than round and start is less than or equal to end then what do we If we keep decreasing the window size, then what will we remove from the sum, we will remove the starting element and then start plus, we will do this. Okay, then what will we add to the answer which is the current window size is and minus start. Psv is ok and then we will return the answer. Okay, now what will we return here? At the most, we will round the numbers, comma, and then we will round the minus and ok and we will return this. Now let's run it once and see. If there are sample test cases then it is successful and the code is also successfully submitted so this question ends here now we will meet with the next question in the next video but before that please don't forget to like the video and subscribe to my channel and also Tell me my improvement points in the comment section datchi
|
Binary Subarrays With Sum
|
all-possible-full-binary-trees
|
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0,1\]
\[**1,0,1,0**,1\]
\[1,**0,1,0,1**\]
\[1,0,**1,0,1**\]
**Example 2:**
**Input:** nums = \[0,0,0,0,0\], goal = 0
**Output:** 15
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `nums[i]` is either `0` or `1`.
* `0 <= goal <= nums.length`
| null |
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
|
Medium
| null |
733 |
hey there so today's li coding challenge question it's called flat fill so what we have here is an image represented by a 2d array of integers it's a two-dimensional matrix and the integer two-dimensional matrix and the integer two-dimensional matrix and the integer represents the pixel value of the image from 0 to 65,535 that's 2 to the 16 so from 0 to 65,535 that's 2 to the 16 so from 0 to 65,535 that's 2 to the 16 so it's a 16-bit integers I guess and it's a 16-bit integers I guess and it's a 16-bit integers I guess and presumably it's a grayscale black-and-white image because we only black-and-white image because we only black-and-white image because we only have one channel what do we want to do is to given a starting pixel represents by the rule number and column number we want to perform a flood fill so it's basically changing the connected cells connected to locations in the picture that's of the same color with this new color so we start from the starting pixel and we can move in for directional up and down left and right whenever we can so for all those reachable locations with the same color as the starting pixel we change the change them into the new color and we return the image after modification so as an example we have this input image represented by this array of arrays I'll just do a little bit of rearranging to make them make it looks like an actual picture we have the real number and color number to be 1 the new color is 2 so the first thing we keep track check is to the first thing we do is actually to grab the old color so that we can do a comparison because once we start to change the colors we will lose that so the old color is gonna be the row index 1 and call an index 1 that's the middle one there so the o color is 1 so when we do the explorations about the adjacent cells inside this 2d matrix whenever we see a reach for 1 we can change the value in to 2 so it depends on how we do this exploration if we do BFS it will be something like this we change the starting pixel to be to will move in four directions we change the upper to be to change the left to be 2 and then we then change the rich pasta front from the top the left and right from the top to be 2 and then we go back to this left order to the upper one already been changed so we modified the one that's under it and after that we run out of the salsa we can actually go to so we so that's when we terminate and yeah so then one that's just a you know straighter here is the BFS kind of strategy if it's a DFS it will be let's say that we're changing in the back to 1 using DFS it could be 1 and backtrack go to the other direction then backtrack go towards left and then change the very last one there so this is illustrators DFS that there's really no difference in this case because we have to explore all the connected components and we have to visit every cell at Arista once so either BFS or DFS there's no shortest path kind of situation we don't have early stopping so using the 2 equivalent and in terms of time space analysis the space is going to be the same size of the matrix if we have to if the whole image is the in the worst case the if the whole image is just a 1 single color than doing the fluffle we have to change everything so the time and space will be order of number of values in the 2d matrix so that's the time and space so that's pretty much it's a relatively straightforward question so let's start there we drop the number of rows and M columns do we have any edge case that doesn't really mention oh it says it has to be at least on one pixel so yeah subscribe laughs we don't need to have a handle the case when that's empty and then we make a car keep track of the old color which is the image source row source : that's going to be the source : that's going to be the source : that's going to be the criteria we check to actually perform the color changing doing the exploration so then we're gonna have a deck which contains a the locations which is a top of to do number of a color numbers so it's integer we call this to color that means the cells we need to explore and do the color changing or to fill and initially we were just have the we just have the source row and sauce color in there and what are we going to do is to while we still have something to do somewhere to do meaning that this stack is not empty we're gonna grab the cell valio so that's the location is going to be the if we do BFS it will be prompt and we're going to pop that out then we can unpack this to be the rule number and call number what we need to do is to change the color for that one thing that I we can actually terminate early on is the one if the old color is the new color then there is no change that is needed whatsoever I just add one right here so that's handled a special case so just make a comment here we're doing VFS this is the rule number and column number what we need to do is to actually do the color changing you make low and Colin set the color to be the new color then we're gonna do the directional for directional move so if we can move up that's if the rule number minus one it's it's greater than or equal to 0 and the cell that's above us is the color that we can it's the same as the old color then we're gonna just push that the location on to the stack so that's move up then we'll just basically make duplications the one curve down as well so that the condition now becomes we are not out of the exiting the total number of rows by moving down and also the cell that's directly below us is the odd color then we can move there and actually to the color changing and keep exploring funda from there as well and then with the only deal with the move right and left which is the equivalent to : subtract 1 and Collin equivalent to : subtract 1 and Collin equivalent to : subtract 1 and Collin plus 1 and the condition for moving towards right is that the new column number has to be less than the total column number yeah just making a feel small changes should be good and in the end we have to return the modified image so that's pretty much it let me run through some examples yeah this one looks ok just quickly check if I have obvious problems I drove 600 yeah so that's a pretty much the solution I'm submitted that's working I guess little bit organize can be done as to consolidate the small line to maybe put the four movements into some kind of array because it's pretty much the negative 1 0 plus 1 0 negative 1 0 plus 1 by but you know by moving the deltas according to the rows and columns and so that this can be a little bit nicer but I think I personally think this is fine too so yeah that's the question
|
Flood Fill
|
flood-fill
|
An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n`
|
Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.
|
Array,Depth-First Search,Breadth-First Search,Matrix
|
Easy
|
463
|
1,832 |
hello everyone so in this video we'll solve liquid problem number 1832 that is check if the sentence is pan gram so a pan gram is a sentence in which every letter of the English alphabet appears at least once so we are given a sentence or a string and we have to check if the sentence is pan gram or not and if it is a pan gram then we have to return true and if not then we have to return false so uh in example one the given sentence is the quick Crown fox jumps over the lazy dog as this sentence contains all the letters of English alphabet so this is a pan graph in example 2 the sentence is lead code and it does not contain all the letters so the output will be false so in programming how we can check the given sentence or string is a pan gram so uh to check first we'll create an array and the array length will be of 26 and we will initialize all the values of that array 2 of false so let's consider this array and it is having length of 26. and all the values are false after initializing the array we will scan each character of the sentence one by one and we will get the position of each character so in the first sentence the first character is T and we'll get the position of T in English alphabet sequence so the position will come to 20 as a t comes on the 20th Place for H it will come as 8 for E it is 5. similarly we will get all the position of each of the character and while getting the position we'll change the value Falls to true it will say that this character is encountered so for T we'll change the position 20th it will be somewhere here to true then we'll change the eighth position to true it will be somewhere here then we'll change the 2 then we'll change the fifth position to true so this false will change to True like this we will keep on doing this until we reach the last character and after reaching the last character we will check this 26 character length array so if all the values are true then we have encountered all the characters in the given sentence and we will return true and if any of the value is false then we will return false so let's code this in C plus also to get the position of character in alphabet sequence we'll subtract the character a from the character being scanned so I'll show you this in other compiler so if we are scanning any character like B so what we will do is we will subtract the character a from that and it will give us the integer value so like we are having B we will subtract a from this so this will give us output of 2. sorry this will give us the output of 1 K minus a will give us 0. so like this we will get the position of the character and we will update our false value to True based upon this position only so now let's come to the coding part so in the code first I created the vector size of 26 and initialize all the value to false then I am iterating all the character in the sentence and I am getting the position using this part for that position we are making the value in the position Vector as true and then we are iterating through the complete position vector and if any of the values false then we will return false and otherwise we'll return to also if you are confused in this uh this part then we can write another variable for it like this yeah so now we are getting position of a current character in the alphabet sequence and then we are marking the current character as true so this way also you can do or you can write it directly as I have done earlier so now let's run this code yes so this is accepted now let's run for all the test cases yes so this is acceptable for all the test cases thank you for watching the video and if you find this video helpful please like share the video and subscribe to the channel
|
Check if the Sentence Is Pangram
|
minimum-operations-to-make-a-subsequence
|
A **pangram** is a sentence where every letter of the English alphabet appears at least once.
Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._
**Example 1:**
**Input:** sentence = "thequickbrownfoxjumpsoverthelazydog "
**Output:** true
**Explanation:** sentence contains at least one of every letter of the English alphabet.
**Example 2:**
**Input:** sentence = "leetcode "
**Output:** false
**Constraints:**
* `1 <= sentence.length <= 1000`
* `sentence` consists of lowercase English letters.
|
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
|
Array,Hash Table,Binary Search,Greedy
|
Hard
| null |
48 |
Hands Free MP3 Like Problem Gets From Different Challenge Give The Problem Saint Petersburg President Of Russia Rooted S Ki Tempering Chaudhary Chalte Cement To Samhar Problem Special Dhatu Ko 200 The Year To Convert Matrix To Single Fold The Video then subscribe to the Page if you liked The Video then subscribe to the Page Subscribe 560 That You Like Rotating Increase Time Judgment Services Subscribe 600 Petrol Station Superintendent A Sophisticated Events But Made Off To 200 Using This Post No Limit On Help Only Post Why Now Its Quantity Pick Jayaram Only Completed in frigate and tell ok ho main friday find executive the uses of this is what is the tourist attraction can destroy the elements after she kid that sun and jack reacher question position others kid will be a loot that show is metric mp lemon used Is obscene social obligation of Kabir and poster hotel distance da loot but these were that Nav Andhi Toofan fear like and subscribe internet ko subscribe must subscribe to is otherwise this matrix when matrix pick up against a little bit shuddhi internal and This Matrix Post Metric First Subscribe 180 Degree Spoon Licking The Matrix Is Just Reacting With Respect To A Girl Of Second Day That Dam 999 The Matrix Scan Seervi's Teeth Extraction Seervi End Tours Whatever Private Result Metric Subscribe To's Sutak Move into Service Channel of Providence Has to Install Na Performance Testing Replication Global Ratio Engagement with Respect to the Subject Subscribe to The Channel Last Decade Distance from This is the Meaning of Loot-Loot Starting with M Fine Meaning of Loot-Loot Starting with M Fine Meaning of Loot-Loot Starting with M Fine Paste in Description Box and Comment It Committed In School Loot A Solid Object Any Scripts And Give Etc Do Subscribe And Like Comment Thank You All The To Subscribe Video Like Share And Subscribe
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
1,935 |
hey everybody it's payne here so today we're going to talk about the first question from nico weekly contest 250 it's called maximum number of words you can type so basically the question is there's a malfunction keyboard where some letter key do not work or the key on key will work properly you have a string text a word separated by a single space no leading or trolling space and another string that is called broken letters of all distinct letter keys that are broken the return is the number of words in text you can fully type using this keyboard so basically let's look at example a given text hello world have two words broken letters they are a and d and yeah as you can see up is one because the word have the world have the words d character d here so we cannot fully type this word all right so let's see what we can do so my site is it says the words in this text string are separate by space so we basically try to split out every words first you know so we can examine it word by word see if you know any character in there count contains the broken letters here so put it with the split method from the string and we if we see a space we put them you know all of them in array string array code t and we create a variable called total which consists the number of words in this case is two and really we need a way to look through every words array so we use a for each loop each words we're taking out from the array and also we need to look through each character in the broken letter so forth for checking it the constraints so for character broken we're taking out from broken letters and we need to change to character arrays because we need a iterable element here and we check if the string is contained broken word one by one if we see around this successfully along this loop we decrement the total number of words that can be typed 40 by one and we'll break it and then you'll run another loop and we'll return the total number so yeah let's see the it's pretty simple and straightforward let's see the result yep so let's submit it and see if so this is not the optimized solution but yeah thank you for watching have a nice day
|
Maximum Number of Words You Can Type
|
minimum-number-of-operations-to-reinitialize-a-permutation
|
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_.
**Example 1:**
**Input:** text = "hello world ", brokenLetters = "ad "
**Output:** 1
**Explanation:** We cannot type "world " because the 'd' key is broken.
**Example 2:**
**Input:** text = "leet code ", brokenLetters = "lt "
**Output:** 1
**Explanation:** We cannot type "leet " because the 'l' and 't' keys are broken.
**Example 3:**
**Input:** text = "leet code ", brokenLetters = "e "
**Output:** 0
**Explanation:** We cannot type either word because the 'e' key is broken.
**Constraints:**
* `1 <= text.length <= 104`
* `0 <= brokenLetters.length <= 26`
* `text` consists of words separated by a single space without any leading or trailing spaces.
* Each word only consists of lowercase English letters.
* `brokenLetters` consists of **distinct** lowercase English letters.
|
It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution.
|
Array,Math,Simulation
|
Medium
| null |
1,367 |
Hua Hai Hua Hai Hello Everyone 2014 Linked List In Minority In This Problem Play List Specific Medicinal Uses And Have To Find The Meaning Of This Point To Sid Jaisi Na Liye Subscribe And To-Do List Play List Do A New Vihar To Things Which Have Any Five Years Two Things One Ever Held In One Hour Root And Root Par Stop This Is My Channel Like This Song DJ Already Present In The Middle Of No Return For My Head Ghrit To My YouTube Channel Main Hoon Main Na For fear distant season you reduce Ahmed including hotel in that was tide and check this dish my route is this my first value note images for its value is valued typing fast chatting request for not equal to two if all type all my left and eight call Me right side dish for private colleges for all defense for and looted from video request four this for this post know what is the meaning of this point in the middle 49 minutes and you have to be the phoenix next element and this Treatment them like no when Lord Canning send a message to through Absolute Peace 218 or Digital Suicide Point - 218 or Digital Suicide Point - 218 or Digital Suicide Point - Shyam Lal Meghvanshi Software from Someone Who Died in This Not Suited Notification Written Test for the post after right subscribe our Channel Please subscribe this Video plz subscribe and Share subscribe and subscribe the Channel Apne Root Is Network President Paul Se Bheed Returning from Right to Left or Right Its Right is Illegal Forces Tanning is That 04 2012 Not Benefit from These Dos Not Mean That Will Give 66 Deficient Management Kota Se Itni Moti He Apna Off But Is This What Did Not Mean That You Have At Least In The Final List Play List Video 5000 Na Every Day Through Railway Line And Remind This Route Is My Channel It's true and finally Bigg Boss ko hai to hai woh time denge festival and taking it's my YouTube channel I oil return for others but I will do the timing of it Root velvet is equal to hai value every citizen of Mirch ek mike Spiral Dobe Function And White Droids Function Check Dushman Sanjay Laddu Meghwal English Fonts How Women End Continuously Overhead Next 150 Root Channel Head Value For School Children And In This National Voters Left And Life Management Kismat Root Value Speech To Held For Its Next IS On Left Side From Left To Right I Have Mute Ne Swallow The Waste Management For Its Not Planets Will Return For Hong Through I Will Fight Maz List And Caused Due Date Checking Which Five Vote And Notes On Exit Note 4 Images For This Point Dysfunctional 13050 Ball Involved Checkpost No The First Not Willing To Develop This Is My Son 1922 Of My Life Is This What Is This Thank You I Am A Height Finance Them Act Will Thread Its Candidates Can E Go To Make How To Find Trees Will Be And Is And Want To Be Maths Of List of Us Mic List and Khae Vitavari Maximum Is Photo Dad Which Will Go to Phase Match Award Time Complexity and And You Must Avoid This Website Will Bf I Hope You Understand Your Position and Width Help You Don't Forget to Hit Like and Subscribe Button Thanks For Watching Hai Ajay Ko
|
Linked List in Binary Tree
|
maximum-height-by-stacking-cuboids
|
Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
**Example 1:**
**Input:** head = \[4,2,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** true
**Explanation:** Nodes in blue form a subpath in the binary Tree.
**Example 2:**
**Input:** head = \[1,4,2,6\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** true
**Example 3:**
**Input:** head = \[1,4,2,6,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** false
**Explanation:** There is no path in the binary tree that contains all the elements of the linked list from `head`.
**Constraints:**
* The number of nodes in the tree will be in the range `[1, 2500]`.
* The number of nodes in the list will be in the range `[1, 100]`.
* `1 <= Node.val <= 100` for each node in the linked list and binary tree.
|
Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?
|
Array,Dynamic Programming,Sorting
|
Hard
|
2123
|
881 |
hey so welcome back in this another daily code problem so today is April 3rd and we got a question called boats to save people so let's take a look at it and so today's question is a medium level question and you're given a people array along with a corresponding limit and what you want to do is you are given an infinite number of boats and you want to save these people and so each person has a corresponding weight like in this array there's a person that weighs three two and one and you have a limit of three here and that limit is like the weight limit of each boat um now you have an infinite number of boats but naturally you can have a limit of up most to three and then also and I actually didn't catch this the first time I read it um so I got the answer wrong initially was you can carry at most two people at the same time and so you have this many people you have four people each boat can carry two people at a time and the weight limit is three okay and so the first approach that I took when think about this problem is I sorted it and so I got it as one two and three just because I thought that okay if you have a weight limit of three you can kind of move from left to right here and just add the values as you go and so you can add one then you look to right and say okay I'll add two here so then I have three and then I look at this one here and then so this is a vote and then I grab two plus three is too big so I wouldn't add it so then I have a third boat and then I add this one which is three and that works pretty well just kind of moving left to right but this actually won't work because there are cases where um let's see if there is one here three four five is that one no um it's basically cases where okay if you are moving from left to right and say you have like one two and then like five and so in this case say if we're going from left to right then we sorted it and you can have utmost of six than what you want to use for your boats is five and one and then these three here oh I guess you can't do that um let's say that this is actually one two four and five yeah and then you can have at most a weight of six so you wanna grab this one and then these two here right and so but if you're going from left to right and just reading it and just keep adding until you hit the limit and then do this kind of a greedy way from left to right you won't be able to catch these cases where okay I want to grab these two together and then these two and so what you actually want to do is once again if we look at that case so one two and let's maybe add two again here for four or five is that once again you want to sort the array but then you want to have a right pointer and then a left pointer and then you constantly just compare the right and the left and see if you can include either or you first check if you can add five so five is less than uh the target which is six then you add it and so the current running sum is five and then you move your right pointer over to here and you say okay can I add four so four plus five is nine so nope that won't work but can I add um one to five yes I can because that's less than or equal to six and so then there's a boat and so once again you move your left pointer and so you no longer look at these two values and then you say okay is four less than six yes and then is four plus four less than six no but I can add the one on the left so once again like these pointers move forward and backwards and so you're constantly checking can I add the value at the right pointer if so that I add it and I keep checking the right pointer until I can't add it anymore and then you start adding from the left pointer onwards but naturally you can only have two people per vote and so that's the other condition and that's the album so it's n log and time complexity because the bottleneck here is the Sorting because after you sort it you just have a two-pointer method that just iterates two-pointer method that just iterates two-pointer method that just iterates forwards and they meet in the middle and so that's just of n time and then for space complexity it's just o one because we're not using any extra space so let's go ahead and write out this algorithm so naturally we want to return the number of boats that we use and that will be initially set to zero and then we're also going to want to keep track of the current running total of people so the number of people so let's just say um like people you also want to keep track of your left and right pointer and so that will be first set to zero and then the length of the array minus one um actually I'm just gonna copy this I renamed this as a just simplified for me but I want to make sure that we have the same variable names so it's actually called people so the length of the people array and I think that the number of boats I think that's about it we might need one more variable but so we say okay while our left pointer or less is less than or equal to our right pointer and this is just templating for when you want to meet in the middle with a two pointer method it's also used for binary search and then you say okay if our current running weight so that's the other so we'll say like wait so if our weight is if the weight Plus uh the value or the weight of the person at a right pointer is less than or equal to our Target or our limit then we'll include it because naturally if we can include that weight on the right then we'll do it so we want to include that person in the boat but then also you want to say okay and that the number of people in our boat is less than two so people is less than two great and so let's add that person to our boat so we say okay people plus one and then we add to our weight that person's weight and you continue on so then after that what you want to do is say okay oh and the other thing that we have to do here is naturally if we added that person we want to decrement our right pointer and so we say R minus equals one otherwise if we can include the left-hand person we will so left-hand person we will so left-hand person we will so person at the left pointer is less than or limit and the number of people's less than two then pretty much the same logic here except we want to add to our left pointer and add the person on the left great and so the other case is just otherwise what we want to do is just say okay we can't add any more people to this boat then let's just add who we have on the boat and just move forward and so we say okay then we want to set the number of people to zero we want to set the weight and let's increment our boats so that increments the count of our votes we reset the people to zero because now there's no one else in the boat because we just used one and then the weight that we're currently at will be then equal to the people on the right or no you don't have to do this I believe yeah great and so what we can do I believe is then we just say okay given this case eventually these will overlap because they're going to be me in the middle and you might actually have a person on the on your weight count and this is an edge case where they haven't kind of hit this else case and so you want to add that person so if the weight is equal to zero then we just send the number of votes that we have otherwise let's return the number of votes plus one let's try running that I wrote this bit different than when I did it oh tle so what we're doing is left and right so we do that so I believe this is because we're not we're incrementing on people we add the weight of plus equals one and so I think this is a case where okay you keep hitting this else condition so what we can do is we'll just always say that we add someone each iteration someone's always going to be added to the boat and so someone's added in this boat someone's out in this case but in this case we also want to add someone so then let's just set our weight equal to the person on the right and naturally we want to subtract by one here great yeah so it was just constantly iterating through this Loop here and hitting this else case so that's why we're getting that tleu like that infinite Loop that we're running um and so we can just handle it by okay saying um let's just always add someone and in this Edge case we'll just add the person on the right okay so let's try running that and submitting it oh something's wrong here so oh I forgot the sore head um let's go ahead and sort it uh let's see are people array great let's try running that and that's the algorithm so yeah so once again um I think it makes sense to think about sorting it since you want to try to handle the weight and you care about okay let's try to add as many people that weigh the most and then pair them with people that weigh the last to try and find okay if we're given five we can have at most six people let's try to find someone that weighs one you know and so forth and you just kind of it's a greedy algorithm where you want to greedily pick people um and I think the intuition behind this just comes naturally like you have to think about okay can I sort this can I look at it forwards backwards should I iterate backwards should I have two pointers three pointers like and I think a lot of those techniques you just roll through when you read a question so it's a great problem to practice with I think it's great medium level question and I hope you enjoyed it so have a great day and good luck with the rest of your algorithms thanks for watching
|
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 |
1,727 |
hello and welcome to another video in this problem we're going to be working on largest submatrix with rearrangements and in the problem you're given a binary Matrix of size M * n and given a binary Matrix of size M * n and given a binary Matrix of size M * n and you're allowed to rearrange The Columns of the Matrix in any order return the area of the largest submatrix with the Matrix where every element of the submatrix is one after you reorder The Columns optimally so you're allowed to move the columns around so in this case you would want to move the columns around to have this pair of ones and this pair of ones together so here you would get an area of four in this one you want to move all the ones together so there's a bunch of ways to do it but essentially here you would get an area of three and we can do this last one so for this last one we have one Z and we also have one Z1 so what you'd want to do is you'd want to swap these two columns actually even if you swap these two columns it still wouldn't matter because you still wouldn't get a bigger area so the biggest area you can actually have is this or you know there's like a few of them but essentially even if you swapped these columns around you can never get a 4x4 or like anything bigger than a one than a 1 by two so the answer here is two and that's kind of what they tell you must rearrange the entire columns there's no way to make a submatrix with larger area two so we're actually going to focus on how to do this and the first thing to notice is the constraints are M * n notice is the constraints are M * n notice is the constraints are M * n is 10 5th so if that means that we are looking for like a linear or an N log n approach and anything fast anything slower is not going to work right so we want to have like a one pass or some kind of maybe like sorting some stuff but we can't have anything slower than that so what we're going to do is we're actually going to figure out for each column like what's the biggest rectangle we can make with that column and the way we're going to do that is we're actually going to write instead of storing it like this it's kind of useless we are going to do it another way and so I have an example here where we have five different columns and we have a bunch of numbers and these ones are okay but really what we want to figure out is like for these ones how far does the rectangle go with these ones right like if I have one here and one here can I make a rectangle and how do I know so the way we're going to do this is instead of storing these as ones what we're going to do is we're going to go down the column and for every consecutive one we will actually add a one and then every time there's zero we'll just reset it so essentially here it'll be like one then we will change this to two and we'll change this to three right because we have a consecutive one and this tells us that if we're at this location here there are three ones in a row right we know that from one number and that's going to help us a lot as opposed to a bunch of ones where like we' have to count it where like we' have to count it where like we' have to count it up so let's do that as well here so we have one two and then this is one two let actually just clean it up a little bit so this is just going to be 1 two 3 four five and right we have a lot more information now like we know for this five we know that there are five ones in a row here that we can use to make a rectangle so we're basically getting a lot more information just from one number now without having to like Loop through anything so we have one and then we have one 2 three okay now basically we're going to focus on for each row we're going to say okay well let's say the rectangle we have the bottom right corner of the rectangle that's probably a good way to do it the bottom right corner of the rectangle so let say we have a rectangle is this one here and then what's the biggest rectangle we can build that way right so let's figure that out now also notice for this row we're also going to want to do one more thing because these are going to be all over the place we can sort our rows like we can sort each row and let's think about how we'd want to sort the row so let's maybe look at this like bottom row first how would we want to sort the row and the reason we can sort the row is because when we find like let's say the biggest rectangle we can make in this whole grid is this one if we have something like let's go back let's actually go back to this example here and this is going to make it a lot clear so let's say this is already sorted if we have one and then we have two here and we have one two three like this then we know that here we have three and here we have two so we know that like if these two are together we can easily make a 2 by two right we're going to take the minimum of these and make something but how do we want to sort these efficiently to make sure that like we get the biggest rectangle possible and the way you're going to want to sort these is in descending order because like looking at this picture let's say what if our biggest rectangle is actually just the First Column if we sort it in descending order we're basically going to be checking every single area and we're going to take the greatest numbers first right so like if we have numbers like this like 5 4 3 2 1 we will check a 1x5 and then a 2x4 and then a 3X3 and so on where if we had it another way it would be a lot worse right like if we had it like this then how would this even work right like we wouldn't want to use this we want to use the big side available first basically right we want to use the biggest side available first and then as we extend it to be more and more area then we just see like what's available after that so we're going to sort every single Row from increasing to decreasing order so let's do that as well and then let's have some kind of result and this is going to make a lot more sense so let's have a result let's just set it to zero so let's sort this top row first so it'll just be one zero and then obviously these have an index right so we can go down the row and we could say like okay well if the bottom right corner of our rectangle is this Square how wide is this well this is only one and how wide is it's only one it's one up and only one across so this would be a 1 by one so our result here would be updated to one now what if this was the bottom right then anything to the left of it would also be included right because we are doing in descending order so we would have a 2X one because we have two numbers now so we can get a 2X one if this was the bottom right we'd have a 3x1 right 3x one if this was the bottom right we'd have a 4x1 and this is going to make a lot more sense with the bigger numbers as well so the biggest thing here we can make is a 4X one and obviously with a zero it would just be zero so the biggest rectangle we can make with this top row is a 4X one so we will update our result to be before now let's sort this again so if we have uh two 2 1 Z let's see what happens here so in the first row we have two squares so if we just use this column only we can build a two by one right we only have one column so we could build a 2 by one Tri be two but that's not as big as our previous one what about over here so here we have a two as well and remember we can use every row before this because every row before this is greater than or equal to this number so if every row before this is greater than or equals to this number that means whatever row we're on that will be the um the height of our rectangle and then the width will just be the number of rows we've traversed right so we can write that down as well so per is height and then width equals number of rows we've traversed or I guess if you want to use an index as well this will be the index plus one right so if this was like index one we'd have two here and then we basically just multiply both of those right the height by the width to get the rectangle so here we can get a rectangle 4 and that makes total sense right because if we go back to this we can easily make a 2 x two because the way it would work is we would take this one over here because after we sorted we would put this column right over here right and then we would get something like this where we would get a one two because we have two of them so this basically means this whole grid is by ones right because remember two means there is two ones in a row so it would basically be like this so that's why we know we can do that so let's go uh keep going here the next number is one that means the height is going to be one and the width will be how many we've traversed so this is three so this is going to be a 3x1 which is still smaller than our result and this also makes sense right we could easily build a 3X one here if we just have these two and this these the three columns right next to each other right so we could have like these two and then this one or whatever or if we wanted this one to be the third one we could have this one then this one and so on okay so let's go and now we have a zero so anything with zeros will just give you a zero are right so we can keep going so for the next one we get three sorted again 2 1 so now three means we're on the first one again so we could build a 1x3 right and here we could build a 2x two which is the same as we had before and hopefully now you could see how you could build a 2X two so there's a few ways you could build a 2 x two you basically can't build anything more than a 2 x two because if you look any of these numbers always has a zero right so this column has a zero here and this is the only one that has everything so you would just take this column and you would take this column here and that would build a 2 by two right it would be like this and this would give you a 2X two and this is a 1 by zero or sorry uh this is a 3X one which are all smaller than the result so far so these are all zeros so we don't really care about any of those so let's go to the next row so we have four 3 2 one zero okay and now we're going to be able to build some bigger rectangles here so for this first one we can build a 4x1 which is the same but now for the second one now we have a 3X two right so this is going to be six so that's better than what we had before so we have six here then here we have a 2x3 which is six as well and finally here we have a 4X one and let's take a look where we would be able to build a 3X 6 so it would be in the order of this would be column one this or sorry this how would we build a square of uh of area six or rectangle with area six this will be column one this would be column two this be column three and let's take a look and indeed we do have um three things right so we have this and this are these are all ones so anything bigger than a one is just a sequence of ones so these are ow ones so we can just put these three columns together and now we'd have a rectangle there six so notice how sworting immediately gets us like we can keep getting rectangles and we can keep going down and getting them so it's very convenient so let's go for the last one so we have five three two 0 so here we can build a 1x five smaller than a result here we can build a 2x3 same as a result and finally here we could build a 3X two same as ours old so the biggest rectangle we can make here is a three or a six area rectangle and that is indeed the case so there's a bunch of them right there's like this one with this if we put these together there is another one over here I believe right actually I don't think there's one over here is there one over here no oh yeah there's this one over here right so we put these together and so on so these are like our biggest rectangles we can't build anything more than a 3x2 and indeed you can see that like if we try to use these there's nothing else in here because this is zero there's zero here okay so this is the biggest thing we can make and so all we had to do was make a list right of increasing ones and that tells us for a particular cell how many ones are there and then we can use that information to figure out what's the actual area of our rectangle by sorting these in a decreasing order and then from that we could figure out like exactly we're essentially doing a greedy uh greedy area calculation right where we're going to say okay we're going to take the ones with the biggest number first and as we extend out our width we will take smaller and smaller ones and then we'll figure out whatever gives us the biggest area so now we have enough to Cod it up so let's do that so we are going to have a rows and columns it's going to be a length of the Matrix and length of the first row then we're going to have the squares that we're going to calculate all our numbers so we say squares so for the first row we will just copy the first row of the Matrix because every row relies on ones from the above row so we don't want to be out of bound so we could just say like squares equals Matrix zero the first C and then from there we will just initialize everything to zero and then we will Loop through all of these values to actually fill them out so the first row is going to be straight out of the Matrix and the rest of them we'll just initialize to zero and we'll actually Loop through to fill them out so we'll say zero times calls for we don't need this value in range one rows right basically going to get a new row for the rest of it filled with zeros and we'll make a result and we'll set it equal to zero so now we actually have to go through this empty squ and fill it out with our values from our actual list here right we have like this one we got straight out of the Matrix because it is basically stra out of the Matrix right if there's a one in the Matrix there's a one here if there's Zer there's zero here but this we initialize to zero so this we do have to Loop through our code to get it so let's do that so we'll say for Row in range one rows remember row zero Straight Out The Matrix we didn't to do that we need to do the rest for call and range call and basically if it's zero in The Matrix then it's going to be zero in our squares but if it's non zero in The Matrix then we need to add one to the number above it so we'll say if Matrix row call equals one if it's zero we don't need to do anything we'll just leave it at zero then here we need to do squares row all equals the one above it so squares row minus one right that's going to be the row above it and the column is going to be the same we'll just add one now what we have to do is for every single Row in squares we have to sort it in decreasing order and then we have to calculate our areas for every single possible um as we go down right we'll start with the biggest number and then we'll keep going down and it's going to be the length times the width so four row in squares row. sort and we want to sort it in vers and then what we want to do is we want to go through the row and actually calculate the area so 4 I and arrange columns we want to calculate our area and maximize it with a result so we'll say res equals Max the old result and it's going to be the actual value here so remember the value here is the height and then I + one is the width right so and then I + one is the width right so and then I + one is the width right so if we're on like I equals Zer then the width will be one and the height will be the actual value so this is I + one so the actual value so this is I + one so the actual value so this is I + one so now that we maximize our result we can just return that and there you go so it's pretty efficient um so let's go through the time and space for this one so for the time what are we doing so we are creating the squares which is already M byn and then or we call this like row times columns to make it easier so row times columns now we this is also M byn and we are sorting every single row right so we're basically sorting the entire we're sorting uh every row so that would be like let's see for the row it has um C columns right so it would be like how many rows are we sorting we're sorting our rows and then the number of columns would be like R think could be like this R log C something like this right we're doing it R times and then the number of items we're sorting in each row is C so I think it's something like this yeah for every column to sort a column it would be actually I think it would be C no I think yeah I think it would be like this it would be R COG C actually so this term is a basically out of it now right yeah because sort to sort a column it would be n log n so this is basically sorting like if you want to sort like an array of n so every column is C log C and then um yeah we do that our number of times so it's RC log c as our final uh time here where R is rows and C's columns okay and for the space so this is just RC oh yeah this is RC because we did make a new squares array or a new squares Matrix you could do this in place but generally you don't really want to be doing stuff in place um for input unless they tell you to do it so I don't think you can do any better than this so yeah I think it's going to be this and yeah so definitely kind of a weird problem but once you realize that all you need to know is just for every single cell what's the biggest Square I can make with that cell then it becomes a lot more intuitive and so that's going to be all for this one hopefully you liked it and uh if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Largest Submatrix With Rearrangements
|
cat-and-mouse-ii
|
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`.
|
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
|
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
805,949
|
654 |
all right guys so let's talk about maximum binary tree so you are given an array but integer already numbs with no duplicated and a maximum binary tree can be built recursively from nums using the following algorithm so you can actually just know this is pretty standard binary tree so the idea is you find the maximum and you then they're the maximum to be a root and the left side will be the subtree and the right side will be another sub tree so that will be the idea so what i will do is i'm going to create a helper function that will give you my in low in high and i would just call in high okay i'll just call the helper function and array so nums and zero two numbers of lengths minus one and so this will be a recursion case so i definitely need to know which one is my maximum index uh maximum value in the array index so i'm going to say in current max current mass will be equal to low and i would just triverse and i equal to low plus 1 and i less than equal to high and i plus so i would say if nums at current max which is less than the nums at i will just change my index so current max will be i and that would be it so i already know what is my current max the current value inside the array right so i'm going to square three node for root and neutrino nums at current max so that will be my root and i do have a root of f equal to something root of right equal to another something right so that would be a recursion case so for the root of left that is going to be the nums and then definitely i when i know this is my maximum i already know this is my rest of the subtree for the left right so i will say low and then turn max minus one and same idea for the right so i would say current max plus one to the height so that would be it and the base case the base gate because you are keep doing it right so there's a base case for high so if low greater than high then you just return no and that would be it so let's just run this and see do i have everyone now oh yeah i do so i need to return sorry so i just need to return a route and let's see what happens yes i passed test all right that would be good right so let's talk about time and space so for the time you need to traverse every single element in the array right so that will cost all of n for the space you generate a tree node for every single column inside the in the red that would be all of them as well so that would be the solution and standard and pretty easy all right peace out
|
Maximum Binary Tree
|
maximum-binary-tree
|
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm:
1. Create a root node whose value is the maximum value in `nums`.
2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value.
3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value.
Return _the **maximum binary tree** built from_ `nums`.
**Example 1:**
**Input:** nums = \[3,2,1,6,0,5\]
**Output:** \[6,3,5,null,2,0,null,null,1\]
**Explanation:** The recursive calls are as follow:
- The largest value in \[3,2,1,6,0,5\] is 6. Left prefix is \[3,2,1\] and right suffix is \[0,5\].
- The largest value in \[3,2,1\] is 3. Left prefix is \[\] and right suffix is \[2,1\].
- Empty array, so no child.
- The largest value in \[2,1\] is 2. Left prefix is \[\] and right suffix is \[1\].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in \[0,5\] is 5. Left prefix is \[0\] and right suffix is \[\].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** \[3,null,2,null,1\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
* All integers in `nums` are **unique**.
| null |
Array,Divide and Conquer,Stack,Tree,Monotonic Stack,Binary Tree
|
Medium
|
1040
|
1,463 |
welcome let's continue to solve another lead code problem 1463 Cherry pickup two if you've solved Cherry pickup one problem normally this one should be easier for you can just copy and paste the template yeah uh the only difference is that we have two robot number one the number two so the number one will be stting at the top left corner and number two will be studing at the top right corner but for the chry pickup one so one robot is at the top left another is bottom right normally you going to turn the problem into all the robot will be stting at the top left but for this problem it is given to you one is at the top left another is bottom right this going to be much easier than pick up CH pick up one yeah because this person is just standing here another person is just standing here and inside the grid there will be numbers yeah it is starting from zero but there's no obstacles we just need to Tex numbers Yeah so basically this is a DP problem so for uh robot one it will check all the combinations so for example if the robot one start here and the robot two start here and for the next PR so the robot one will check uh just below it and just the diagonal we'll check this one yeah and for robot uh number two it will check this one and it will check this one but it will get the maximum sum of the two yeah if we only take this five if robot one take five robot two take five it is only five but what if robot one take two and robot two take five so that is a seven so we're going to get to the maximum of seven so what is the result from here it is the 3 + is the 3 + is the 3 + 1+ 7 yeah and then we go to the next so 1+ 7 yeah and then we go to the next so 1+ 7 yeah and then we go to the next so if it is a seven it means robot one standing in here robot two standing here and then robot one can choose this one or this one and what about robot two can choose this one and the right one so what going to be the maximum of course the maximum going to be 10 because the robot one will be setting here and robot two will be setting here so it going to be 10 what about the next robot one will choose this two and robot two can either choose this one or this one it's the same so it is three now we need to sum up all of them 4 + 7 11 + 10 + 3 it is up all of them 4 + 7 11 + 10 + 3 it is up all of them 4 + 7 11 + 10 + 3 it is 24 as you can see that basically this is a dynamic programming problem but this is much easier than Cherry pickup one because for Cherry pickup one another robot is here you need to turn this robot to the top left corner and then two robot will be uh working together now we have robot one and two staring at the first row and they will be working together until they went to the last low and we just need to yeah check what is the maximum cies we can pick at each plac and we're going to sum up all of them as you can see this would be much easier um now let's just check some cases so we have rows and columns so this means it is not a square it is a rectangle and those column is 70 and great is 0 to 100 so normally um let's just uh yeah use the same solution as Terry pick up one if you are not familiar with my code please check up my videos for charry pickup one if you understand that video normally for this one you just need to yeah write the code you don't need even to think about it yeah now let me just start coding I'm going to prepare a DFS with memorization so uh with starting point of R1 C1 and R2 C2 yeah I don't know why the color is different this is the strings uh normally I need to use a cast yeah maybe because I click to this one yeah I don't know uh let me just give a pass yeah now let me just continue yeah let me finish the main part of the function and then go to the DFS so I'm going to put R and C it will be the length of the grid and the length of the grid zero and then I'm going to prepare a directions so the directions would be yeah as the directions must be the next low so it going to be 1 - be the next low so it going to be 1 - be the next low so it going to be 1 - one and 1 Z and 1 + one so this is the one and 1 Z and 1 + one so this is the one and 1 Z and 1 + one so this is the directions so finally I just need to return this DFS so the first robot and the second robot with zero and C minus one yeah that is the second robot position now let's just finish the DFS part so we're going to check the column first so if C less than zero or C1 more than equal to say or say 2 similarly less than zero or say two more than equal to C so we're going to return uh minus infinity just as what we did in pick up one um for here we don't need to check rows because rows is just sted from zero to Rus one until it goes to Rus R minus one we're going to return so we need to T if uh R1 equals we don't need to check R2 because they will always be at the same low yeah because each of the time they will always move to the next low uh if R1 equal to Rus one so we're going to U return yeah we need to tack this R1 and C1 if C1 equals to C2 they are at the same column yeah if they at the same column it means they are at the same low they are at the same position and else we need to sum up all of them R1 C1 plus grid R2 and C2 yeah uh yeah we finished the ad cases so this is the ad cases this is the terminal operation it means we went to the last row and then we just need to yeah get the result so we're going to prepare a current position this is just like uh from the beginning uh the current PR would be this yeah it would be grade R1 C1 if they are equal else and would be some of them this is the current PR and then I'm going to prepare a next so this means next I'm going to start in the DFS what is the next uh because finally I'm going to return colum plus since this next yeah so for the next I'm going to Define as a minus infinity you can also Define it as zero because for this problem zero is okay because definitely there will be a number bigger than zero or more than equal to zero yeah that is a different from T Pi up one because s pick up one there's obstacles but for other problem there's no obstacles so we can Define next as negative Infinity or zero now we just needed to check all the Ops so for Dr R1 d r uh dc1 uh in directions for dr2 and dc2 in directions now we're going to check Row one and column one it will be um R1 + Dr R1 and C1 plus dc1 and then I um R1 + Dr R1 and C1 plus dc1 and then I um R1 + Dr R1 and C1 plus dc1 and then I just need to copy to check the second operation the robot of the number two so it going to be row two column two R2 Dr R2 and this one I'm going to say to C2 and dc2 yeah now I need to check the maximum because I want to get to the maximum value next with DFS is going to be Z one column one Z two and column two yeah so this is the entire code now I just need to check if it works hopefully it should be no problem but let's just check uh load two yeah here I have a typo let me just run it yeah as you can see it works now let me submit it to Che if it can pass all the testing cases as you can see past all the testing cases and it's pretty fast but let's analyze the time complexity first before I will optimize the algorithm yeah so now so this is the DFS this is the time complexity and space complexity so the time complexity will be R1 * C1 so the time complexity will be R1 * C1 so the time complexity will be R1 * C1 R2 * C2 basically if it is a 70 for R2 * C2 basically if it is a 70 for R2 * C2 basically if it is a 70 for example we are giving the maximum number 70 yeah it is n to the power of four time 3 * 3 because this one have three time 3 * 3 because this one have three time 3 * 3 because this one have three uh yeah this one is three and another for Loop is three yeah let me go back to the code Editor to calculate what is the result so it is 7 to the^ of 4 * 9 so result so it is 7 to the^ of 4 * 9 so result so it is 7 to the^ of 4 * 9 so this will be the time complexity basically this is a uh 2 * 10 to the basically this is a uh 2 * 10 to the basically this is a uh 2 * 10 to the power of 8 yeah it is the algorithm yeah already this is 2 * 10 the^ of 8 but it already this is 2 * 10 the^ of 8 but it already this is 2 * 10 the^ of 8 but it can still pass normally this cannot pass uh maybe it depended on the testing cases now we can optimize it because R1 should always equal to R2 so this means we can remove this R2 we can decrease the four dimension to three dimension so how can we do that we can just remove this R2 and then we're going to just check R2 so if there is r two we're going to yeah make it to R1 because they are equal let's check if there's other R2 let's make it R1 uh let's check a yeah we're going to change it to R1 yeah let's just check if there's any other R2 there's no R2 but for this zow two we don't need it and here this is zero we don't need it now we turn the four dimension to three dimension let's just check as you can see it works now let me just submit it to check if it works now as you can see it works and it is faster than before because the time complexity changed before it is 2 * 10 complexity changed before it is 2 * 10 complexity changed before it is 2 * 10 the power of 8 now it is 70 to the^ of 3 the power of 8 now it is 70 to the^ of 3 the power of 8 now it is 70 to the^ of 3 * 9 and the time complexity becomes * 9 and the time complexity becomes * 9 and the time complexity becomes three time the 10 to the power of 6 it should be much faster normally this is why yeah now let me go back to T um yeah now let me go back to Tex the record of my subm yeah as you can see we compared first of all we reduced the memory because we turned the problem into three dimensions so the memory is uh space complexity is n to the power of three and the time complexity is n the power of 3 * 9 basically it is n the power of 3 * 9 basically it is n the power of 3 * 9 basically it is n the power of 3 as you can see the time reduced a little bit and the space Also reduced thank you for watching see you next time
|
Cherry Pickup II
|
the-k-weakest-rows-in-a-matrix
|
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100`
|
Sort the matrix row indexes by the number of soldiers and then row indexes.
|
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Easy
| null |
1,816 |
hey guys welcome back to the channel in today's video we're going to look at a lead code problem and the problem's name is truncate sentence in this question we're given a string s which contains a list of words that are separated by a single space each word consists of only lowercase or uppercase english letters there will be no punctuations inside the word a task is to truncate string s such that it contains only first k words and we have to return the string after truncating it so we are given the input s and also we are given an integer k representing the number of words that should be present in the result starting from the beginning in this question the string s contains five words and we have to print the first four words these are the first four words which has been displayed as the output and each word is separated by a single space in this question there are seven words and we have to print the first four words these are the first four words and each word is separated by a single space now let's take a look at the steps we need to follow to solve this question let's start off by creating a variable called length which will store the length of the string as the length of the string s is 5 for this example the second step is to create a string array called words by using the split method on the input string as so this is the input string s and we have to create an array of this string as where we separate each word with a space and the array contains only the words without the spaces so we are creating a string array called words which is initially empty and using the split method on the string s gives us this array so this is what the words array will contain it contains the five words present in the string as now let's declare a string builder sb which will store the result note that you have to return a string as the output so first let's store that result in a string builder and then you can convert it into a string before returning it i created a string builder which is initially empty now we have to create an integer variable called index which is initially zero so index is now equal to zero so this index variable we are going to use inside the words area to access each word present inside the string now the fifth step is to use a while loop which will run for k number of times which means that until k becomes 0 this while loop will run and inside each iteration we have to append onward at a time present inside the words array into the string builder and also append a space whenever you are appending a word so that you get a space inside the result like this first we'll access this word and store it inside the result by appending it and we also append a space so this is what the stringbuilder will contain after the first iteration before starting the next iteration for the while loop increment the index by 1 so that it will point at the next word so that we can access that and append it inside the string builder now index is pointing here so access that word and append it inside the string builder and whenever you're appending a new word append a space now index will be pointing here access that word and append it inside the string builder and add a space next iteration index will be here append it inside the string builder and add a space now for the next iteration k will be equal to 0 because k was initially 4 3 2 1 and for the next word k will become 0 so this while loop will run only till a point where k is greater than 0 the moment k becomes 0 this while loop will terminate so this is what the string builder contains as of now with a space here and index is now 4 and we terminate the while loop as you can see we have the result inside the string builder but we have to return a string so we have to convert the string builder into a string using the two string method so we convert the string builder into a string so now the string contains this string with a space at the end but as you can see in the result you shouldn't be giving a space if you directly return it without trimming the string you'll get a wrong output because you have a white space at the end which you have appended in the last iteration in the while loop so to remove the last white space use the trim method on the string after converting it from a string builder so now the output will contain this without a white space at the end and that is the required output so you can return it so let's code it up i hope you made a note of the steps because we are directly implementing the steps into code line by line so let's start off with the first step of finding the length of the string the second step is to create a words array by using the split method on the input string as so wherever there is a space inside the input string s it will be splitted and added into the words array now we have to declare a string builder which will store the result now the next step is to create an integer variable called index which will be initially pointing at 0 so initialize it with 0. now let's open the while loop and this while loop will run until k becomes 0 so k is not equal to 0 initially k for this example starts with 4 and until it becomes 0 you have to run the while loop now inside the while loop as i mentioned let us append the word at the index position so words of index and also append a white space the next step is to increment the index for accessing the next word in the words array and now we have to decrement k for the next iteration so k starts with 4 for the next iteration it will become 3 and so on until it becomes 0 this will happen now that we have the result inside the string builder after the while loop is terminated let us convert it into a string so sp.2 string so sp.2 string so sp.2 string and also i've mentioned that you have to remove the last space which can be done by using the trim method and you can return this as the output so let's try to run the code there you have it a solution has been accepted as you can see we're getting the expected output let's try for all the test cases are running now let's try to submit the code there you have it a solution has been accepted the time complexity of this approach is of k where k is the integer given to us because this will iterate for k number of times as k is a constant i think you can mention it as of 1 correct me if i'm wrong in the comment section below the space complexity is o of n because you're using array to store the words present inside the input string so that's it guys that's the end of the video thank you for watching and i'll see you in the next
|
Truncate Sentence
|
lowest-common-ancestor-of-a-binary-tree-iv
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces.
|
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,236,1218,1780,1790,1816
|
1,622 |
hey what's up guys this is john here again so uh so let's take a look at uh the last problem of this week's bi-weekly contest bi-weekly contest bi-weekly contest which is number 1622 fancy sequence so this one is like a design type problem you know i figured it's a pretty it's pretty nice problem okay so you're given like an api uh interface like and they ask you to implement several functions so the first one is the append right so appends an integer value to the end of the sequence so this one is pretty straightforward okay and the second one is like add r so this one says increment all existing values in the sequence by an integer increment so with this one means if you have two sequence numbers in the current list uh so this one supposed to increment everything that's in the list let's see if we increase two so this two will become like four and five okay so that's what this one does similar for the multiple r here basically this one it's like just a instead of increase it is multiply that so okay and then the last one is the get index uh to get indexing stream here so basically this one just simply returned the uh the this index the number on this index right after this kind of like adds or multiply uh operation okay and if the index is greater or equal than the length of the sequence return minus one so this is like just a minor case okay and then yeah it's give you a bunch of like uh a bunch of examples you know i mean the concept or the uh the general idea for this all four problems all four like uh functions it's pretty straightforward right the hard part is this basically you know the other constraints here so first the total numbers of the index could be uh 10 to the power of five and this one is here like the uh they're like uh in total like 10 to the power of five cos uh for all the append add multi r and the under get index okay so what this system means it means that if you follow that you get the what the problem is described to you for every time when you call like a all or multiply out here basically you do like a o and o in operations right so basically you update all the numbers in the current list okay so with that we have a total number of uh in cost so basically the time complexity for that naive implementation will be enough of n square with given this kind of 10 to the power of five constraints it will definitely tle right so the heart the difficulty for this problem is that how can you find a better solution right so um okay so a better solution is that it's this right so if we can i mean of course first we still need to we still need like a place to store our card numbers right so we need a list for that so that's for sure and so this part basically so this one tells us for the add r and the multi r here we cannot loop through the element right and if we cannot loop through the element what can we do we have to find a one uh solution instead of on solution okay so how can we find our o1 solution right um let's uh you know let's try a few examples here right i mean you know i think for the purpose of the proof concept you know let's forget about the multiply all here let's only consider this at all because i figure out uh every time we have like different like criterions here or conditions we can just try to use one of them and to make this problem simpler and to see if we can find like a pattern of it and then we can add the second conditions on top of that okay so let's say we have a you know we have a number here right so we have a number like two here so we have a number two here and the uh so we have a number two here and then on top of two we add we do add on top of two which means the two will become two to four okay and then later on uh we add the uh we add another number three here right the second option is like add uh the sec uh three into this list okay and from there onward right let's say we also do a add two okay so here we also add two three will become to five right uh i actually know what so i think this is a bad example so sorry about that so let's do this okay let's say we have a we have number two here let's say we do a two we so the first time we do a plus two right and then next time we do a times three and then we plus four and then we do an another like time times five so let's say we have like this kind of sequence of the uh yeah of the uh the operations right so as you guys can see here so and what do we have here we have 2 times what 2 times 3 times 5 right plus what plus the uh plus two times three plus four times five okay right so we have basically we have two parts and the first part is the how many multi multiplier we have get so far in this case we got in total 15 so which means that i mean in the end the we need to do we need to use the original numbers which is number two here to multiply by this 15 okay that's the first part right and second part is the what second part is the how many it's basically it's basic how many uh numbers we have increased so far right from both the plus two times three plus 4 and time times 5 that's how many numbers we need to increase right so basically we use 2 times 3 plus 4 and time times 5 and these two parts will give us the final answer right okay so that's that and let's assume uh each of these operations happens after adding a new number okay so what does it mean it means that okay so let's say the first number is two right so the first number is two and then so we which means we need to keep like uh a total increase of each of the at each of the index here right so at the beginning right so we do add two here so we have a basically we need to have a like add a list here okay if we are only considering the ad here right so at two here we add two so it means that the total basically this ad list is kind of like a accumulated ad we have we will ever have so far right so let's say we have a number two here and then we add two right and then let's say the this is like the numbers so let's say the next number is three okay so the next number is three let's say we also do a plot plus two here so now we have the total plus we ever have is four right and let's say uh the next one is four we also do a plus two okay now the total class we have is six so on so forth so right say we have five and then the class is eight okay let's assuming we only did the add operations without the matr operation okay so basically at each of this of these locations here we do a add-on do a add-on do a add-on okay right we do add r here and in total right in total we have eight and now let's say uh i want to calculate the uh the index um let's say we want to get the index get index of 2 here so we which means that i want us i want to get the total uh the current value for this number okay so what's going to be the number here right so for the number four here how many ad do we have so far we have uh we add two to become six and at five we also have a have added two here so which means that the uh the get index of two should be uh should equal to four sorry so equals to 4 plus 4 which is 8 right because 4 is the number itself and the number 4 here is the uh is a difference right it's the difference between the uh so how many numbers we have increased starting from four to eight okay so that's that so what's gonna so what's that value basically as you guys can see here the value for that is basically it's gonna be the eight minus that's the uh that's where this number this 4 number 4 is coming from so which means we have to use like this add right so add -1 add right so add -1 add right so add -1 divide minus the what the basically the add of the uh of the index this index uh -1 right so that's that uh -1 right so that's that uh -1 right so that's going to be the formula for that right i mean and yeah and that's only to consider the uh the add part right so and you if you're adding the multi all parts intonate so this one will become like more complicated so uh so this thing will become to what so let's say at this po at this location right i mean after adding this one so that's a current total here right if we have like uh do a multiply by two here right so we have like a 12 here right so this one becomes 12. i mean uh no matter how we are calculating this uh if no matter if we're doing a like add or multiply here i mean the increment number uh we can always keep it uh in this ad in this add like uh array here basically every time if we do a like if the operation is at all we simply add it to the last to the current location if it is a multiplier we also might multiply it by the current location right so that uh regardless of the add or multiply you know just for example just like this right so the total increment uh at the previous operation is this it's basically six plus four is ten right so now we have a five here which means that we the current one should become to ten times five right that's going to be the total incremental value for this current location that's how we uh keep this like add right uh with both the add-on and add right uh with both the add-on and add right uh with both the add-on and the ma and the material operation here okay so that's how we keep this add and uh now we have this part right so how about these 15 parts how should we calculate keep like this 15 so that we can finish the first part right this one i think which uh it's easier we can simply like introduce like another array here basically every time when we have like this multi r here with simply uh do a multiplier we multiply on top of that so that you know later on we can just use the uh that multiply to get to give us the uh the 15 here right and okay i think i have talked a lot so let me try to code this part so that i we can have a better understanding okay so we have a self uh ad right so this one uh let's make it like increment okay increment self multiply right if you guys do remember you know the operations the formula we have here is the uh the add right so the uh basically is the uh self dot uh increment right the uh the minus one right and minus self dot increment uh index minus one okay right i mean if this index is zero based so we'll have like an issue here right so i think the uh a small trick here is that we can just uh pad this array uh by one so that this index minus one even though the index is equal to zero uh it will still be within the range right yeah because you know if we have like let's say you for example if we uh initialize th this like two arrays with kind of like this one right we pad it by adding like the initial like a dummy numbers or like a anchor numbers here then later on here right when we do this calculations here instead of index minus one here we can simply use index here because we have already increased the numbers of the of this array here so that you know this index minus one will just becomes the index so that's the basically a small trick to handle this like a zero index case okay so and after that right like i said you know the uh we have the numbers uh every time we append the numbers right we have a dot append the values right so that's the first step and how about the second step right i mean these things here right i mean basically since we're keeping this like the uh we're accumulating this add number right this like increment arrays here so that we can we have to carry it over from the previously uh place basically we have to do a increment okay we need to increment -1 that's going to we need to increment -1 that's going to we need to increment -1 that's going to be our initial state right same thing for the multiply here right because we'll be using those uh because we have to initialize this like values at each of the locations so that later on we can just use the values otherwise this place will become a w will like be a zero or yeah it will be a zero number which is invalid right so multi minus one so that's how we uh inherits carry over the numbers from the previously state now the uh so we have a when we do the add here we simply uh add this one to the at the last one of the uh of this increment array here that's how we increment it right and same thing for the increment uh when we do the multiplication right so it's same thing with this amp here that's how we keep maintaining the how many numbers we have been increased so far right so that's that yeah i mean so later on you know okay so that's that i mean and how about this part right so we have also need to increment this part right so we just need to do a multiply uh minus one right times m right so that's good will give us the uh the how many uh multiplier right we will be get we will need for the final answer right so that's the second part and this part is just to update the uh the in the incremental of the numbers right so this is to update the multiplier right and now finally for the get index here so first we have to check if the index is greater than the uh than the length of the self numbers right so that's if that's the case we simply return minus one otherwise right otherwise i mean we have increment right so what's going to be in the increment like i said the increment is the uh stuff of the increment minus one that's going to be the current increment so far right minus the increment of the of this index right of the index that basically this will give us the range basically how many numbers we have how many increments we have so far right from the uh from this index to the end uh to the current time right and that will give us the uh let's say we have x here x plus two times three plus four and time times five right so and this part is the what so this thing will become x times uh 15 right plus uh 2 times 3 plus 4 times 5 right so we have two sections of this so and this one is this part right because we have keep updating this one and if we do a like this is a kind of like a presump right like a pre-sum of presump right like a pre-sum of presump right like a pre-sum of you know we have a to get a pre-sum you know we have a to get a pre-sum you know we have a to get a pre-sum we just need to get the uh the end minus the beginning right so that's the presump now it's this part right so the only thing we need the only thing left is how we just need to get the 15 here so to get 15 we simply do this right so we have a multi player right equals to what self dot the uh the multi the minus one still the minus one divided by the self of the uh of the index you know that's why we initialize this multiplier this one here because if we're getting the index of zero right so here will be zero and we do the multiply here so that's why we have to set this to one instead of zero okay so that's we have the multiplier here now we have everything we need we can simply we could now we can return our result here so the result will be what will be the uh the numbers first right so the number is the uh let's see so the number is it's just the uh this one here so we have self numbers right the index so we i mean we can use index right so here keep in mind here we didn't pass these numbers here right so that's why we can just index it's just the numbers we need okay now we have a times the multiplier right multiplier that's what how we get this 15 here right remember the 15 here is we this uh it's supposed to be also like index minus one since we're also we're all we also pass this thing with one here that's why we can use the index itself plus increment right so that's the two parts we have here and then we simply just do a mod okay yep yeah i think that's everything we can run the code here oops oh sorry okay this thing here oh there's a there's an issue here let's see which part is wrong here so we have an increment multiply we have a hat this part seems all right this things use the probably this part i think first is this right so i mean we have to do a index equal or greater than this but i think that's not the cost for the for our issue so we have like one increment is i think there's an issue here you know it's this part basically you know uh so when we're talking about this increment here right so we if we're only doing this we're only considering the uh the add case without this multiplier case you know so for this part we have to do this i mean times that this will give us the correct increment from this index to the last increment value why is that you know so here's why okay let's say we have a and we have a 2 right so we have a 2 3 4 and five so this is the numbers so this is a number okay and let's say at the two here we do a plot plus two okay so the total uh the plus is two here right so this is the increment two and let's say at the three here so this is the with the three new numbers here we do up we do what times three so now this total increment becomes six right so let's see at four here we do a plot a plus four here now the total increment is what six plus ten and six plus four is ten okay and here at the five here let's do it let's say we do a times five so the total increment is what is 50. okay and if we're getting this numbers for this index uh two here so what's the uh what's the correct number of this so let's say so for four right four times what four times basically no sorry four we first we do a plus four right we do a plus four and then we type times five okay so by using our formula right so this thing transformed to four times five plus one plus four times five okay so this part we already have right so that's the multiplier here right that's i mean which is five but how about this part as you guys can see here so the actual increment is 20 okay but if we are simply using this formula right sorry not this formula if we're simply using this formula without this part so what values do we have uh we have 50 right 50 minus 6 will be 46. afford will be 44 right which is not correct so why is that so this is because the you know when we multiply 5 right we're not only multiplying the five of this current four here we're also multiplying the five uh with the previously accumulated result okay so which means that as you guys can see here so to multiply five we have a previously six right we have a six times five and then we have like with the current four right the four times five so the total this is 50. but actually what we need here is the we only need th this four times five right so what does it mean it means that we have to remove uh subtract this uh the increment that's accumulated by the previously uh accumulated in increments right so in this case it's the uh is this one is the six times five right that's why we need to multiply the five minus the previously uh result and multiply by the uh by the current by this like the multiplier within this range so that we can get the correct increment okay cool so i think this time should be okay yeah okay so this one accept it let's try to run the code so it's also accepted all right so now as you guys can see here so the time complexity for this thing is you know all the append add multiply r and even the get index it's only uh o of one time right so it's a constant time so now the time complexity is the just like the o of n right the total yeah i think that's it i mean it's a i think it's interesting it's more like a math problem i think yeah it's more like a math problem plus a design but i think it's good it's a very good practice at least i like it all right cool guys i think that's it thank you so much uh for watching this video guys stay tuned uh see you guys soon bye
|
Fancy Sequence
|
max-value-of-equation
|
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.
Implement the `Fancy` class:
* `Fancy()` Initializes the object with an empty sequence.
* `void append(val)` Appends an integer `val` to the end of the sequence.
* `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`.
* `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`.
* `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`.
**Example 1:**
**Input**
\[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\]
\[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\]
**Output**
\[null, null, null, null, null, 10, null, null, null, 26, 34, 20\]
**Explanation**
Fancy fancy = new Fancy();
fancy.append(2); // fancy sequence: \[2\]
fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\]
fancy.append(7); // fancy sequence: \[5, 7\]
fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\]
fancy.getIndex(0); // return 10
fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\]
fancy.append(10); // fancy sequence: \[13, 17, 10\]
fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\]
fancy.getIndex(0); // return 26
fancy.getIndex(1); // return 34
fancy.getIndex(2); // return 20
**Constraints:**
* `1 <= val, inc, m <= 100`
* `0 <= idx <= 105`
* At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
|
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
2036
|
841 |
in this video i will show you how to solve keys and rooms from lead code so the question says there are n rooms labeled from 0 2 and -1 and all the rooms are locked except -1 and all the rooms are locked except -1 and all the rooms are locked except for room 0. your goal is to visit all the rooms however you cannot enter a locked room without having its ski given an array rooms where room eyes a set of keys that if you can visit all the rooms or falls otherwise i think this question is quite straightforward but the solution is not so straightforward so let's look at the example at here you're at index zero here you're at index one here you're at index two and here you're at index three so as it says in the question room zero is unlocked so when you're at room zero you get the key to unlock the room which is index one and then when you're at 2 you get the keys to unlock the room at index 2. so this here says you got the key for the room at index 1 and here you got the key for index 2 and here you got the index for three but three is unlocked anyways so when you visit a room you may find a set of distinct keys in it each ski has a number on it donating which room it unlocks and you can take all of them with you to unlock all the other rooms so this part seems more relevant to the second example right here so when you're at here let's label this again room zero room one room two room three so when you're at room zero you're able to unlock room number one and you're able to unlock room number three but you're not able to unlock rule number two because even when you go to room number one you're able to unlock one which is the one you're at well zero is unlocked anyway so it doesn't matter and then unlock room number three so two is unlockable and therefore it's false and again here it's also relevant for example too given an array rooms where room's eye is the set of keys that you can obtain if you visited room i which in this case is the index return true if you can visit all the rooms and falls otherwise okay let's see how we can solve this well i can start off by creating a stack and saying this stack is contains zero because i'm able to unlock room zero it's open so then i can just assume oh well i have the keys and then what i can do is create a set and in this set i will say here are for example scene or i can say the scene rooms or the keys doesn't matter and this set will take in the stack so that let's say when i'm here and i have one and three and i move to the next room and then i have three again i do not append it because if i do i just want to keep a record of all the unique keys in there the distinct keys there is no point of re-adding zero there is no point of re-adding zero there is no point of re-adding zero re-adding one and re-adding three re-adding one and re-adding three re-adding one and re-adding three so i can now loop through my stack so i can say while stack pop me the value in there so my stack ascii 0 i pop the value right here so here i'm going to have 0 so let's start to this example right here so i have 1 2 3 and i've not done anything yet i just have an index of 0 to start with and i beg the question for j in rooms idx so i'm going to start with the first room so this 0 is going to go right here i can say i have a mistake already and it will be room so it's going to get me 1. it's going to get the value 1 out of here so for j in rooms idx in this case it's one but hey why did you use a for loop because just in case they were two or more then you get three zero one if this j is not in c so if this one here is not stored in my scene rooms then i want you to oh sorry i want you to append this j to my stack so hey i've not seen this key before so now you're gonna add this key one into your stack right and you want to add this to your scene rooms so let me just copy paste this so it's faster okay so what i've done right here is trying to make sure that i am appending the keys as i go along so in the next loop there will be two in it and then two is gonna go in here to get us number three and then it will append it to the stack and added to the scene rooms which you can see i've also there so if jay is not in the scene rooms to as follows and at the end what i can do is i can compare the length of the scene rooms with the actual length of the rooms so in this case here i'm gonna have three and every time i visit a room i'm gonna also have three so in this case it will return true because the equal the number of rooms is equal to the equal amount of scene rooms now let's see this code in action for the other example so let's take this example down here so in the first iteration it will be one and three as you can see right here we have one and three it's gonna append one to the sorry it's gonna pin j to the stack so this will be one and it's gonna add to my scene rooms so this will be one and then it's also gonna do the same thing for three and then in the next iteration it's gonna substitute the idx one here so then it will get this whole number here which is three zero and one so it's gonna check hey i already got three nothing to do here um i already got zero so nothing to do here because you have already zero and three from the previous iteration and one oh i got one too so nothing to do here so the length of the scene room is still one does that make sense and then it's gonna take it's gonna pop the next value which is three and it's gonna take a look at three and it's gonna say wait a second i already got zero so nothing to do here so when you look at the scene rooms it will include three which is zero one and two so it will include zero sorry zero one and three while the actual length of this list is four and the scene rooms is three so therefore this is not equal and it will return false if the first one were to had one two and three and it already has zero then this would have been four and then it would have been true please let me know if you have any questions regarding this thanks for watching
|
Keys and Rooms
|
shortest-distance-to-a-character
|
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_.
**Example 1:**
**Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\]
**Output:** true
**Explanation:**
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
**Example 2:**
**Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\]
**Output:** false
**Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room.
**Constraints:**
* `n == rooms.length`
* `2 <= n <= 1000`
* `0 <= rooms[i].length <= 1000`
* `1 <= sum(rooms[i].length) <= 3000`
* `0 <= rooms[i][j] < n`
* All the values of `rooms[i]` are **unique**.
| null |
Array,Two Pointers,String
|
Easy
| null |
784 |
welcome to february's leeco challenge today's problem is letter case permutation given a string s we can transform every letter individually to be lowercase or uppercase to create another string return a list of all possible strings we could create you could return the output in any order so we had string a1 b2 we can see that these four strings are going to be the different combinations that we can make when we make a and b uppercase and lowercase so how can we solve this well we can certainly try to do it recursively uh but i'm going to try to solve it iteratively instead say we have the string a b c what are all possible combinations here if we start with a we know that we could either have a or a right that's obvious now what about b if we add b to here well we have to add b to both of these and also have one down here like this have capital b's like that and if we want to do for c we'd have to add basically c's to all these and c's to all these here so you can kind of see a pattern here that's forming as we build up our string each one of them is kind of like exponentially making more possible combinations like it's kind of 2xing exponentially every time the only exception to that if there's numbers if there's like numbers one then the only combination is this one here right so we can definitely write an algorithm to take care of this we'd have to build up our string every time store it somewhere temporarily and then add it to that the if we have a character we can add a lowercase and an uppercase and if it's a letter we can only add it just once so i'll show you what i mean let's start by initializing our output which is just going to be an empty list but we're going to have a string here so that we could for loop through it so let's see four uh what's called s well i'll call it characters c and s what do we want to do well it depends right is this character a character or is it a is it like numeric luckily there's functions in python where we can check for that we can say if c is alpha which means it's alphanumeric or i'm sorry alphabetic then we will need to add to every single one of our outputs both whatever's in here lowercase and uppercase so what i'm going to do is actually create a empty list called temp and we'll say 4 o in output what do we want to add to our temp the o plus o lower as well as o not o i'm sorry o plus o um is that right i'm sorry o plus c lower like this as well as upper here now if it's not numeric then we will just add well we have to add every single output still but we're only going to add just whatever c is and we assume that's numeric maybe it's some sort of symbol i don't know so once we do that we fill up our temp with um building upon what's in our output and what we'll have to do is clear our output and make it whatever is equal to temp now and luckily we can just go through our loop and finally we turn our output at the very end so if we look at what's going on here uh it should return to us the different combinations we don't care about order luckily here the order seems to be the same but it doesn't matter whether the order is the same or not so let's go and submit that and there we go accepted uh what is this time complexity wise oh gosh um assuming that we're looking at n i believe it's n squared might be actually might be exponential it might be n to the ah is it n squared i'm sorry i'm actually not sure here but i'm pretty sure it's exponential because we're building each time so it'd be like n to the nth power i'm not sure i should probably look that up but hopefully this helps and yeah thanks for watching my channel and remember do not trust me i know nothing
|
Letter Case Permutation
|
insert-into-a-binary-search-tree
|
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string.
Return _a list of all possible strings we could create_. Return the output in **any order**.
**Example 1:**
**Input:** s = "a1b2 "
**Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\]
**Example 2:**
**Input:** s = "3z4 "
**Output:** \[ "3z4 ", "3Z4 "\]
**Constraints:**
* `1 <= s.length <= 12`
* `s` consists of lowercase English letters, uppercase English letters, and digits.
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
783
|
65 |
thank you morning YouTubers so here it's about 8 A.M at your place it might be like 2 A.M A.M at your place it might be like 2 A.M A.M at your place it might be like 2 A.M and you're facing this difficult issue and you just want to get out of the office what are you doing in the office at 2 am anyway um this video will try and help you out technically I hope you subscribe to my channel and that you liked the video that will really help me and my family out God bless thank you foreign foreign foreign foreign thank you please click subscribe and like thank you for watching and may God bless you always
|
Valid Number
|
valid-number
|
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the following formats:
1. One or more digits, followed by a dot `'.'`.
2. One or more digits, followed by a dot `'.'`, followed by one or more digits.
3. A dot `'.'`, followed by one or more digits.
An **integer** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One or more digits.
For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.
Given a string `s`, return `true` _if_ `s` _is a **valid number**_.
**Example 1:**
**Input:** s = "0 "
**Output:** true
**Example 2:**
**Input:** s = "e "
**Output:** false
**Example 3:**
**Input:** s = ". "
**Output:** false
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
| null |
String
|
Hard
|
8
|
795 |
Scientist Dr Hello Hi Guys And How Are You I Am Positive In Good Saunf Ballu Number Of Resident Maximum Kar 119 To Send A Deep Into The Behavior When They Are And Have Left Bhavnagar Oil Bond We Have To Return The Number Of Continuous And Not S Well a survey research labs maximum element in there is at least left most right date means difficult directly relative volume maximum are elements to do it is please pay attention to elementary middle east the left and most right means the measurement that should be one thing great Din left and lose no request to right Sudheesh condition involved in hair soft you will consider this simple to three four in the tower the left and right to and 40 can see the maximum age limit for and married into electronic and request to 406 420 500 index Bhi to find the number of and subscribe you take the example distic example for this is the way are two three four one two have the number subscribe kar sunao kal subah mil doob hair hai tu kamaal thi kamar lipstick siddh example fennel sexual show and pleasure -Features Direct B's scope Kuch Bittu 123 people to 234 because of tourism element and tail lies between them and throw to three 500 kar david ek 2345 to 1000 k not get back soon s you can also take three ok ok ok i 535 can not in a position to bank se miss you can take off s you can take four 2525 respectively 60 interface m yes sorry 523 1965 you can take trained you can attack similar difficult 10 from this issue will consider to take two less and 5551 two digits in this is better than solid is video can not increase sin yadav and so you have to start that from here consider 2012 consider when you are you have to take out a new rate it is the no from where you Hey Veri Bigg Boss's Bigg Boss You Kannout Kansive, but the limit from he is the darkness of Steve Davis Ki Bay Eding Annie Previous Elements You Can Not Make Ai ₹ 1 and Order you have to take you Have to ₹ 1 and Order you have to take you Have to ₹ 1 and Order you have to take you Have to consider you have considered as like it when you are so in this to 16 2010 this is possible through to laborers' money that police is possible but zero not possible so you have protection more to subscribe 200 so because of this metal has reached to for innovative Manner to interact pose you have a first you will fight back to ask to increase the 512 you have to calculate the size of the subscribe to is but on this urine issue that this you will move late sweet i daily discount bittu ka machine ka photo in Famous 60 seconds possible self show hair to calculate saudi se window-eyes a plus ok officer ok mehak's wedding attend and can put on earning now suhag calculate the total number of possible morning is 36 and wipro 6 that i will give one example this Small Example Which Is Which Makes Your Word Is Concept Clear How Let's Check Welcome To My AB To Calculate The All The Best Wishes Menu Saver In Them Into R Ma Pa Dh Ni Sa Ki Salman Khan To Come Aakhri Din To Kamar Aur Tu Where was the day 300 this is possible saver is this is for forty verses 151 food ₹3 this is for forty verses 151 food ₹3 this is for forty verses 151 food ₹3 ok time se 60 lakh liquid you can quickly and properly Delhi subscribe Video to that you will take a variable table spoon when you will point 2 and you will and YOU HAVE TO TAKE A PUNE RESULT SUBSCRIBE BUTTON TOO KAR DO HUKHA HAI BUT FUEL MOVE TO SEE THE NEW TO MIXI IN VANDE KRISHNAM 2ND YEAR TO ADD RESULT PLEASE SUBSCRIBE 398 THIS POINT FIVE VIDEOS BECAME THIS TOP SUBSCRIBE FOR LIVE VIDEOS THAT HANDS FREE Popular Web Stores Such In This Research That 9th Possible To 0.1 Aghi Nai How To Come As Nice That 9th Possible To 0.1 Aghi Nai How To Come As Nice That 9th Possible To 0.1 Aghi Nai How To Come As Nice Entry New Basic Bike Toward EU Subscribe To My Channel Subscribe Quality Improvement Subscribe 560 Videos That Bigg Boss Exit Point At This Point Yo Window IS No Any Previous Story Element Is 153 Like This Point Se Your New Window Size Atishay Dahej Pe Subscribe Button In This Possible Subscribe To That Instinct You Can See A Good Way Exam Place Example Is Yacht Is One Two Three 40 A Pipe 6 7 8 Fancy This Chain Is Country Ko Facebook December 30 2010 President Meghraj But You Will Update You Can't You Ca n't Make Any The Amazing Subscribe Our Video Size That Aisi Rojgar Par Consider And Vikas Hai That Skip Like And But You Friends Our Surya Recent All The Thing And That To Calculate The Same Manner On Hai But Titback Like It Is 108 Via In This Case It Left Side 10051 250 G K 125 Samay A Suicide Attack Hua Hai 1000 Like Kumbh Ka Machine To Kamakhya One And Never Left Side It Into this now you are so situated of one so in this case you have considered as the can not be possible case to throw ke notification beautiful cosmetic skin bittu main tu kya machine ki thi how to hai tu ko fish building good ok i one how To Less Economic Gesture To A P Give Mobile Vote 142 And Anshu S Well S 123 In 123 45678910 To Increase 923 123 21 I One To Three Locations On Teachers Appointment Cases 119 Crystalline Sequence Amway This To Calculate The Same In English Hairstyles To The Giver To Story 2004 Medium To Na Ho This White Window System 231 Countries In The Country That A Nine Discus Is Vikram The One That Is Vikram One So I Can Attack On Hai But You Can Take It Is Anomaly Vibrations Request U in three re-entry Vibrations Request U in three re-entry Vibrations Request U in three re-entry basis but if you will take to 70 you can you extend this application watch your questions2 machine this section add 2 spoons of ghee to commercial number 151 slow distribution and it's possible am anil kapoor extend 3031 a ajay to tomorrow morning office of possible business share the best wishes till day till 1232 0 a message case 123 ludhiya 3131 sudhir 6 player 16 302 323 231 123 li vansh which vansh 300 total 5010a 200 in this Case Yo Festival Window Size In This Is What You Ya Yovan You Can He Be One Of The Mission The Best Remedies To Do Subscribe 4,320 Setting On 111 Training Wali 212 Want To Three Vansh 12367 Dhish Aadat Tours And Travels Patient Size Surya Flats And it is also working in your personal life in lemon and width classification of elements which subscribe and subscribe the Channel subscribe to do Anything 3 A Two and Three and Sudhir and is so sweet note you can extend 2323 descendants 310 efficient hair 2012 how to do this Late And 120 Body Vacancy Here Peer Victory In English Newspaper Industry Also For This 2ed The Previously Calculator Free Specific 232 This Is Not Possible That Now Enter S3 Plus 362 609 Sure 323 324 323 506 subscribe to 98 That In English Black 1023 How To S2 is 80 but extends 110 m to syrup middle love middling android os android window size two three ok okay do n't choose content vitamin c committees also present that I have this belt tight all the others but in the draw in the - E Commented on Sunday December 21 draw in the - E Commented on Sunday December 21 draw in the - E Commented on Sunday December 21 2008 251 How To Can Share Through To Mode Off Andrew's Fish Strengthening Serum Porn Can See Cinnamon Element And Three For Window 7 Plus Srivastava window-eyes Window 7 Plus Srivastava window-eyes Window 7 Plus Srivastava window-eyes Painters 0.5 Inch 11 Painters 0.5 Inch 11 Painters 0.5 Inch 11 2013 So You 04 Nov 30 Gram Subscribe To How To Do 1729 12323 Do To Please Atithi To Om Shanti Tu 121 Ok 9o Ki 900 Cancer 2323 Dos Video Jatin Adhat Shyam Hai Tu Kamal Sudhish 257 Newly Appointed To Suggest Lines Which Can See This Player Is Point And Elements Which Electronic Left subscribe width body what is this subscribe kar lu e saiya tu jis calculator window size video side mein left - part plus one ok n and video side mein left - part plus one ok n and video side mein left - part plus one ok n and decisions of cases where we calculate the number four our difficult series we can calculate the number of this Is Subscribe Our Subscribe 20 Celebs Ke subscribe this Video subscribe And subscribe The Amazing Subscribe Button Click Asli Ruchi Development And Pimple 10th Window And What Does Not Mean That Video then subscribe to the Page if you liked The Video subscribe Play List Send Art This Test All Things Pages in the App to Calculate the Best Student Nurses Gather Wide Number of Jobs for Pyun This Video Subscribe to That
|
Number of Subarrays with Bounded Maximum
|
k-th-symbol-in-grammar
|
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,1,4,3\], left = 2, right = 3
**Output:** 3
**Explanation:** There are three subarrays that meet the requirements: \[2\], \[2, 1\], \[3\].
**Example 2:**
**Input:** nums = \[2,9,2,5,6\], left = 2, right = 8
**Output:** 7
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= left <= right <= 109`
|
Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
|
Math,Bit Manipulation,Recursion
|
Medium
| null |
353 |
okay so lead code practice question design snake game so in this video i'm going to introduce the solution for this specific question and i'm also going to go through uh the general procedure we should follow in a real code interview so let's get started so remember the first step in the ryokoni interview is try to understand the question ask proper questions to clarify the ambiguous part and also at the same time think about some edge cases so let's reach through this problem design a snake game that is played on the device which with the screen size as height times wise so play the game online if you're not familiar with the game so the snake is initially positioned at the top left corner with a length of one unit and you're given an array of the foot in and is a row and the column position of a piece of wood the snake can eat so when the snake eats a piece of wood it's lunch and the games are both increased by one so each piece of the foot appears one by one on the screen meaning the second piece of the foot would not appear until the snake eats the first piece of the foot so when the piece of the foot appears on the screen it is guaranteed that it will not appear on the block occupied by the snake okay so the foot will not appear on the body of the thing so the game is over if the snake goes out of the bone or if it is hard if it had occupied a space that is body occupies after moving okay so implement this snake game class um so this one it is a constructor and then this is a move function so the move function will return the score the game after applying one direction move by the snake if the game is over then we will return minus one so let's see this uh first of all the snake move to the right by one then down by one and then uh to the right uh and then the lens uh the lens of the snake increased by one and now so now the score is one we are going to return one so on and so forth so how to do this problem the next step is about finding idea how to solve this problem and do some space runtime analysis and discuss with the interviewer to get an agreement before proceeding to the next coding step so we have so i will go through the solution and at the same time go through this piece of code to explain how it works so we have first of all we define the so we use we define the queue we define two things uh for the body and one cube for the food and then we have a uh a integer which record how many of the food units have been eaten so the wise the hat the body defined as a set which is the corresponding units occupied by the body and the body q so this q is uh so the head is the last element and the tail is the first element so it's like every time we try to move uh we try to remove the first thing which is the tail and we add one unit into the body queue to the last and then the foot cue is uh we just put the first um in the constructor one by one into the foot queue so let's take a look at the uh the constructor so first of all we will initialize the west as west minus one which is for easier computation this is about like defining the boundary actually for this game and the foot heat we initialize at zero and then we have the body and the body cue initialized whereas the initial position which is a upper left corner to be inserted into body and body cue for the foot we just go through every other foot and inserts each of the position into the foot queue so that's pretty much about the constructor so let's see the next one so the move api so for the move api we are going to get the current position the current hat position which is the last element uh in the body queue and based on the direction it is moving you compute the next position the hat is going to it's going to be located so this one it is a helper function if it is upper then and then we minus the row if it is dot button if it is down then we plus the row if it's left we minus the column if it's right then we plus the column so pretty straightforward and after the move we have the next position so if the and then we define another helper function which is snake thigh to see if at the next position snake the snake will die so for we pass in the next position as a parameter into this helper function the column and the row uh the row and the column so if the row or column out of the boundary then we are going to say okay the snake is going to die otherwise we will see if the next position so if the next position equals to uh the it's not so if this the next position is equal to the tail it is okay uh because that is because essentially um essentially if this the snake disappear sorry the tail of the snake disappear then the next position is the original tail that's okay it is not going to die uh but if it is not the if the next position is not the tail and also at the same time the unit is occupied by the body then the next position is going to be somewhere in the middle of the body of the snake will die so this is a snake dye function and then um so uh the next one which is uh to see if the food so if there's still any food in the food cue and also if um uh if the so if there's still some food in the queue and also the foot doesn't uh fall into any of the units occupied by the body um and the next position is uh the foot in the queue in the first position uh i mean the neck the top position of the foot in the queue which means that if we move to that direction we are going to eat one unit of the foot then we are going to just uh extend the bot the body queue because we either eat one unit of food we need to extend our body lungs by one and we update our body sets and also we pull the foot in it from the keel then we plus both the foot eat and then we return the food eat so otherwise it means next position is not a food unit so we are going to uh we are going to just remove the tail which is the last one and at the same time remove the unit occupied by the tail from the body and then we are going to add the next position into the queue and also at the next position into the body to update uh the units occupied by the snake and then we return the foot eat so essentially you can see the algorithm uses a set for a quicker lookup and we use a cue body key and the foot keel for the movement of the snake and also for the consumption of the foot so for each of the operation the runtime is going to be constant like for the constructor of course it is constant for the move it is also going to be constant just in qdk operation which is which are our all one operation so that's it for this uh question um so don't forget to do some testing after you're done with coding uh if you have any question about the solution or about the coding whatever feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Design Snake Game
|
design-snake-game
|
Design a [Snake game](https://en.wikipedia.org/wiki/Snake_(video_game)) that is played on a device with screen size `height x width`. [Play the game online](http://patorjk.com/games/snake/) if you are not familiar with the game.
The snake is initially positioned at the top left corner `(0, 0)` with a length of `1` unit.
You are given an array `food` where `food[i] = (ri, ci)` is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game's score both increase by `1`.
Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.
When a piece of food appears on the screen, it is **guaranteed** that it will not appear on a block occupied by the snake.
The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies **after** moving (i.e. a snake of length 4 cannot run into itself).
Implement the `SnakeGame` class:
* `SnakeGame(int width, int height, int[][] food)` Initializes the object with a screen of size `height x width` and the positions of the `food`.
* `int move(String direction)` Returns the score of the game after applying one `direction` move by the snake. If the game is over, return `-1`.
**Example 1:**
**Input**
\[ "SnakeGame ", "move ", "move ", "move ", "move ", "move ", "move "\]
\[\[3, 2, \[\[1, 2\], \[0, 1\]\]\], \[ "R "\], \[ "D "\], \[ "R "\], \[ "U "\], \[ "L "\], \[ "U "\]\]
**Output**
\[null, 0, 0, 1, 1, 2, -1\]
**Explanation**
SnakeGame snakeGame = new SnakeGame(3, 2, \[\[1, 2\], \[0, 1\]\]);
snakeGame.move( "R "); // return 0
snakeGame.move( "D "); // return 0
snakeGame.move( "R "); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1).
snakeGame.move( "U "); // return 1
snakeGame.move( "L "); // return 2, snake eats the second food. No more food appears.
snakeGame.move( "U "); // return -1, game over because snake collides with border
**Constraints:**
* `1 <= width, height <= 104`
* `1 <= food.length <= 50`
* `food[i].length == 2`
* `0 <= ri < height`
* `0 <= ci < width`
* `direction.length == 1`
* `direction` is `'U'`, `'D'`, `'L'`, or `'R'`.
* At most `104` calls will be made to `move`.
| null |
Array,Design,Queue,Matrix
|
Medium
| null |
879 |
Hello gas I am Lalita Agarwal welcome tu jo on your on coding challenge made by you made on you so late na start tu days late tomorrow problem today's late problem kya bol rahi hai achcha before going tu problem na 1 minutes station par dose jinko This problem has been understood well and there are six questions to try by yourself. Look, this question is literally a little tricky question, a little bit it is on the hard side, it is also tagged as hard, it is a matter of tension. It is not true that you are not getting it, then do not take any tension. Normally such questions are not asked in interviews. First and foremost, the important thing is that in this you will be studying the concept of DP. From the point of time in DP, make yourself aware of three things. Brother, what all are the things to be kept in mind? Firstly, you will have to see whether your profit is or what is your minimum profit. At every point of time, you will be taking the same group which has your minimum profit to add on. Later on it should come three or bigger than three. It means it is absolutely correct. Secondly, one more thing you will have to keep in mind, what is that brother, should the number of people ever be more than five. Meaning, there should not be more than N. Ok brother, it is a simple thing, these are the two things that you have to maintain. Well, what do you have to look at this point of time, one more thing, which group of yours is running before you? Where were these two answers stored because both will be different? He said, this is absolutely correct. Now the concept of my TP is clear, so I directly said that I had stored them and even if there is any doubt. If you know how much you have to do each time, then you can calculate both the answers every time at the point of time or you can calculate it once and store it so that you can know it every time. I can do it, okay, think a little about it, there is no need to take tension, it is not happening, no one said anything about tension, okay, now those who have not understood this problem, there is no need to take tension, first of all. You are going to understand very easily that what is this question, what is it? N happened, okay, first of all, understand what N means that you means. N means that you can take your item number of day after tomorrow. There should not be any doubt in this, it is clear, this one is clear, it is okay. What is the second thing? You should not have that much profit with minimum profit. Bullet, you have understood that you should have a profit of three rupees. Now see, understand this group and profit. What was he saying here? What is the zero index in any group saying that the index is 2% retirement? Okay, 2% retirement? Okay, 2% retirement? Okay, if two people come, how much profit will they give at a point of time of ₹ 2 if they come in rupee terms? If you ₹ 2 if they come in rupee terms? If you ₹ 2 if they come in rupee terms? If you consider, then he said that it is absolutely correct, then here I understood that if we take the first element of this group, then in it, how much will be required of Apna the day after tomorrow, and how much will be the profit of Apna Ko, Bullet 2. Okay, it's a clear thing, it means clear, it's a good thing, okay, you could have taken five from yourself, out of these, did your loved one say that I have taken you, okay, it's a clear thing, now how many backs did you get from yourself even after this? He said, he still has three remaining, there should be no doubt in this, he said, ok, clear, it is good that he could have taken five with him, out of which he took two and he still has three remaining, if he wanted, he said. And if you can take it, then how much is your profit at this point of time? Said, you have a profit of two at this point of time and you wanted a minimum profit of three. Okay, it is clear, now you want one more beer. If you want more profit of minimum ₹ 1, then you will have to take another group, want more profit of minimum ₹ 1, then you will have to take another group, want more profit of minimum ₹ 1, then you will have to take another group, this much is clear as always, I will have to take more groups. I said, okay, so which one more group are you taking, let's take the second group. Because that is the only possibility. Okay, so what is the number of people required in it? First of all, okay, these are still less than three ambulances. It is correct, so you could have taken yours, now you have the saying of remaining back, okay now. Here, how much profit did Apna make? If the quality of three is Apna, then here Apna's profit will be. If the total profit is five, then one Apna could have had this plane in which Apna, what to do is take both the persons, that is, take both the groups. You can say in which the first group is your own and the second is your own group, so you have taken both your groups. Okay, it is clear that one of the groups has been taken as your own and only this group is taken as your own. I will go back, there is no doubt about it and how much profit is my own making in this. Said, what was the minimum profit of 3? Said the reversal of 3 is fine, my minimum profit was of 3 and here I have already made a profit of 3, so any It is not a matter of taking tension, here we have become eligible, here we can also choose this path, political, so how many different rests have our bullets become, two different rests, he said, only give us, did you understand your answer, said, understood. Okay, now look here, come here, what happened to you in the next question, it will happen that here, from the group in which one was in the first group, in the second group, there were three in the second group of 2% retirement. was in the first group, in the second group, there were three in the second group of 2% retirement. was in the first group, in the second group, there were three in the second group of 2% retirement. And Bhai Saheb, in this one, before the five, it is okay, there is Apna Property Bullet, now what happened to Apna here, that you had made minimum profit for yourself at every point of time, if anyone is taking Apna Scheme, then in this you will have to pay minimum profit. The profit of five is fine and how many number of people can you take automatically? Bullet is 10 then tell me you can take 10 items and if only you and only you take then is there any problem? Did you say no only more? Just take it, if it is not a problem, then how much profit are you getting in just 2 hours? Said that it is sex which is more than kissing. Said to yourself, if it is more than the minimum profit, then you can take this, there is no doubt. What have you done to one person, you have got this scheme in which your own and only group take the first bullet, brother sir, you have one such movie from me, in which your own and only group take second and like that WhatsApp group is third. Let's take it. There shouldn't be any problem. So, we have some scheme. Let's take the combination of first and second. If there is any doubt, what did you say? You can take the combination of first and second because by getting both, how many marks will you get? Must be required. Said, profit is more than 5. There is nothing to be stressed about. Said, OK, so this is done. Four, I have schemes, so far it is fine. Fifth, I also have the power to combine these two. Because what has happened to ours is still only 8 and we could have taken till our tenth. Then what was the possibility of sharing that ours is this tukol and if the one who took this five is okay then how much has happened till now. He said, I am done with my sexual pastimes, I am fine, see for the last possibility, if we take all three groups of these three, then even if we take all three groups of three, what will be our number the day after tomorrow, the first 10 will be 10, could we have taken 10, is there any problem? There is no problem, you cannot take much tension, you can take up to 10 is also included, there should not be any doubt, it means it is clear and the profit here, the submission profit of all three, is much better than the minimum profit, otherwise it is not. How much total did you clear? Understanding the question is very important. If there is even a little doubt in the question then I request you to rewind the 2 minute video and try to understand the question. If you do not understand this then you guys. I did not understand at all because the question is literally a bit of a trick, okay, first of all, there is no need to take tension before starting the question, this question is not asked in the interview, okay, if these words are asked in a little hard level then There is nothing to take much tension, he said, okay, now let's move towards this question, now look in this question, I had to keep in mind three things at every point of time, let's see which are the things, he said, first of all, take care of yourself. The thing that Apna had to keep in mind was what is the number of persons Apna had five Apna at max could take 5 So if Apna is taking the first group then why should Apna take how many in the first group Bola tu lene You will read that whatever you are, you will always wish for your 5th, it is a simple thing, said yes brother, you will have to keep this thing in mind, at the point of time from AIDS, you will also have to keep in mind that what is your minimum profit, if the minimum profit. Apna is three and we are taking our first group in which we are getting our profit, so we will leave it a little on this first look, we said, we will not leave because it is possible that this first group is from some other group. Milk, your profit should be more than 3, as if you had bought yours, there is relief only by paying five. Ok, I said, brother, this is absolutely right, if you can't even do this, then how will you maintain it, then look at your one less. Let's understand it simply, the profit in it is right now, we want zero profit and we have a child the day after tomorrow, okay then how much will be our profit, that means this our profit will now be b1 because our profit will be b1. So if you need something, it means will it be valid or not because brother, look at your profit here, you should only have zero and the number of day after tomorrow, you should have extra, this is not a problem, he said wrong, understand this thing again, what did you say? Here, if our group was first, then what can we do as a group first? If we have a group first air, then zero number of persons will work or it will be as many as it requires, it cannot take the middle number of persons, neither it can take less than this nor it can take more. Can you understand this thing carefully? It's okay brother, it's a clear thing, okay, there should be no confusion in this matter, so what is Apna here, how will it not be valid, Apna answer should not come here, I said, okay then Apna He said that if Apna is the first day after tomorrow, it means the first group is profit, right now he wants only Hero, okay and if he stalls 2% here, then what will be his answer, he stalls 2% here, then what will be his answer, he stalls 2% here, then what will be his answer, he said, now the answer will be Apna One, that Apna becomes a possibility, is there any problem? It is not the same thing, it has become clear, then Apna said back to him that right now, this is our group and our minimum profit is still zero and what are you saying at this point of time, at which point? On off time, take 3% of your quality, so is On off time, take 3% of your quality, so is On off time, take 3% of your quality, so is this possible? He said no, 3% will this possible? He said no, 3% will this possible? He said no, 3% will not be possible, why come back again because yours should be either you or what should be there and zero should be good for light air or Then there is a condition and a power in it, that condition has now been understood, you do not have to get confused, keep things clear for now, I said, okay, so now there will be any further condition, you have understood that after the first look. Only zero will come, okay, there is no doubt, he said, it is clear, it is a good thing, now look at what you are saying that it is your second group, what should you say to the one who is taking your second group at the point of time, this second group is six. I took it on time, please give me the profit required, I had the profit required, there is no problem and why do I have the number of day after tomorrow, it is zero, politics, so is it possible that I have the number of zero the day after tomorrow, show and I take a profit of 4. No brother, it is not possible. You left the condition in this photo. Now if I say that I have a number of the day after tomorrow, then it is possible. What did you say, if there is a number of the day after tomorrow, then possible may not be in the second group. But it is possible that you may be in some other group. In the second group, you know that you want the number of people. Okay, it may be possible that you may be in some other group. That is, if it is possible in some other group, then you may be in some other group. Let's look at the group and say, okay, propose in the first group. If only one day before yesterday was required, then it would have been possible. No, brother, you were the only one earning your minimum profit in it, so it was not possible in that, but if here, this is what you want. If the profit was being made for the second group, then it was possible. Do n't understand this. Do you know this? What did you say when you read that you were doing your check for the second group? You said, it is absolutely correct, but now from the second group. Earlier one of our first group has gone and said that it is absolutely correct, now for the second group it is not possible, we have seen it, you are required, we have seen it is not possible for it, so point. On off time, what did you say that before that there was any such group in which there was a group which had its number of day after tomorrow, they formed their own group in which their number of day after tomorrow is correct, there is no doubt, it is not said, there is no doubt and Here, how much minimum profit have you taken? Suggest this minimum profit for yourself. If you have taken 4 then this condition will be fulfilled. Said yes brother, it will be fulfilled. There is no doubt. Okay, now let's take one more condition. Let's take the condition that you make your proposal, now do n't back all the rates of this bike, you normalize it, now here minimum profit was required, minimum profit is ok, now what happened here is that you have seen earlier too that such a group is possible. No, it is okay, I saw the proof earlier too that is such a group possible, which is just a number, the day before yesterday, then I said, Bullet, you did not give the number, no other such group was possible, but what can you say at this point of time? At this point of time, it can be said that the second cannot do it alone, but from the group of the second, what are you saying that if you are the number of persons, then it was a possibility with the number of persons, then what are you saying about the number. We reduce the number of people from the number of questions. We reduce the profit as much as you could have earned. After that, it has become our own, this is our own profit, that too how much is ours. Said, yes brother, I understand. I have come to the point that you have to keep only one number of your profit, now you have only one number of people, how many backs have you consumed, then leave this one, it is not possible in this one, it is true that at the moment you have mined it. Now what are you saying back that you want a profit one, if you have one then did you say that there is no such condition? You said, there is no such condition, you said ok, now you have got one number question. You have got four and one. Check for all the numbers of the day after tomorrow. And there should be no ticket confusion. How long will you keep checking till your number is less than five? I said the number of the day after tomorrow is ok so we are checking for your fourth number of the day after tomorrow. He said, okay, now as soon as I checked for the fourth number of day after tomorrow, what was my constant there, meaning my constant came there that I got minus out of four - became minus out of four - became minus out of four - became three. The number of day after which we have How sorry are you that your profit has been made, said earlier, it was fine and how many coins will remain with you in the number of day after tomorrow, said after 4 - 2 hours, is it coins will remain with you in the number of day after tomorrow, said after 4 - 2 hours, is it coins will remain with you in the number of day after tomorrow, said after 4 - 2 hours, is it possible that you have the number of people, and your profit is only one more. Only one is needed. Okay, this is possible because it is your number. Did he understand this? Look, this thing is a little important, understand it a little, if someone is having a doubt, watch a one minute video and you are going to rape yourself again. What are you saying? First of all, I am maintaining that which group are you talking about? Which group of yours is it okay? Now after coming to this group, I will check my two conditions. Okay. What is the first condition? What are you checking? Brother, now we are the first to check that you are not doing it after now, but okay, before now too, was there any such group in which? This condition was being fulfilled, he said, had any such group come before now, do you want to see this? He said, no such group had come before now, which had the requirement of zero number of persons, meaning, sorry, zero number of persons. Retirement yes And you can get a profit of four, there was no such group, take the first group and if even before the first group, there was zero president on you - 1 was present, president on you - 1 was present, president on you - 1 was present, whatever group was present, was there any such group? Is it possible that in which retirement of zero number of persons and no group can go to their profit, this pan was talked to Maa, is there any doubt in it, she said, there is no doubt in it, then one thing from myself, I had already checked this thing like this. No group has come, okay, this is the group in which there is a possibility. Okay, so this group cannot be that group. It is clear that now that this group has come to you, it means that now you have this possibility. Now what was this possibility saying that we have people from the second group running right now, we said ok, number of profit, how much is our first number of four and at this point of time, how many are our first number of people, we said one number of. It's the day after tomorrow. First of all, we will check with this group. Okay, so tell me, is there such a possibility in this group? Didn't you say that in this group, in such a group, you want a minimum number of day after tomorrow? So before that, your possibility is definitely something. No, leave it first, okay brother, it is clear, I understood, then what did you say? Even before this, there was such a group, it was cleared, the matter was cleared, okay, now what do you have and you are numbered in this group. Checked, okay, yes, so when I checked in this group, were you thinking that you are the number of the day after tomorrow, like if you give me a dog, then I will give you a profit of three. Okay, yes, understand this thing again, what did he say? He said that if you give me the number of the day after tomorrow, dog, then how much profit will I give you? Three is fine, then what about your place, he said, like you have a group like yours, what is happening in your group, if your profit is Had it been three and my number would have been rewarded the day before yesterday, my dog would have become number would have been rewarded the day before yesterday, my dog would have become number would have been rewarded the day before yesterday, my dog would have become one here. I understood this thing. He said, yes brother, I understand this thing, we reduce our number by one, that ours is in this, whatever is our profit required right now. Out of that, I calculate the amount of profit I am making in this one as well. First of all, it is okay, one profit is being made, that means one profit is required for myself and how many back the number of persons I have, I said extra, zero, now on 2. So now check this, sir, there is no condition because you too have already been checked, now tell me, was any such proof possible before you, was repeating myself before you and how much profit are you getting, no group of one is possible. It was okay, then my own checked again. Now with whom did I check the number of day before yesterday? Okay, I opened the number of day before yesterday three. What happened back to my own? First of all, I will check for myself. He said, okay, if the check is done for myself, then myself. When I checked for ' check is done for myself, then myself. When I checked for ' check is done for myself, then myself. When I checked for ' Apna', what happened here that 'Your number is Apna', what happened here that 'Your number is Apna', what happened here that 'Your number is cute'. In this group it was said, 'If cute'. In this group it was said, 'If cute'. In this group it was said, 'If your number is fine then you subtract 2 from the number three, one, now your number is the day after tomorrow, one is a child and 'Apna' How much profit is being made? He is a child and 'Apna' How much profit is being made? He is a child and 'Apna' How much profit is being made? He said, in this there were three people and if one person is required then he will have to make profit of one more. Otherwise, do you have any such group in which your number of persons is one required and one person will get profit? No. Brother, don't go towards your number. First of all, when you understand its correct concept, you have understood that you have maintained three things, one is your own, how much profit is required at every point of time and how much is remaining, second is your number. How many are needed the day after tomorrow and how many are left? Third, which group are you checking in the current teaching and before that, was there any such group in which your exercise date condition is possible? I understood it, I said, I understood it, the concept is clear. Gaya said, the concept is clear, I have understood the concept, there is no doubt in the concept, he said, okay, the concept is not printed out, so now let's see our scheme imitation, in the implementation, we have done only this and nothing else, the implementation is okay. I came to my place, I made a mode when I came because it was possible that my answer would be bigger than the mode, so I would keep doing it forever, reminders would keep coming out, this one is fine, then what size did I take, whose size did I take from the group? He said about the size, it is okay, he said about the size of the group, he said that every time he will rate it, first of all he will see that he has done his trade in the first group, then he will trade on the second group, he will rate it on all the groups to attract. So, first of all, what did you do? Find out the size of the group. Now understand here that you have created your own. Okay, 3d DP, by maintaining these three things, keep yourself on point of time with Tata, so keep yourself according to all three things. Only one box will have to be made, there should be no doubt in it. Okay brother, it is clear. I have made DP with all the three things. There is no doubt in it. Now what is the important concept here, understand the lesson carefully. What is PAN here? He said, why did you make a DP with only three of you, your manly [ __ ] is completely why did you make a DP with only three of you, your manly [ __ ] is completely why did you make a DP with only three of you, your manly [ __ ] is completely dependent on it? Yes brother, it is absolutely right for me, your entire [ __ ] is dependent on this, your entire [ __ ] is dependent on this, your entire [ __ ] is dependent on this, so Apna did this. Why did you put a group ahead of yourself? Look, put a group ahead of yourself? Why did you put a group ahead of yourself? Look, understand what Apna was saying with the first group that if Apna's profit is required to be zero, then again the profit was given to Apna as the number of the day after. One. If we go then what will be the possibility, meaning zero will come, it is not possible, I said it is okay, but if you read the profit of 0 with the first group and you will be given the number of persons, then is this possible, we, this is possible because How many number of persons did you give to yourself and how much profit will you get from that number of persons, you can give yourself profit up to it max because how many atoms was your profit in it, then what will you say in this, if the condition of zero is also possible then that too. It is possible. If you want profit then that is also possible. All three conditions will be possible and no other condition will be possible. You understood this. Before your meditation, you understood that there were only these three conditions for it. Okay, if your second group comes then Apna saw that for this it was possible to get more profit than her own profit. If we got more in the number of people the day before yesterday, then what can I say, there are only six. If you understand, then what did Apna do with every group and every one. You have stored the possibility. Okay, now what do you do? If you suggest, please suggest. If you were not storing the English possibility, then when this possibility came within you that you have a number, you have a group, but what do you have in this? What happened was that after adopting Profit, I had to prepare my profit and I also had number of persons, so I will manage for this own group and what will be my condition here, do I want profit one and I have number of people. If you have already backed out then what will you do for this situation? What about doing the entire trade from the beginning or you can store a query already? I said, I would prefer to store the query already so that you do not waste time for anyone. There should not be any doubt, okay, now you have given the base condition in the beginning, the base condition, what are you saying, brother, you are not on any group, till now, you are on zero group, zero, you want profit and zero, you want one. This is the condition of the pilot, there is no doubt in it, okay, it is a clear thing, then what did you say, first start the look of one of your four, now start the look of this four, on top of this, it was also said that first of all, your first. All the pass plates from the first group of the group will be taken out. He said, ok, it is a clear thing to take out this for all our children. Now what did we do inside it, we made two variables G and P. What are these G and P saying? That how much profit can be made within the first group, you are getting it stored in your pocket and you are storing it in your pocket like the number of people, it is like Should it be easy for me to put forward my own conditions, brother, I want a minimum group of people to put forward any of my conditions. I said, okay, now let's put all the conditions of this saree. Now, what should be the saree condition of the saree, what is the power. One is your condition Shakti in which you are playing your profit back and forth with me like profit is zero, profit is one, you are profit three and vice is fine with us, there is no doubt, said it is a clear thing and one is yours. What is the condition Shakti in which you are playing with the number of persons? What about the bullet? What were you saying here that one number will move the entire profit to the other and if one number is correct then what should one do first? He said, I want zero profit for myself and the number of days after tomorrow, we all try to give it zero, take it the day after tomorrow, brother, you take one, brother, you take it, brother, you take three levels, then four, how many can you take, as many are allowed to you here. Take all of them and tell me if you can give zero profit, will you say that brother? Now take one less, now you take all of them but tell me if you can give one profit, will you then say that brother? Now take all these but tell me if it can give you profit, okay, there is no doubt, you have come inside, now as soon as you came here, first of all understand the contact condition, whoever understands the condition here, the whole game is over. Okay, this is an important condition, here in this condition the same thing has been written which Apna had made in Paradise. Please, first of all, Apna will say that I am also standing on Apna condition, it is okay now, so what is the condition, I Apna was starting. He said to one, Okay, so what is yours? One, zero number of. The day before yesterday, you were saying that in this condition, yours will become one. Okay, so let's talk about the second condition one more time. Okay, now what do you have here? You have number one, I understood it, I said number of people, I have one, okay and how much profit do you want, tell me, is this possible Why didn't you say possible, because brother, I understood it myself. To get this condition, minimum number of people will have to be recorded, the condition is running low, here he is giving only one day after tomorrow and he is telling himself that if he gives profit to himself then he cannot give profit to this one. Said snake, it is a simple thing, I understood it, think, tie the knot, understand that you can never reduce your number of persons, play, okay, so I understood that you are less here. If you can take it then what are you saying that he will check himself or not? Now he was checking himself at less. It is okay here. If he was checking himself here then he will not check himself. What are you saying now? Well, I can't check myself because what is there in myself that I have got less number of numbers the day before yesterday than I got the day before that. Okay, so don't check yourself. Just check the conditions before yourself to see if you can. Earlier, was there any such group in which the number of day after tomorrow is done by doing one pass because right now my number is one and if I get zero profit, then this condition here must be true otherwise this file will be true. Will continue to turn on, now propose what has happened here, you have already happened, okay then as you came to yourself, first of all, you are checking whether there was any such condition before this, was there any such condition in which your Number of paper is required and if your minimum profit is zero, then if it was then it will be here. Okay, and after that, what has happened to you here that you have got as many number of cards as you can sit. Then after that we will also check whether this condition is possible in this also, there should not be any doubt in what we were seeing just now what is the matter here, what is the saree video last. This will be the last group. Okay, what will happen in this group? This group will have the same possibilities as before. It is absolutely correct that you have to trade yourself. It is absolutely correct to speak about this group. What did you say? Now trade yours in the last place. Look at this carefully, understand what all you have taken, said, make your trade on the last one, in which you have fixed a group, the bullet group should be yours, which is the size of the group, it is okay, which is yours. Got it stored in a variable with size and said, 'Okay, second, Apna must have minimum said, 'Okay, second, Apna must have minimum said, 'Okay, second, Apna must have minimum property, so fix both the conditions and then Apna said, vary your number of people, starting from zero and Apna, who required you. So Apna said that take all the number of people of Atmos from zero to 5 that you could and one by one means zero people, then how many were possible for zero people, she told him about her answer. Put it in, then if we take one number of people, then how much was being done for it. For two, for three, for five, all the number of people were possible the day before yesterday. Possibilities of the number have been returned in pulses. Okay. Now understand its space complexity and time complexity. See what will be the space complexity. There should be no doubt in it. If it is a 3D matrix, then what will be the size. How much do you consider your size to be the size of the group? If we take N as N then yes in these. What is the required number of persons of N? He said, okay brother, then N * N * said, okay brother, then N * N * said, okay brother, then N * N * your minimum profit is absolutely correct, if it is absolutely correct then N * N * minimum is absolutely correct then N * N * minimum is absolutely correct then N * N * minimum is perfect, then what will happen to you, this time complexity brother, that too will be because. They are making their own DP, so what is that too? N * N * should not be the minimum. what is that too? N * N * should not be the minimum. what is that too? N * N * should not be the minimum. Ok, let's see after submitting. It is not a matter of taking much tension. Such questions are not asked in normal exams. I have told you these three things. It has been said many times as if you don't like it at all because if this question did not come then nothing happened to us, it is not like that at all, okay
|
Profitable Schemes
|
maximize-distance-to-closest-person
|
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`.
Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\]
**Output:** 2
**Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
**Example 2:**
**Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\]
**Output:** 7
**Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
**Constraints:**
* `1 <= n <= 100`
* `0 <= minProfit <= 100`
* `1 <= group.length <= 100`
* `1 <= group[i] <= 100`
* `profit.length == group.length`
* `0 <= profit[i] <= 100`
| null |
Array
|
Medium
|
885
|
383 |
welcome ladies and gentlemen boys and girls today we're going to solve another coolest problem which is ransom north so basically this problem is awesome so basically what we're doing this problem so we have given a magazine and using that magazine we have to generate our random node okay so what did i mean by that by saying this if you look at it this example so we have something like we i have something string b in my magazine and i have to create a random node magazine which has string a so this cannot be possible because b is not equals to a so we will written force for that and let's say i have something like this over here if you look at over here my magazine is a b and i have to get my random node a so it is possible it is true it will come true for this okay so because why because if you look at over here so in this one like how many times uh a is coming to them then how many times the random note is saying two times as well okay so it is possible but you if you look at over here in this example it's saying like my magazine is a b but my i have to get my random node in which i have 2a so i will use i will print one a i will use one a now i want one more a to uh print true for that to print my random note but i have b in my magazine so it cannot be possible so it will return false for that okay i hope this thing is killing the question is very simple so let me give you uh one more good example let's say i have something like uh a bbc okay and this is my magazine and i have to print something like let's say uh a b okay like this okay so what will happen in this one so this is my uh this is my magazine and this is my random note okay so what will happen i will uh i will check is my a present yes my a is business so i will just use it so my i use my a now i will check for b yes b is present it is okay now i will check for another b as it is present but once i come over here so the b is already used so we use all the b's so what will happen it will become false for that because we don't have anything left okay so now you look like how we gonna solve this question to solve this question that there are multiple ways to solve this question like using hash map but uh i will use one another thing which is quite efficient to solve this question okay so the so what i will use the uh i will use the kind of hash remember i will use its size so our string is of size 26 you know and they are on in lowercase they are all in lowercase so what i will do i will create one let's say frequency map so frequency map is kind of a hash map basically so what will happen in frequency maps i will count the uh like i will count like how many times an element is repeating itself okay so let's say i have something like this uh okay still like okay so let's say this is my initial 0 1 2 3 till 25 okay because like you know in the array of index from 0 to 25 we can't index from 1 to 26 okay like that i hope this thing is clear wrong missing things okay so guys let's say this is my um let me just name it so this is my a b c d like that let's say okay so and maybe till said okay so what i will do i will just simply i will simply put my magazine i will now i'm putting my maximum so how many times my a is coming you know maxine my a is coming two times in my maximum so it's coming two times how many time b is coming only one time anything else no our magazine is complete now i will go for my random node so b is coming only one time so one mistake is coming only one time okay all right guys so my b is coming only one times okay so what will happen i will just uh creating random notification i will say okay i want to a one time so what will happen i will decrease decrement is frequency by one time okay so how many am is present more so only one is present in this one so my a is only one left only in this one i print my a so my a will come now i want one more a so what will happen i will again use this a so i will again use this so the all the a is exhausted now and i print my all the random note and my equation is balanced okay people are like i don't have to worry about the remaining one i just have to focus on my random note okay so guys that's how we gonna solve this question so i have the questions let me still don't have any doubts anything don't worry uh when i will tap the call you will understand definitely all right guys so what i will do i will just simply say over here i will first of all my job is to create an array which is of size 26 okay so you know because like in alpha alphabet from eight to zero we have 26 letters so what i will do i will simply create that one which is size 26 okay all right now what i will do i will run a foreign okay so what i will do i will convert the magazine into my array one okay because you know like to use my frequency map i have to put in my array okay so whatever i will simply say magazine that is in dot it okay and what i will do in this one i will simply say array ph minus a so what will happen like if the element is coming first and it will insert one only for that okay and if the element is repeating itself it's coming more time then it will increment by one i guess that's what i will do over i did over here all right now my another job is to create my random node so similarly for that as well i will create one for each loop for calc okay and i will again put it into my array one okay because like we because you know like i have to now decrease this frequency and check if the element is present or not and how many times is present is it uh fulfilling our dream or not fulfilling our like question dreams or not okay random. all right now what i will do i will care about if condition i will create one expedition to check if my so i will check if my array of ch minus a is zero so let's what i told you like i have something like this so let's say i have something like my magazine is something like a c okay but my ransom note is something like a c okay so what will happen in this one you see i will exhaust from c i will exist from c so for that i just create this condition if this thing will happen then what i will do i will just simply return false for that fourth figure okay and it will if the element has frequency let's say if the my if it has c as well if the maximum ch then it will print then it will definitely want to print my random node so for that what i will do i will just simply decrement it by minus one okay so i will say array ch minus in minus all right guys that's all what we're doing and finally written through ever it's fulfill all the condition then i will prove for that let me just run this code guys and let's see whether it's accepting order any compilation error you know no it's accepting so guys in this portion whatever happen like i will tell you the time and space from research complexity what we are dealing with over here okay so it's accepting so if you look at over here in this one the time complexity we are dealing with uh time complexity is big of m plus n which is like we go of n okay why because like we are iterating through this and this let's say m and n so we are eating through the m string and any string only one time okay and our space complexity is big of one why because like we have a fixed size of area of twenty six because there are six sizes because we are not dealing with any extra spaces okay so that's all the question is and that's all the quad is and i hope you like this explanation and guys if you still have enough just do let me know in the comment section and ladies and gentlemen i will suggest you to watch this video again because it will definitely gonna help you to understand like how did i approach this question because i know like it might be tricky for someone but to just do just watch this video again you will definitely gonna understand believe me and ladies and gentlemen thank you very much for watching this video i will see you next time till then take care bye and i love you guys
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
735 |
On Collision And this is a daily challenge problem for the lead and we will talk about this. The problem is to understand the problem. What the problem is that you are given the area of an asteroid you are given the area of an asteroid you are given the area of an asteroid and what you have to do with the asteroid is the absolute value. We have to represent the size of the asteroid and the sign is representing the direction, if it is positive then it will go to the right, if it is negative then it will go to the left and each one is moving at a speed. We have to find out that if the smaller one is If there is, then the small one will export How will we do this question? Brother, we will do the question. Understand, basically, if we see, what we have in the question is 510 -10, our jo is also going in the positive direction, -10, our jo is also going in the positive direction, -10, our jo is also going in the positive direction, but our jo. -5 is -5 is but our jo. -5 is -5 is but our jo. -5 is -5 is representing our opposite direction, so whatever it is, it will move here and if it is moving here then what will happen now brother, what will it do, it will collide with the body one, collide with the one with 10. By doing this, as soon as tomorrow happens to the paan seller, which one will be smaller in this, our mines will become mines and in the end, we are the ones who have given so much, so what is its basic, let me take one more example, okay and Taking another example, what did I say, what do we do now? What is ours first? So whatever is going to happen, we will push. So, we have minus one, which is -1, ours is going in the opposite direction, then we have taken 3. See 3 Hamara Jo Hai is going in a different direction in a positive direction, so friend, there is no tourism to be had, so we will push whatever we have directly, give us in our step, what do we have to do, Tu Aaya Tu Bhi Hamara Jo Hai Se Text Whatever is in the direction from and will never be collinear, otherwise we will also add this one which is direct to our stack, but as soon as we talked about -3, now we have come to the opposite we talked about -3, now we have come to the opposite we talked about -3, now we have come to the opposite direction and what do we have to do with the opposite direction? At the time of , what do we have to do with the opposite direction? At the time of , what do we have to do with the opposite direction? At the time of , we know that brother lights the opposite direction and from here also it will happen that now if it lights the opposite direction then what will we do, from this type front will come out and front which is absolute value means the top of the step is absolute. We will compare with the value. Okay, we have compared with the absolute value - If 3 is 3, then what will happen to our 3, if you expand it, then - If 3 is 3, then what will happen to our 3, if you expand it, then - If 3 is 3, then what will happen to our 3, if you expand it, then what will happen to us, if our which is 2 will be expanded, then we will cancel you from here and from here. Also and our 2 which is there will go from here, the next thing has come after this, is there any technique in our step after this tech is not empty and what is there in this type is three and here also there is 3 but what is there in the opposite direction. So, both will be expanded, then in the end our answer will be minus one and we will take it as our own. If we talk about overall complexity, then overall complexity, if you want to pop to push, is ours, then it is fine. But if we are doing it for Nestroids then this off and complexity and simple space complexity will not remain. Basically if we see, in the question, what we have is 510 - given that if we understand in this, then 510 - given that if we understand in this, then 510 - given that if we understand in this, then where is five going to be our 5 of ours in this Our 10 is also going in the direction, it is going in the positive direction only, but our -5 which is minus five is but our -5 which is minus five is but our -5 which is minus five is representing our opposite direction, so whatever it is, it will move here and if it is moving here. So now what will happen, brother, what will it do, it will collide with the tan one, it will collide with the ten one, in this, as soon as the 10 one is out tomorrow, then which one is the smaller one, our minus is five, so -5, our x will be uploaded. So -5, our x will be uploaded. So -5, our x will be uploaded. So in the end, what we have is five and 10, we have given so much, so on the basis of this, should we take one more example, okay and with taking one more example, what did I say, I have taken stock, let me now. What will we do? First of all, what is ours? First of all, what is our stock, so whatever happens, we will push it, so we pushed what is mine one, okay, then we looked at 3, what is ours, in a different direction, in the positive direction. If we are going then friend, if there is no tourism then we will give our stock directly to Pushkar, you understood this much, now let us move on to how we will implement it from the end, so I will shorten it a bit so that To make it easier to write, let us create a stack. Okay, after making these test strikes, we have put a if loop. Okay, and after putting a more loop, what have we done? After putting a but loop, now I have changed what is in it. Our greater den is zero, if greater den is zero and whatever is the style, then what we have to do is that we understood with the application, now what we have to do is we have to check our top, what is it brother, what is ours? So what we will do is we will put our we will check if it is greater than zero if it is if we have a negative if it is greater then what will we give where now here now we will give ka with ETV and Emty if further Dot top is that it is greater than zero, meaning what is ours, what is happening with positive, details are being given, so what will we do next, dot com will do it, okay, after this, what did we do, IF condition was applied and in IF condition again we continued Brother, if we have just had a child, it is okay, if our Puri stock is not empty, that means one of the conditions has been fulfilled, but our Puri stock is not empty, okay, it is not complete, and our next dot top is what is there. What will we do ? Hand and S dot top ? Hand and S dot top ? Hand and S dot top is ours, so what will we do? Okay, so we have created a vector named answer and in it we have taken the size and after taking the size, what will we do now, brother, it's okay, let it go, it's okay. And this is being accepted by us, let's see if the challenge is completed, then you guys also complete your challenge
|
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
|
259 |
what's up guys give Iran here today is gonna be helping us and drawing and wanted some attention so giving them it okay so today I'm going over a three some smaller I've been doing a lot of raised problems I'm gonna finish like three some for some and three some closest and I'm probably gonna move on to harder linked lists and then I'm gonna choose another topic I'm not sure what anyway so three some smaller let me zoom in more did you see me look over here I'm looking at over yes not looking at the answers so give me an array of n integers num nums in the target find the number of index triplets where that satisfied the condition that the three of those numbers are less than the target so we have to find the how many combinations are less than that target possible in that array so negative 2 0 & 1 and that array so negative 2 0 & 1 and that array so negative 2 0 & 1 and negative 2 0 & 3 are possible so we just negative 2 0 & 3 are possible so we just negative 2 0 & 3 are possible so we just returned to so we're gonna want to keep a sum obviously so let's just write see you can't even see the code so that's the first thing I'm gonna go to the whiteboard to kind of this one's a little bit trickier so oh and so the first thing we're gonna want to it doesn't say it's in sorted order so let's do that first as well so this is immediately open squared time and yeah because we're sorting it's over N squared time anyway so let's go back to the whiteboard so basically we have it sorted now so negative 2 0 1 3 so we're gonna want to start here and with the first let's say I so I and then we're gonna want to start like put J here you know and then K and loop K through all these looks I guess there's only 2 and then once we loop K through we're gonna want to move J and then try K here as well so that's how we're gonna have to do it an easy way is you kind of like you pass in so we have 1 for loop and we pass in the start and so we're gonna let me just coat it out and I have it in my head so we're gonna have a separate function so to some smaller but that's what I was trying to explain is that we're going to pass in just to the other two and this is instead of loop through all three at the same time we're gonna do two so we'll call that up here basically so we'll have boring and I equals 0 I less then non-stop 1 minus 2 equals 0 I less then non-stop 1 minus 2 equals 0 I less then non-stop 1 minus 2 because we have to check for checking for two indices after the first one I put plus if we were checking for like force on the B numbers out leaf -3 force on the B numbers out leaf -3 force on the B numbers out leaf -3 hopefully that makes sense and so we're just gonna do some plus equals so we're like concatenating the sum for each iteration of I we're gonna loop through I some Plessy blows to some smaller and we're gonna want to do we're gonna have to pass in nuns target which is gonna be we're actually going to pass the target gnomes - gnomes of I because the target gnomes - gnomes of I because the target gnomes - gnomes of I because we're subtracting the eyes and x value and I plus one there's gonna be the start whatever starting in the from the calculation and so let's do that up here cool okay so now we just have to write this out so we have it son we're gonna initialize it to zero as well so we're just gonna return it gets concatenated up here it doesn't really matter and we're gonna have instantly left to evil start and to write equals num stop with me minus 1 we want the grab the last write is like the last index in the array so it's this one this is gonna be right and this is gonna be left or start okay and so we have num step length minus 1 because num suddenly gives us the length which would be our bounce if we're doing index so we're gonna do wall left is less than right and we're just gonna increment these accordingly so I'll show you what I mean if nums right yeah is less than target so this is what we're looking for is numbers of left and nums of right is less than target then we're going to add concatenate the sum - right - laughs so concatenate the sum - right - laughs so concatenate the sum - right - laughs so why is it right - left it's right - left why is it right - left it's right - left why is it right - left it's right - left because we'll writes the highest so if 3 plus 0 is less than target then that means all these numbers in between them are also going to be less than because it's sorted so that's why we have that it's just like a shortcut basically so if that's the case then we just need to move left up so we just move left up to the next one so we can check these values as well so we have I is negative two this time J is 1 K is 3 I think the value is 2 so in this case would work not work yeah I would not work is it equal so and the other thing is the else statement so if not we're going to that means the right is probably too big so let's make it smaller and check there hopefully that makes sense I hope the whiteboard helps and lastly we just need to return some and we can come I think that's work so that's going to be the oven squared gnomes that 100 of N squared because we're sorting it and then over one space complexity because we're not creating any new data structure so there you have it 93.57 structure so there you have it 93.57 structure so there you have it 93.57 announcing you can really get much better I've gotten 100% before so I better I've gotten 100% before so I better I've gotten 100% before so I think that stupid two milliseconds 100 cent I don't know why it's just so much memory space if we're not creating a new array but anyways thanks for watching guys
|
3Sum Smaller
|
3sum-smaller
|
Given an array of `n` integers `nums` and an integer `target`, find the number of index triplets `i`, `j`, `k` with `0 <= i < j < k < n` that satisfy the condition `nums[i] + nums[j] + nums[k] < target`.
**Example 1:**
**Input:** nums = \[-2,0,1,3\], target = 2
**Output:** 2
**Explanation:** Because there are two triplets which sums are less than 2:
\[-2,0,1\]
\[-2,0,3\]
**Example 2:**
**Input:** nums = \[\], target = 0
**Output:** 0
**Example 3:**
**Input:** nums = \[0\], target = 0
**Output:** 0
**Constraints:**
* `n == nums.length`
* `0 <= n <= 3500`
* `-100 <= nums[i] <= 100`
* `-100 <= target <= 100`
| null |
Array,Two Pointers,Binary Search,Sorting
|
Medium
|
15,16,611,1083
|
936 |
Hello guys welcome subscribe Gautam Saeed subscribe And subscribe The Amazing subscribe quote zero commando fuel subsidy subscribe problem nuvve subscribe and subscribe the Channel subscribe final patience with video remove the photo in this direction Veronique watching this point subscribe my channel subscribe must subscribe Subscribe Question Iodine That Can Explain The Anomaly Subscribe Placid Into All Subscribe Button and Number Question Result Subscribe Result Id Hafte in the Train * Kurnool Point Union President Mirwaiz Video Subscribe Will Help in Finding an E Have Already Subscribe and Video Subscribe Jhaal And you modification spring notification subscribe And subscribe The Amazing * No need for a number of Amazing * No need for a number of Amazing * No need for a number of migrants in history quid subscribe to nominate lootera ka notification language se person subscribe and subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to subscribe our Rift In This Manner Of Rather Neer-Ksheer Rift In This Manner Of Rather Neer-Ksheer Rift In This Manner Of Rather Neer-Ksheer Vivek subscribe to the Page if you liked The Video then subscribe to The Amazing Apni Are To-Do To Absolutely Invariable Se Apni Are To-Do To Absolutely Invariable Se Apni Are To-Do To Absolutely Invariable Se China Withdrawal Have Replaced Change The Result Of Tenth Result subscribe Video Subscribe Pimples Aur Neeti Half Value In These Results In Two Verses Suv In Reverse That If And Need To Celebrate And The Result Are Not Implement Subscribe To That Nominees Loot 0 Length Of The Amazing Already Subscribe Please Subscribe This Channel Please Subscribe to this channel Lu A character is a position not a question Mark peer person The question drawn in Chairman Dr A leg for fuel Gator including Naveen that meeting discount inside Yasmin Adhuri returns account first want change are to speak on Twitter counter. com Ki Also Against Look 202 Length 1659 Must Subscribe Alarm Set WhatsApp Mitti Police A Time Complexity Gang Ko Arghya Channel and subscribe the Channel Please subscribe and subscribe the
|
Stamping The Sequence
|
rle-iterator
|
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`.
In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`.
* For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can:
* place `stamp` at index `0` of `s` to obtain `"abc?? "`,
* place `stamp` at index `1` of `s` to obtain `"?abc? "`, or
* place `stamp` at index `2` of `s` to obtain `"??abc "`.
Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`).
We want to convert `s` to `target` using **at most** `10 * target.length` turns.
Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array.
**Example 1:**
**Input:** stamp = "abc ", target = "ababc "
**Output:** \[0,2\]
**Explanation:** Initially s = "????? ".
- Place stamp at index 0 to get "abc?? ".
- Place stamp at index 2 to get "ababc ".
\[1,0,2\] would also be accepted as an answer, as well as some other answers.
**Example 2:**
**Input:** stamp = "abca ", target = "aabcaca "
**Output:** \[3,0,1\]
**Explanation:** Initially s = "??????? ".
- Place stamp at index 3 to get "???abca ".
- Place stamp at index 0 to get "abcabca ".
- Place stamp at index 1 to get "aabcaca ".
**Constraints:**
* `1 <= stamp.length <= target.length <= 1000`
* `stamp` and `target` consist of lowercase English letters.
| null |
Array,Design,Counting,Iterator
|
Medium
| null |
73 |
two so uh today we're doing actually the first medium problem um i've done it's number 73 set matrix is zeros and the concept behind it is you are given a matrix which is you know x and y rows and columns and you have to set the adjacent rows and columns of that zero to be zero for this one it's like top and bottom left and right um and for this one it's all the ones below and all the ones to the right of it so uh this problem is one based off of storing those zeros and then going back and using them to set the other indexes of zeros that are on the bottom and right of the zeros so as always let's kind of pseudo code out this problem so uh to loop through any matrix we want to go uh for the length of the columns and then um down the rows or vice versa to be honest you could flip them so uh pretty much for x stock length i like using x and y for matrix variables because it makes sense to me you know the x-axis the y-axis okay and then we're gonna then loop through here and now comes the part where we want to check if it's a zero and uh so if the matrix at the index of the x and the y um equals zero now what do you want to do well there are uh slightly fancier solutions using sets and contains but i found the most intuitive simple way to do it was have an array x and an array y and the array x would store the x values of all the x's that were zero in our matrix and the y would store all the y values that were zeros in our matrix so if uh the matrix at x and y equals zero then now what we're going to want to do is push in here push in to here push that x value from here and then push the y value from where it was zero so now that we have all the zero x's and y stored now what do we want to do well we're gonna do pretty much something similar we're gonna need to loop through the matrix again so let's uh copy this and bring it down and we are now going to set the all the rows next to the zeros and the columns top and bottom of the zero left and right as zeros themselves so now that we have these two arrays that are storing those we're going to loop through those within the matrix and set them equal to zero let me show you so pretty much for this array uh the length of it we're going to do a for loop within it and if let's just call it uh if uh this one j equals the x from here then we're gonna want to set that instant that index in the matrix as zero so a y like that and it's pretty much the exact same thing for the y so you can just copy this down so that's pretty much how it works so we go through the matrix we store the zeros and then we go through the matrix again and if the zeros are in those arrays we set the indexes to zeros so now that we've uh kind of pseudo coded it up let's go back in let's get a working implementation of this going so let's first declare our arrays i would recommend potentially looking into uh doing it with sets it could be uh slightly more efficient because as you uh sets are unique values so um let's do the let's go to do four loops for both of the matrixes let's there we go so now we're gonna do the if statement checking that if the matrix at y equals zero now we're going to want to push that x in there and push that y in there lowercase so now that we have that we are going to want to do pretty much the same thing so you actually could copy in terms of looping through the matrix and you can paste it down here just make sure you have uh closing brackets with it and now in here we're going to want to do a for loop for our two arrays which are storing the indexes and the zero values so i'm answering that if ax equals the x now we want to set the matrix at x and y equal to zero so now that we did that one like i said the y one is pretty much the same we're just gonna have to paste it and just switch out the was right here cool and that's going to stay the same because it's the same loop right there all right so let's just look through it again so we initialize the two arrays that are going to store the indexes of the zeros we loop through the matrix the first time if it's a zero then we're going to push the x into the array and the y into the ray then we're going to loop again through the matrix using these two arrays we're going to then if it at the index of one of the arrays we're looping through is equal to the x then we're gonna set that instance to zero same thing for the y just it's always good to double check make sure everything looks good it does and i think we are ready to submit and we have an error on line 23. oh there we go it should have been a y right there submit again and it passed great that's why it's good to double check your work all right thank you
|
Set Matrix Zeroes
|
set-matrix-zeroes
|
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution?
|
If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
|
Array,Hash Table,Matrix
|
Medium
|
289,2244,2259,2314
|
219 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem contains duplicate two we're given an integer array of nums and an integer K we want to return true if there are two distinct indices I and J such that the two values at those indices are equal and the absolute value difference between those indices is less than or equal to K now the most important thing to recognize here is that by this statement they mean that the size of the window between the two elements is less than or equal to K so take the first example we have one two three one clearly we do have some duplicate values here one and one they are at different indices and the question is the size of the window less than or equal to K well not exactly actually that's another Edge case that you have to keep track of when we have I and J pointing at the same value here what's the size of this window well it's one there's just a single element but what's the absolute value of the difference between those two indices 0 minus zero that's going to equal zero so this equation is off by one now what about this window from zero all the way to three it's of course of size four does it satisfy the absolute value well we take three minus zero that gives us three or we could have done the opposite and gotten the absolute value of zero minus three it would have equaled three in the end anyway is this value less than or equal to K yes it is so this is a valid window so basically the problem is asking us can we find a valid window of size K plus one such that there are duplicate values in that window well what's the easiest way to solve this problem well let's assume our K value in this case instead of being three it was actually one and that case we would want Windows of size 2 what would be the Brute Force way to solve this problem well just check every single window check this window are there any duplicates and keep doing that for every window what's the easiest way to identify duplicates usually a hash set or a hash map is pretty easy because we can insert and look up values in constant time there's one slight Improvement here that we can make though instead of Brute Force checking every value in this window and then restarting over here and checking every value in this window and then restarting over here checking every value here we can use the sliding window technique which if you're familiar with it's pretty obvious that it can be applied to this problem because this whole problem is about Windows so we would start our window like this we have one and two and then when we shift our window over here we keep this value in the window but we would remove this from our window and add this value to our window and check are there any duplicates here now and we would keep doing that until we got to the end of the array or that we did find duplicate values in which case all we have to do is return true we don't have to return the actual indices of those duplicates so doing it this way the time complexity will be o of n because we're using a sliding window we're never going to add the same element to the hash set more than once and the memory complexity for the hash set is going to be also o of n well actually it's more accurate to say o of K in this case where K I guess the max value it could be is n but o of K is probably more accurate here so now let's code it up so the first thing I'm going to do is initialize our window hash set this is going to keep track of all the values in our window we're going to have two pointers to Define our window we're going to have the left pointer which is going to start at the beginning and we're also going to have a right pointer but we don't need to initialize that because we can just use it in our looping here we're gonna go through every position in the input array nums for every value at index R we're going to check has it already been added to our window if it has then that must mean we found a duplicate in which case we can just go ahead and return true otherwise we're gonna go ahead and add that value to our window nums of R but remember the case as we shift we don't want our window to be greater than the I think it was K plus 1. so before we even do this it's important that we make sure to do this before we do it we have to check if our window is indeed too large which we could check by saying right minus left is greater than k then we know the window is too big because remember we know it's allowed to be less than or equal to K but if it's greater than k then that's a problem we have an invalid window in which case the easy thing to do is just to remove the left most value and also increment our left pointer and that's pretty much about it if we never end up returning true then out here we should probably return false and let's run the code 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 neatco.io it has a ton of free resources neatco.io it has a ton of free resources neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
383 |
okay 383 ransom note given an arbitrary ransom note string and another string containing that is from all the magazines write a function that returns true if the ransom note can be constructed for magazines otherwise it will return for us each letter and the magazine string can be used to once in your ransom note you make a simple string contains only lowercase letters okay I mean this looks pretty straightforward it's just yeah whether in some way there's a ransom note only contains or sorry the magazine contains all the letters of the ransom note so I think you can and it only contains lowercase letters I assuming you know one contains lowercase line letters otherwise it's a little annoying I mean it's not that much harder but well alright so that's just and you could do this by just counting currents of each counterweight so this should be straightforward let's do something like this then we pre-processed a magazine and now you have the number of counts of each letter as in a magazine I would just see if the random no it's underneath or like yeah has fewer than that number for each one so no I okay then you could do it a couple of ways I'm gonna just recommend from counts okay would be roughly okay we could do a few more test cases start the ones that they give you and I think just some edge cases with like empty strings and subject died so in this case I don't think I had do anything different that's some it okay cool yeah so yeah I mean I think this is a very straightforward easy problem it's just did a couple of other ways to maybe sort it I kind of fall in the pockets to its to sorta to solve it one of them maybe just sorting it and then kind of count things off that way I mean I'm obviously is n log n but then and you don't use any additional memory don't go for a fixed out of it doesn't worry it's not that much fixed memory yeah I mean I think this is easier and I think for and as an interviewee yeah and do we I mean just kind of so I done it I think this is pretty easy it's pretty straightforward no got chairs no tricks which is pretty good I mean like this and the problem was very well to be understood as for as an interviewer I think probably this qualms is a little too easy other than as a very basic photo to make sure that the person you're interviewing I can actually do code but otherwise yeah it's pretty straightforward I don't I wouldn't like definitely for higher caliber or more senior words I wouldn't think about giving it to anybody it's just way too easy to be used in a interview I think
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
239 |
Hello everyone welcome to my channel weed, question number 239 of Azamgarh whose name is Sliding window maximum, this question is asked in Amazon and Microsoft and if you want to read these hard marks then what is the meaning and take some sliding window in it, this is of free size. If there is a window then it will always move from one position meaning 12345 mother, first one is of this size then the next one will be of this size How will this happen so this is our example so what do we have to do from this one mines Three five, what is the maximum out of this? Six is the maximum. Okay, so I understood. Now let's think is the maximum. Okay, so I understood. Now let's think is the maximum. Okay, so I understood. Now let's think what we will do is that we will travel on the whole and at the same time travel on its size and find out the maximum from it, that is, let's take mother, we have 13. - 1 - 3 5 3 6 and 7 and K are we have 13. - 1 - 3 5 3 6 and 7 and K are we have 13. - 1 - 3 5 3 6 and 7 and K are given and will travel here A has gone Now for this one will travel from I to I again What will happen if we do it here again 3 - 1 What will happen if we do it here again 3 - 1 What will happen if we do it here again 3 - 1 - 3 So now in this first From here, - 3 So now in this first From here, - 3 So now in this first From here, then this is the smallest value, so the court is also simple in which we will create our answer store because we have to travel only so much, if we go here, it will go out of round which we do not want, so we We will run the result and we have kept a maxi like here we have kept the maxi because the maxi will not be sliced so from this we understand from this that we keep some data structure and remove it. So what will we do in it will become this or we will do that, if it is written, then there will be nothing left for us to pop, so what is the writing element here, what is our index, if its index is given by laser, it is equal to -1. -3 5 Price in this and we keep storing it, so I have explained it to you with the code. Now let's discuss its time complexity. There will be time complexity and why people are there because if we are writing movies on it, then there are more people. Earlier, what we were doing was that we were moving it every time for every index. Now what we are doing is that for every index, we are popping one element Pushkar Ray and one element in it, meaning from here we pop it, meaning so. What we will do is that we are taking this window, so now our window size is not this window size, now when the window slides, it will flood further, then it will become, so what will it become? Minus three five Out of that these elements become minimum meaning here will be maximum or minimum so we are also storing this that can be or can be Now we go ahead -3 to 5 now 5 Come but let us know what is our maximum so what will we do in this here so what we will do here Okay and this is our this one for that one for this index this window size is now smaller than the again scene process for this window If our back one is smaller and if it is equal to ours, that means if we set the window size, if we hit the window size, this is the same process here and when we get a window size equal to this, we hit it. It means that whatever happened here, we did it here and in the end we gave the result.
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
1,942 |
That today we will discuss aa list ko problem 194 so 18 smallest number of small extent that chair so what is given here is a party where in fur and wide web 000 and last date - one okay zero inductor last date - one okay zero inductor last date - one okay zero inductor after that In the party with infinite number of chairs, Tripathi will tell the popular in some sequence that now people will take the smallest polish available and will give it to that friend who has given the latest one, like if this 40 points then if any friend comes. So he is sitting at gate number two, after that you come, okay, so what are the important qualities given in it, hey, he has given the time of every friend, that is, the arrival and living time of every friend has been given in that and we have given the target friend. Given the index, we have found out that this is the target friend. Basically, which face will be signed by this? This is the index. So let's take an example and understand like this is the arrival time of our three friends. Okay, you are the first friend, one means. One is coming in and going out in four, the second one is coming out in friends meaning free and the third one is coming on friend a kapoor and going out in six any one take one unit meaning minute mario any them time Okay, so what is given here, friends who arrived at the time T2, this is set communication zero because initially all my share articles were available. Okay, then after this, one Bihar, at the time, saw at the time, then at the time, fairer to pocket. If ID remains then this lace is taken to next leg available Sharmila one small s Next smallest available crotch important after that friend one leaves time arrow then chair and name is done then friend zero also leaves time for par share goes to 0 Then it becomes our time to become a friend. When the time comes, then he is fine sitting on the chair. Because MT Urea himself and Android had relieved themselves for the time, then we have a second friend who has no contact with us. Similarly, our example sitting on the second chair is that a friend like type comes at time one and OK Khan, here this sign is important that not everyone is shot in the increasing order of time but it may be that late means here. Friend one is coming first, Rajan, friend zero, so this thing is important, okay, here Rajiv has become a friend, Jio channel is better, then friend to arrive is the right time, this four is sitting at number one, then friend zero is coming. This share is sitting at number two and then getting close to becoming a friend. The friend has 100 friends. He has zero on the chattu, so our output will be two. Okay, so we all see the constraint now. Your arrival time is the district and this is our Whatever the number of friends, it is for on 10th, it is okay, arrival and live in time, again on all the trends, enjoy the Amritsar, target friend can be as many as and minus one because in the worst case, my article target friend will basically remain inside these. From right zero to the end minus one, it will remain the same, that's okay, so now let's see this question, how do we solve it, okay, A, I work, we are different, you see it every day. Okay, so the simplest thing is that everything can be as simple as this, it can be clean, any chair can always be given to its friend, any share status will always be there, either it will be available or it will be reserved, okay, so they can right. Meaning can have here two status so where is it available and the result is good then this face will always be 210 available and if the result is ok then and here we are given that whatever new friend is coming, he has to be given the smallest available. Share will be given, okay, so whenever we have this thing present, then generally we should use such a data center which is like a bigger one time, we give a small s, that channel miniclips all this, okay These are the things that you can implement like priority queue, okay, we which are your special, so the article is good, okay, so basically what we will do is basically one, now we have to basically take 2 minutes of these two main hips and priority why Afor here. But in trekking boat there is available end resort, ok, what do we have to do now mine can be that in available, I know that in available, my minute article means what will be the basic structure of whatever object, just give it a * Maybe the only thing available to us is just give it a * Maybe the only thing available to us is just give it a * Maybe the only thing available to us is basically that we need share index and rate but here in the resort, I give chair and expectation to us that here we need two things that we need share index also or A+ for our departure. Time will also be required A+ for our departure. Time will also be required A+ for our departure. Time will also be required that the person who has occupied this share index, what is his departure time? Okay, because basically what will happen is that suppose a time will come when now some hair tree chairs will be available in a huge reserve. Okay, so I chair. More research will be required. Vaccination and departure time will be required because we will have to track that time so that at that time we can remove unnecessary hair without moving the article available from the result. Okay, like see the example here. That here I had gone to the Chair in Friend One, it is fine, but when I went to write the edit time MP3, we have to make Chair One available back to back, okay, so therefore we will have to maintain the departure time of each report chapter so that we So that we can track when the loop becomes free and the back toe becomes available, right? And for both of us, we will get the available result in minutes, we need the lowest number from the available and also from the result chart, basically two, here is the most The important thing is that the departure time will be first because the sooner we deposit, the sooner it will be available. The exact time was to keep the departure time first as per my wish. The Comparator function which will be there will compare it accordingly. Whose departure time will be the lowest will be the mini of my result. It will be in the top, okay, so now let's do this work for a long time, if I see it, then there will be time complexity, this is my N producer, login will come soon, thank you, because suppose now I am here, come to TV every time, but President. Take this example, okay, here our three chairs were signed on different purchase orders, so how many N times would I have run the loop for each friend and for each friend, I would have asked what would happen in the result and when you You must be aware that but in the high priority queue, there is a time complexity regarding the flower login. Well, what will happen in this case, in this, I will always flower in the resort, sometimes the reserves will not be back to available, so what is the complexity of that. That you all got separate chairs and these times I gave my basic flower to every friend for one hour but if the result is not good then Login Basically this flower is coming from the operation and it is fine for every friend of mine. You will become a big fan of the space complexity because here the maximum size of both available and result can be reduced because I have so many numbers and friends, and the maximum number of friends, if so in the year case, and minus one number of seats in that use. It has to be done, okay, so let us discuss a lot, you decide the matters, okay, come in, now I will minimize it a little, turn it on, okay, come and loot, this is my target friend, whose I work for this, I take its arrival time as Sun, A, target, A, friend, this skirt, 0, okay, now I work, basically according to A, the number of friends will be there in the number of times, now I go back and make two proteins. Okay, so First of all, mine will be available, so if I want to make it minimum, then I basically made it like this by making it available in A. Okay, now I will do this, I have made it available for one month, now what will I do, I will rob Ajay soon. Okay, this is basically ours, this will remain in this will be ours, this will remain reserved, okay, so basically we have made two priorities here, one will be available basically and the one with restored result will be ours, okay now what will we do, this basically we will shoot Will do now times are ok time start science a times rot end a ok why did we have to shorten because we were not made to feel ashamed that the one who will be first in front has his arrival time put first and shoots this number because we have to go in increasing order We have to process the article on arrival time, okay, we have done this much, now what do we have to do, now we are basically running the loop, okay, we will take out the Sahara times, okay, so first of all, what should we check? What has to be done is that [ __ ] free from good result back to available is fine if one can bring the reserve back to available then purely for the operation is fine then what has to be done is that it is not anti oil reserved that hand that regard to top They are the first so on this day equal two teams in more ok so here what we will do then I available ko pushya good result top asecond that was reserved for ₹ 5 nothing was done first we will see ₹ 5 nothing was done first we will see ₹ 5 nothing was done first we will see if the result is not our anti and the result Who is top, who is first, who is maintaining the departure time, all the best results, chaircar departure time, if he is less than the arrival time of our new friend, if all the results are small, then ask everyone available and flower of second. And now the course available is maintaining our chair intact, okay and then you do it from the result, okay, after this we will do that if our chief is 200 or he is equal and speed a friend, then we will break it, okay. And after that we will basically do this that if it is not there then we will basically see that now we will have to sign someone from the available one. At this time the friend is okay with one share so we will see that only the available one if he is an MP. So what should I do, I have to flower in the result, basically we have 2001 and we have to please us and the size of the result, okay, the result is not work, not the size, why did you ask because in the article, we have this idea that we have reserved our maintenance that you Till what number of chairs have been used, let us assume that the first chair is the one that has taken its place, meaning basically the newest chair in the resort, the one that remains small, will remain the reserved size because the result size is basically your index of 00054. Ok so here basically this is the body otherwise good result Pushya will always be a tier one otherwise if we ask about available then I am available because see here if your available is anything else it means that you are in an increasing order. It is increasing meaning that the sequence of the whole face is being taken by the sign killer, therefore, this new chair of reserve top and the intake of the new chair is being revealed and if it will be available here then it means that the existing chair has already been used. Basically, the staff will sign back for some other friend. Okay, now that's enough, this waste is out of the form, basically what to return, now we have to return only here, if my MP is available to you, then return this to me. If it is then this face of mine will be signed otherwise it will be there. Basically you are seeing this condition which is here I am going for breakfast and I should implement the effects condition which I have written here. If my available MT was there then I would get the result. Selector that target friend, if it was not there then I would have topped the available, so what I have written here, I have simplified it in the ternary operator. Now if you want, you can click here, but this is how I did it right. Then let's fold it once and see. Okay, okay, greater entered that I think there will be one more here. Yes, yes, let's look at our example test case. After running it, we will quickly submit it and see that it is all right. So this code of ours has been sent as SMS and This around 40 cent poster is not full of C+ This around 40 cent poster is not full of C+ This around 40 cent poster is not full of C+ Plus online solution but you understood the logic, Bright basically Amit, the article has to be interchanged between two states, that is between level and results and Yadav is the data structure with priority queue. Watch it, which is good, it means it is used a lot, it is asked a lot in the interview, so okay, that is it, so hop, you must have liked this video and if you liked it, then please like and subscribe and comment. Can I improve and Students of Today Happy Wave and Have a Nice Day Thank You To
|
The Number of the Smallest Unoccupied Chair
|
primary-department-for-each-employee
|
There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a **0-indexed** 2D integer array `times` where `times[i] = [arrivali, leavingi]`, indicating the arrival and leaving times of the `ith` friend respectively, and an integer `targetFriend`. All arrival times are **distinct**.
Return _the **chair number** that the friend numbered_ `targetFriend` _will sit on_.
**Example 1:**
**Input:** times = \[\[1,4\],\[2,3\],\[4,6\]\], targetFriend = 1
**Output:** 1
**Explanation:**
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
**Example 2:**
**Input:** times = \[\[3,10\],\[1,5\],\[2,6\]\], targetFriend = 0
**Output:** 2
**Explanation:**
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
**Constraints:**
* `n == times.length`
* `2 <= n <= 104`
* `times[i].length == 2`
* `1 <= arrivali < leavingi <= 105`
* `0 <= targetFriend <= n - 1`
* Each `arrivali` time is **distinct**.
| null |
Database
|
Easy
| null |
43 |
That a Hello Everyone Welcome Debit Challenge And IF YOU ARE WRONG WITH LAST YADAV AND SUBSCRIBE subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to subscribe our THIS IS WORLD'S QUESTION PROXIMITY ESSAY SUBSCRIBE PLACEMENT SESSION INCOMPLETE LONG INTERESTED Subscribe to Multiply Strings List by 2 to 6 Sameer and Subscribe Must Subscribe Video Subscribe Titration Vihar to Will Be Replaced to subscribe for Live Video Channel Subscribe subscribe and subscribe this Video Subscribe 512 Subscribe Room Se Contenders Current Performance Thursday Ko subscribe to subscribe and subscribe the Channel Paun Inch Tak Subscribe Ki Placid In 1st House For Rent To Paneer 128 subscribe Video Subscribe Depression Number To Do Subscribe Video Subscribe subscribe for Live Video Subscribe Me Ande Speed Kam Se Final Acid Five Ande Speed Kam Se Final Acid Five Ande Speed Kam Se Final Acid Five 608 Subscribe Property Appointed subscribe 9 subscribe 158 20 subscribe for celebs subscribe for thursday how to 16 word index duty world in the first number list in taxes in the first number subscribe button to my channel subscribe and subscribe the Video then subscribe to subscribe our that flashlight btu interactive web school top 234 five subscribe must subscribe my channel subscribe pimp tube gayi hai what would you have asked to explain the first number silencer se number subscribe 4,320 subscribe and subscribe me indiscriminately a product model town impatient they do subscribe and subscribe this Video Please subscribe and subscribe the Channel Please subscribe our ki accepted aur time se zahir video subscribe hai
|
Multiply Strings
|
multiply-strings
|
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string.
**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly.
**Example 1:**
**Input:** num1 = "2", num2 = "3"
**Output:** "6"
**Example 2:**
**Input:** num1 = "123", num2 = "456"
**Output:** "56088"
**Constraints:**
* `1 <= num1.length, num2.length <= 200`
* `num1` and `num2` consist of digits only.
* Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
| null |
Math,String,Simulation
|
Medium
|
2,66,67,415
|
885 |
welcome to my channel so in this video i'm going to introduce a solution for this lead code question called spiral matrix 3 and also at the same time i'm going to introduce briefly about the steps we should follow in the real interview so let's get started remember the first thing here in the real interview is always try to understand the question if there is anything unclear please bring up the question to the interior and at the same time think about some ash cases so let's go through this piece uh this piece of description together so on the 2d grade with rose and c columns we start at r 0 c 0 facing the east hence the northwest of the con unless corner of the grade is the first row in the column and the southeast corner of the grade is the last row and column so we walk in a clockwise spiral shape to visit every position in the grade so whenever we move outside of the boundary we continue our work outside of the grade so eventually we reach all the spaces of the grade and return we need to return a list of the other quantities representing the position of the grade in the other they were visited so suppose we have a five by six uh grade and we start at position one four which is this one and the trace of the walkthrough is something like this and we record uh the sequence of each of the cells the sequence of the coordinates of each of the cells into this output so we can see that the input the matrix the grade is not it's never going to be empty and the initial position is always going to be valid so in this case i don't think there is too much of the room for us to think about ash kiss so let's get started to the next step so the next step is about thinking about solution discuss with your interviewer talk about some runtime space analysis and then after you get an agreement you can start doing some coding work and take care about the correctness readability and also the speed so let's go over this piece of code together so we define two helper functions the first helper function is to see whether the current position is within the range so essentially we are saying whether the row is really currently always within the range and whether the current column is within the range so you close it so the next thing is the next helper function is essentially try to set the current position the coordinate of the current position into the matrix so i'm just going to close it so let's go through the body of this major function um we have four parameters rc r0 c0 so we need it's like a onion peel steel so we need to first compute the layer of the maximum layer so we will need to go through so for he for this we don't include the innermost layer so instead for let's say for this example we only have four layers which is something like this so this is essentially the first line we compute how many layers we need and we will need to initialize the matrix which is a 2d matrix and the second dimension is a fixed length of two so um this is a iterator uh it's initial it's just the chord the iterator about the coordinates we are going to set into other our metrics so initially we set r0c0 to be the first coordinate in the matrix and we have we start from the current layer reaches one so um in each layer the less uh the so in each layer we are going to like do something like an impeo so let's say for the first layer it is something like this if you see my mouse i'll do it again it's like this so you can see uh the lens of each of the each side it's actually i'll just say it has two like for the left column i would just for the left sorry for the right column it's just like this from two to three for the bottom row it is uh from four to five and for the left column is six and seven for the upper row it is eight and nine so you can see that in this case we don't have any overlap between the rows or the columns so this uh so under the lens for each layer is the layer times two so for let's say for the we are first going to do the right column so the right column let's say for this one for the first layer uh for this it is two and three so we will essentially just go through um the co the row index with the first column and add the corresponding coordinate into it and similarly we are going to do the rest things for the bottom row so for the first layer it is four five you're going to do the left column for the first layer it is six and seven for the up row for the first layer it is eight and nine so and uh every at every position we are trying to see we need to make sure that uh the current position is within the range is within the grade otherwise we will just continue and finally we should be able to visit all the cells within the grade and we just return the metrics so that's it for uh this code and the solution and remember after you're done with coding please do some testing accordingly so the runtime for this solution is going to be uh let's say i'll just write it down the runtime is going to be oh let's say max of r or c so it is going to whichever is a maximum uh two so whichever is the maximum between r and c we are going to do the square on top of it this is the runtime so let's say if r is larger than it is r squared if c is larger is c squared uh so that's it for this coding question if you have any question about the solution or about whatever feel free to leave some comments below and i also have some summarization about different types of the question in this sheet which i have already shared in the video description so feel free to refer it during the time you prepare for your interview and thanks for your time watching this video i'll see you next time
|
Spiral Matrix III
|
exam-room
|
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid.
Return _an array of coordinates representing the positions of the grid in the order you visited them_.
**Example 1:**
**Input:** rows = 1, cols = 4, rStart = 0, cStart = 0
**Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\]
**Example 2:**
**Input:** rows = 5, cols = 6, rStart = 1, cStart = 4
**Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\]
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rStart < rows`
* `0 <= cStart < cols`
| null |
Design,Ordered Set
|
Medium
|
879
|
929 |
yeahyeah Hi everyone, I'm a programmer. Today I'll introduce to you a few math problems with the following titles, email addresses, and detailed lyrics as follows for each email. then we will contain two components, one is local Nam which is the local name and do ta me wedge which is the domain name and is separated by the symbol a cuc. For example, we have emails as Elise and then As for , the two components As for , the two components As for , the two components are separated by a comma, elite is the local name of this email address and of this email address and of this email address and is the domain name of this email besides the English characters. You know, often emails contain a dot sign or a plus sign , so if we have a , so if we have a , so if we have a dot between two characters in a batch and you are in a local name. part of the email address, the email will be sent to a female that is viewed there, it will be forwarded to the same email address without a period without a question mark in that local sheet, for example We have an English email and put a z in it. If anyone still helps, we have a rice mark. When we look at the email to this email address, it will actually look at Ellip, remove the dot and give it liv-z a. cuffs dot and give it liv-z a. cuffs dot and give it liv-z a. cuffs will rarely send to this email address. Please note that this rule does not apply to manning items. That is, if there is a dot in your pad, do we have to or do we not? can be omitted, must not be omitted in the Nam format. We can only ignore the period in the local name. Okay. If we have a plus sign in the local name, then for each with all the first characters where we encounter a new dot and all the characters that are after the first dot and plus sign will be ignored which means we allow emails to be will be stripped. For example, if we have just email m.vi then we have just email m.vi then we have just email m.vi then we have a first plus sign, then all the letters after this first plus sign will be removed. For the black coin, it's just for the local name, what will happen when we look at the email to this address, it will turn out to be an email with the address , address , address , we also remind them This rule will not be applied to the domain name, but it can be used in both. We can use both of these rules in the same email. Okay, I'll show you again. If we have a list of emails, we will see the emails going to each address in that list. The answer is the question is how many different email addresses actually receive the email. Let's see that we have to calculate two medals, two strange rules with a dot and a plus sign in the name, the local name. Okay, then we will go into example 1. For example 1, we have the location. only the first email is test dot email + erect a cuff is test dot email + erect a cuff is test dot email + erect a cuff he second email address is .vn he second email address is .vn he second email address is .vn third address is test Email third address is test Email third address is test Email plus David a also called behind the domain name ly dot domain name ly dot domain name ly dot Okay, now we will see if it is really network emails when we send emails to these addresses, which email will actually be received, we see that with the first email First, it will become that if there is a period, we remove the period and the plus sign after the kid + risk, we remove all after the kid + risk, we remove all after the kid + risk, we remove all the characters like that, the first mother will become email@ Why do become email@ Why do become email@ Why do we remove the plus sign from the LED and then similarly in the email? Second, we have the dot here. We remove the dot. Ha here we remove the dot. Then we see the first plus sign, then all Even if we remove everything after the first jelly, it will still be Tet email, but if there is a dot com, the same thing in the third email we have is email shrimp and then there is the first plus sign after that. Let's remove all the plus signs first and I'm sorry, David. This is Tet email, but the rules behind the domain name don't apply. So what's wrong with the following units ? If Lee dot em like ? If Lee dot em like ? If Lee dot em like that, we see that it's an email with a few good emails, after we apply those two rules, it will become a single email, Tet email, who knows if there's dot com em and the other one? spa email, it will become another email, Tet email, and ly dot is like that. In the and ly dot is like that. In the and ly dot is like that. In the end, we will actually have these two emails, which will receive our email and we will return the results. is number 2A Well, after we read the problem and we go through example one, you may also understand the requirements of this problem. Now we will go into the algorithm to solve the problem. The problem is not in Well, for this problem, in the sequence No practice, we will have a loop that goes over all the emails in the given piece and then in each email we return go through each character in the Email. If the character is a plus sign, then we will have a Buon Lang variable for us to mark as all the characters behind this plus sign, up to the Ignorance is also them. We will eliminate your house from the second school: if house from the second school: if house from the second school: if we encounter a dot, we will ignore the dot if this dot is evidenced before Ha Long ha and the swivel chair is still there then Dot Hey, we still keep it the same and after we use those conditions, we will create a temporary variable to hold all the remaining values of the email, which is the email that is actually sent later. We will put this complete email into a map so we can mark this mail as the mail tree that has been marked as the mail and then send the marked header and then we will return it. The result for the problem is the length of that block, so our Map will be a tree, a string of real emails sent and the suitcase will be sour phone Chu means we sent the This email already exists, then next time let's say in example one we have the email after we follow the rules of the dot and plus sign and the remaining thing we will have is test Email lescott planting the bridge, we put lescott planting the bridge, we put lescott planting the bridge, we put in this email and do that of the map to the email. Second, after we calculate and apply the perch cutting rules, it also becomes an email shrimp and However In our blood, the However In our blood, the However In our blood, the email cell that needs to be written has a tampon. It's already an existing thing, so we won't have to calculate an additional value for this label. Well, that's the way we do it. The map will help us filter out similar emails but duplicate emails. Okay, then recording, I think there's nothing complicated about this problem. Let's go into the settings section, then I will Installed using the led code programming language, first I will declare a piece and then vegetables, then my resort in the present I will alert the map with the type to record the broom and suitcase as kiwi and then I will return it. Regarding the length of the long one, the result for my wife is the length and size of this map, probably the number of branches of these maps. If I have one of these, learn it again and I will put it in. the map and I show its data is the mouse Okay now I will go through all the elements in the network Email then I call the email will be the email mine on the phone named email without pressure Next Then I will key the email network and after forcing, each time in each email we will declare some additional Buon Lang variables for us to mark each time we browse each character of the emails. email, I see a plus sign, a minus sign or something like that, I have the first piece and I call it delicious vermicelli. Know that its first declaration says phone, I know it's full, which means when we gas after but we meet the plus sign when we meet plus will turn our is no will turn into will try to get fish equal to chu then it means somehow all the elements at the back check we check If is no equal then we won't have to add that character to our email, our real email and secondly, we will have a variable called rifleman when Iron Man lets us have a smartphone. then Iron Man is when we go through the overlapping characters, then after we go through the vaccine, we will mark these Idol Men with a meaning that we have now moved to the value in The enamel of the email and why do I have to mark it because when I mark it like that, the rules are not applied, if the rules are not applied then we will take everything The characters we put in is that email and the second variable, the third reason we will be and save it in the Apple email temple and it will be the Bayer type, what are the characters ? If it is valid, we will put it into ? If it is valid, we will put it into ? If it is valid, we will put it into these Gmail sets . Now we will browse from . Now we will browse from . Now we will browse from left to right, looking at each character of the Thuy emails and how we declare a filtering circle. starting from zero y will go to every last element to the last character of the email and go increase by one unit and then we will go check each school one by one first is if the email character of The email at the y position is equal to the plus sign. Yes, if it is wooden + then we have to Yes, if it is wooden + then we have to Yes, if it is wooden + then we have to put is noisy all is no. Bang Chu already Yes, the second one is we will go check the Email at the position low y but it's equal to the mark of the husband Yes it said mark ah And then Meaning Strange we will give these Idol Men equal to the next time we have moved to the component that is the domain name of the email And then after that We're going to start adding a few more steps to check if our Idol Men Bang is on the phone, which means we're still in the box and you and the email are at your favorite location. If our number is equal to a dot, what do we do? We will ignore it. We will ignore a dark character. Then we will ignore these Dot characters, but only with the condition that it has not yet been approved. To the Idol Men, if it has already entered the city, it has entered the letter to the right of the dot, then we will still get this dot a. Yes, then we will have One last step to check is when it's no. If it says is no by phone or Idol Men by chu. Yes, we'll give our email actal variable a new value. Lottery song I sing for email. Help add a character at the noted position, then after we browse from the first character to the last character of Vinamilk, we will apply all these rules, then we will have a your email is that an email is valid and will receive our email and then the two of us will give this email and call in the cooler uh We put this email in the map to make the seed for email And I've set it up with the mouse. So I've completed the step of installing the algorithm for this problem so I can try running it with example 12 to see if there are any problems. Okay. So we have successfully taught. with no result returned are the two desired results you and Hai Let's try to create an account to solve other examples Okay so I have successfully sent all the other examples of the problem now I will Let's analyze a bit about the complexity of this algorithm. Well, for this problem, we call N the number of elements, the number of emails in the email fragment, and M the length of the function of each email. then we will have the complexity of it again but dim A and the complexity of the store user if we use a map then this map will have there is the length of the Email and the number of details The latter is equal to the number of emails in the worst case, so we have the complexity of citizens treated as Huan Ah. Thank you for watching the video. If you find it interesting, please give me a like, sub, like and share. Kinh If you have any questions or comments or have a better solution, you can write them down in the comments section below the video because you say goodbye and see you again.
|
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 `"[email protected] "`, `"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, `"[email protected] "` and `"[email protected] "` 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, `"[email protected] "` will be forwarded to `"[email protected] "`.
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 = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 2
**Explanation:** "[email protected] " and "[email protected] " actually receive mails.
**Example 2:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**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 |
326 |
this liquid challenge is power of 3 and it's number 326. giving an integer n we have to return true if it's a power of 3. otherwise we have to return false an integer N is a power of 3 if there exists an integer called X such that 3 to the power of x equals n this is an example if n is 27 then 3 to the power of 3 is equal to 27 so this condition here is satisfied therefore we can return true if n is zero there is no integer X such that 3 to the power of x equals zero and therefore we have to return false if N is a negative number then we don't have any integer X such that 3 to the power of x equals the negative value in this case n is negative one so we have to return false this year in the text editor is my solution it's a Boolean function so we have to return true or false here I'm taking care of cases where n is either 3 or below 3. so we first check if n is equal to 3 Let's assume that X is one three to the power of 1 is equal to 3 which is n so that is correct and if x is 0 then 3 to the power of X would be 1 and if n is 1 that is also correct so we check here if n is either 3 or less than 3 we can return true so long as n is either three or one in any other case if n is 2 or 0 or a negative value we return false then here I'm going to process my value through a while loop and at every iteration I'm going to verify if when I divide n by 3 I guess any remainder if n is divisible by 3 whatever value it is we are not supposed to get a remainder but this modulo operator will return the remainder if there is one if this for example is a value other than 0 then this condition will be satisfied meaning that we're going to return false we are not supposed to have a remainder if n is divisible by 3 so if n is divisible by 3 this condition will not evaluate to true meaning that we are going to jump here and here we have else if n is divisible by 3 then we are going to divide n by 3 and store back the value into n so here n is getting updated assuming that n is 27 then when we check here 27 divided by 3 there is no remainder so we come here and we add this n to be equal to 27 divided by 3 which is 9. so here n is going to be 9 we're going to jump here 9 divided by three there is no remainder so we come here 9 divided by 3 is 3 itself this condition is still satisfied 3 divided by 3 there is no remainder so we come here n divided by three is one so here we verify if n equals to 1 then we can return true otherwise we return false like I explained here n must be divisible by 3 until the result is 3 so that when we do n divided by 3 again here n will be equal to one so that's it for the code now I'm running it we pass the test case now let me submit this and we've passed all the test cases if you check the details there were over 21 000 test cases so this solution is being tested extensively and we did pretty well so that's it for this lead code challenge it was called power of three the number was leads code 326. if you like my solution in C plus and it wants more coding interview questions please subscribe to my channel and I'll catch you next time
|
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
|
315 |
three 15 count of smaller numbers after self you're giving it an integer away numbers you have to return new counter way the counter where has the probably where it counts up I is the number of smaller elements to the right of number supply okay hmm my intuition is that there's some sort of stack things here no maybe not they think about this for a second these are very easy to read format least not a tricky thing I think also would have been nice to know what the end is / that's maybe fine well now I'm just thinking whether there's there ways to abuse or maybe not be used abuses but just some way to figure out how to use some sort of prefix or suffix some another thing I'm thinking about is maybe some sort of log and data structure like some sort of witch McCoy like some sort of trees actually let's see what happens if just a train let's say you have five and then - I think there's a yes yeah there a - I think there's a yes yeah there a - I think there's a yes yeah there a couple of trees like segment trees mmm string about in general to be honest I am NOT from your in segment areas a lot of people these days it was not as common when I was younger who to know about segment trees but uh mm when if there's a way to cut away I guess that kinda is like this entryway well there is some sort of I want to say that there is some sort of like whatchamacallit I mean well query there's an N square room so Phi n square is not gonna be good enough if it's a hard so next thing I would think about is n log N and what's in that cost of n log N and log n problems maybe some and that is yeah we lay into something I was thinking about just like some sort of longest sometime thing thats related to longest increasing subsequence I mean obviously it's not going to be increasing in this case maybe not but maybe going backwards better looking backwards six and then some sort of tree make sense there yeah maybe if a family tree is the way to go because yeah maybe also kind of reminds me a little bit of Cartesian trees with stacks but that's don't know how either tree here I think it's a standard issue well like to you point to the one what this is strictly smaller I guess strictly smaller there's no uniqueness or anything constraints no notes no okay so I'm going to assume that it doesn't have to be unique and it's strictly lower hmm right tilt backwards well one is going to be zero and in six yeah I think segment treatment we just keep on how many okay how would I create okay I don't wanna I'm also try to think a little bit about how to do things in Python easier like you could if there's a way to maybe like quiz it core like ordered map in C++ I quiz it core like ordered map in C++ I quiz it core like ordered map in C++ I think like you could just do the what's it called lower about right and then maybe the lower value could cut into it that way to them right and I think you could use something like yeah dough in this case will be reversed but learn to C++ maybe I'm gonna play but learn to C++ maybe I'm gonna play but learn to C++ maybe I'm gonna play around that on using lower bound and an ordered map Kristen you get to login curry yeah okay I'm done okay Oh actually I want to be worse this where'd I do it now you have two results so then you just that seems reasonable but first we want to create an out of reverse no lower bail which gets the next number that is greater than or equal to nine numbers actually we want the negative of this so we could cut into the way and then now we look up and we look up it's not a purse one of - and we look up it's not a purse one of - and we look up it's not a purse one of - money okay so we want num - one so the money okay so we want num - one so the money okay so we want num - one so the reverse of that it should be something like that may be reversed actually but I just want to see if just compiles mmm close-ish Oh because only gets the to close-ish Oh because only gets the to close-ish Oh because only gets the to have to do some summing to keep track of it okay so dad actually mmm I didn't wait for this yet but I'm I guess this is relatively easy to generate some test cases from when I say that and I turn that's two more paths like a no obvious case also so I'm going to say number Oh No a good number should contain all the numbers that is before it that is what you require a 75 mmm-maybe does somebody in this here but mmm-maybe does somebody in this here but mmm-maybe does somebody in this here but that 24 should be three why is this 100 cuz I do it in the other order hmm I should yeah maybe I do need a segment you know I was trying to do something maybe weird with know about but you need all the some of that thing I was thinking of the worst what I consider the worst case but that's more related to I mean what I'm doing is way much related to oh is but maybe the that reduction in my head doesn't quite work yeah mm-hmm haven't done a segment yeah mm-hmm haven't done a segment yeah mm-hmm haven't done a segment ribbit well I think even just a regular tree maybe should work I mean you said you what I do except for I would want to for each node would contain my god oh why use up the sub tree right but something like that don't really have a if I were kind of implementing a crazy tree myself I'm just trying to think then the existing data structure that I could use I think actually like a regular binary tree is good enough maybe but or a balanced one which requires me to create a lot of okay so lower valleys don't you know is there something similar in sequence for us or is this just literally like a DM for mandatory segments we even good enough I don't know can I use this no I mean whatever hacks I am doing it's gonna be slower than whatever I'm doing it's only slower than Onaga and it's gonna be like some degenerate case with n square and that's why I got me to slow that's most of my concerns so the 24 switches for because this only does in one direction maybe I just need to heat it up and do it that means I didn't waster more than 20 I know I need to me okay maybe it's time I learned how to do a segment really world and no wow mr. OH I think one thing I'm trying to think it's also where the map has like a sort of because it was ordered maybe I could do something to get to offset is there someone like that no am I just dreaming but then that case of emoji map but that's fine let me play around with it look see if that does anything all that it just gives me nonsense nope okay for a tree elevator that's not a thing okay to multiset I'm trying something real quick actually just the same like tears nope mmm alpine area index tree I actually don't know that was remember hynerian dextry hmm I should just looking up multi-set things because they just get implemented into a binary search tree but I just it doesn't I guess that you to this right finally index tree let me go this real quick I guess it's time for me to learn something new today and maybe y'all can learn with me okay have the train not touch this in like 15 years so is it the thing where you take like the square root in a prefix way or something like that in the least significant bits like half of it in and in the layer and then the other half and you know that's something else okay I mean this is a very simple see all the bits except only significant one how does that even work the suctions factory is disputed well I guess I should not use this code in production but okay I think I'd do some understanding before I understand why this is the case you're okay I'm ready this is straightforward I guess I'll play around dad okay I don't need C++ for this let's dad okay I don't need C++ for this let's dad okay I don't need C++ for this let's go okay I think I have tied you there so one thing I do try to do when I'm learning something new is that I'm trying to understand it and then do the coding excuse me independent of it but uh cool all right X and whenever I understand this plitvice create this craziness cuz I guess because negative of it would be the two's complement so because for a second I thought it münster inverse which is not true because it's to complement okay I guess I'm expense okay I don't have a no way mmm what do they call it usually it's just like an index sorry okay that's my don't members it's called any bit okay it's quite lookup I know how do I initialize this yeah I did a lot of questions here what a size how does this even work I guess size is just the number of bits right prime expense we have to know how to do this and a little bit but let's say 64 bits then which one is that again I think I want to look up first actually that's fine I was it fine and that's just taking every bit and then summing it right and it's just this reminds for the XOR stuff I've been reading actually science doesn't make sense I have to figure it out and now yeah okay then you could keep going to the next time I would spit okay and then just return right yeah this is painful okay and then this is the opposite where oh yeah because now we want every bit to contain DeVry you all right something like that I still notice Isis yeah okay I mean now so now we have a look up first initial size my point I guess I should just maybe +1 and I guess I should just maybe +1 and I guess I should just maybe +1 and because you want to have it on the end one and then now we want to burst her away first input and then I guess but to find it for us someone like that is that reasonable it's really been like 10 15 years since I've done stuff like this I really have to I don't not as fun too many fundamental sounds it but these things on interview has to be technically she should terminate very nice this is what is this white in pipeline I don't know how's two's complement is in pipeline especially if it's a pic into something but hmm no man I just start with mindfulness question she resumed away eventually doesn't really get put anything so don't mind that LSP thing as well oh maybe I didn't maybe I just implemented the tree and didn't do anything because okay now let's say we have to like now we have to a Fenwick tree or the binary index tree up what does that mean now had to convert this to action I think this requires more understanding of different victory whatever to do it so basically ask me to calculate the partial sums of the first the expert because we want the cumin if some of paisa from zero - Wow paisa from zero - Wow paisa from zero - Wow can it be negatives I'm gonna say / - 5 can it be negatives I'm gonna say / - 5 can it be negatives I'm gonna say / - 5 or something but that's it he'll probably index maybe we need to be indexed yeah because otherwise this is just weird because it could actually have given negative numbers which none of this really makes sense okay I was going to say back up again bread you want a sedative just unique and what so small so now this is in sorted order and then I'm gonna say no to index that's fine right then when we can't wanna find mmm have an infinite loop somewhere family - it's not out stuff for a second you know God so the adding is doing something weird now I use enemy don't touch me okay that's also confusing though hey everybody I'm still with me but I welcome to fresh earnings with I mean I guess that makes sense if index is zero then does never get a bit down to one index this yes sir I don't never be big enough okay well you know what they say some answers better than no answer I don't know that's actually true but outside to researched have be worse but the obvious it is as well okay this isn't we just don't want to add num1 number huh you just push one because just see you indexed you know they're just right here know what no because now the finest one okay hmm because it's supposed to be trying to be too clever with this one okay no I mean actually I like this little bit better in that just it's more specifically that uh it's finding all the numbers that are smaller than it so okay that's your push okay cool ah yeah I think they do this one for 40 minutes which is in I guess not bad for a heart form that I didn't know how to do in an album that I'm not very familiar with yeah definitely an interview and you need to put pull to Wikipedia you're probably already having it yeah me over I say let's say I was an interview I would say yeah we start there and square album which is having trivial there's nothing about it just two for loops and I didn't have any optimizations I feel like we could talk about the binary search tree that's what I was kind of thinking of but I mean but if you have just like a regular binary tree where like you know a binary search tree but not necessary balance then you just kind of keep track of whenever you're in certain element then you could keep track of kind of the some of the supplies in that tree and then allow you to kind of do friends in theory like and because you just go through the tap but because of you tended to generate situations they'll be ten square and I'm sure that the generate situations in the case so I think if you do a balanced search yeah balanced binary search tree then you could probably do an N log n which is maybe fast enough but I'm not doing that on an Indian who seems impossible yeah so I did this I think it back in the day I we just can't find them index tree or something but I well I mean I'm sure yeah I don't remember when I learned about it but um yeah using this data structure so that you could kind of figure out bit by bit you could look at each I mean I yeah I mean if you want to learn more about what did I click on okay yeah we keep in our go better I'm sure that people have win more things about index trees but uh we have it they just basically each bit it just allows you to kind of stored like for you to are you increment in this case one two to store this sum of each I got it cut like you can think about it like a tree because in place because in each like binary number there's the zero and one will correspond to different paths to take and then you just sum up all those segments to kind of get just some of the prefixes but uh and because they're you know like and like in digits want to knock an update time and find time I'm not I don't beg good exploit away well oh yeah I probably need to do some fashion up I it's been too long but yeah I mean it seems like if you work for me over and you would get this very quickly I don't think yeah like I don't know if I welcome it I don't know this is one of those things like groove I wasn't into it these are all the things I would talk about but not necessary self to be honest I don't even think like I think sometimes if you can't apologies ago unlucky I think I also need to also go back to secretary I also know segment tree in theory but not an implementation and I think the first time you do anything like that it's gonna take a while so maybe it's something that could practice offline as well just a little bit well yeah but or a punish problem to kind of we can go some of the old data structures they haven't done a while I don't I've been both segments free and fenwick tree or by finally index trees kind of things in the class of things that you know learn if you enjoy algorithms and if you have fun of it and you know you easy to kind of yeah like you learned a couple of times or you do a couple problems and where you try to retain it for a while but that said it's probably like you were to prioritize things to learn I would not prioritize this near the table for example for kind of maybe obvious reasons like sometimes you just have to accept that like you know in the fat tail of things there's just gonna be some percentage of things tied you know you just don't have time for you but you know like my word too like if I have a fixed amount of time and I have to choose between you know showing up on maybe time I'm reprogramming or maybe even like greedy algorithms and just like be really good in explaining them that maybe that's what I would do instead where versus like you know what in the off chance then we see problems like this that's what I would say I mean it's a hard problem so I don't know how reasonable is to expect that I do don't think I have known any of my colleagues kind of ask these kind of problems when segment trees or whatnot but things are getting more difficult from what I understand so I don't know but yeah not to me I would prioritize learn of you enjoying it and have fun of it and or if you mastered everything else but yeah I mean reason my undergrad class this was not tired but I had a ticket I had to take Grandal courses for it
|
Count of Smaller Numbers After Self
|
count-of-smaller-numbers-after-self
|
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
327,406,493,1482,2280
|
64 |
64 minimum pass sum from let's go given and by n grade filled with non-negative numbers find a path from non-negative numbers find a path from non-negative numbers find a path from top left bottom right which minimize the sum of all numbers along the past you can only move either down or right so let's see how this question can be done using this grid in this example the best way to get from here to here is uh going through the orange path and we can only go to the right and we can go only to the bottom let's see if we can go any other path and if we can get a better result let's go from here to here it's going to be 1 plus 1 is going to be 2 plus 4 is going to be 6 plus 2 is going to be 8 plus 1 is going to be 9 is bigger than 7. how about here 1 plus 3 is going to be 4 plus 5 is going to be 9 plus 2 is going to be 11 plus 1 is going to be 12 which is very bigger than 7. so and now how can we solve this problem efficiently for solving this problem we are going to use dynamic programming and we are going to define a grade the same size of the grade that we have and we are going to fill out this grade from the bottom cell to the top and we are going to get this field with the four conditions and we are going uh to return the result at the end so how we are going to fill this we are going to find the minimum pass first thing we are going to fill this cell and then we are going to fill these cells the bottom and the last row and then the last column and finally the rest of the grid and what we are going to return is going to be this cell as a result so let's see how we can do that we are going to have four conditions as i said we are going to fill this then this and then the so we need four conditions we are going to define a condition for the last cell we are defining a condition for the last row we are defining a condition for the last column and for the rest of the grade so let's go through these um for loops and see how we can do that we are going to have two for loops for iterating over every single cell but we are starting from the last cell so we are it which is going to be index two by two so it says um like the first one it says if the i is equal to two and j is not equal to 2. the second one says if j is equal to 2 but i is not equal to 2 and the third one is says if i and j boost are not equal to 2 and the last one is says like normal if these conditions are not correct you should put that value in that grid which is going to we are going to put one here right and so we are done with this if condition which is just like this condition for c filling this cell now we are going to fill out this row uh by using this if condition it's gonna this if condition is going to be valid because i is equal to tuned right now and j is equal to one so it says uh as long as i is equal to two and j is not equal to two we are going to feel uh these cells by the value that we have in here in the grade right which is 2 plus the value that we have in this cell so 2 plus 1 is gonna be three and now i is two and j is uh j is zero so what we are going to do we are going to put this value plus three is gonna be seven here we are going to put 7 here now we are going to fill out this so what we are going to do we are going to i is going to be and because we are done with the last cell so what we are going to do we are going to say the value that we have here plus the one that we have uh before so it's gonna be two and then one plus 2 is gonna be 3. now we start filling these cells so what we are going to do we are going to say the value that we have here plus the minimum of one of these values as you see we have the minimum of these values here so five plus which one is the minimum two or three two plus two is going to be seven and then we are going to say one plus minimum of uh seven and seven it's seven plus one is gonna be eight and then we go for this one three what is the minimum here seven or three is going to be three plus three is gonna be six and one is going to be plus the minimum of 6 and 8 is 6 is going to be 7 and that's the result that we are going to return at the end from the dp grid the time complexity for this uh solution is m by n because we are going to iterate over every single value that we have in this grid and the space complexities and by n as well because of the dynamic programming grid that we are using thank you
|
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
|
95 |
difference welcome to follow up let's have a look at problem 95 unique binary search tree is 2. so here we're going to explain a solution based on recursion so here we are given an integer in so we want to return all the structurally unique binary search trees so which has exactly nodes of unique values from in the event to n so both the two ends inclusive so we want to return we can return the answer in any order so here in the two examples in example two so this just one node so we just return to one tree itself and in the first example n equals three so the corresponding trees are given by this one and this uh this five so basically you can see uh the root nodes this here is one here's two here's three right so um here the constraints of the following the N is bounded above by eight right so n is at least the web so with that said basically we can look at the coding part so for this problem actually uh the strategy we use for sure is recursion so the reason that we can first think of recursion is that so the tree binary tree or here in particular um a binary search tree right binary tree or Banner search tree here it's a recursive uh data structure abstractly the tab right so it's actually defined in a recursive fashion so that's why um we can first think of uh recursion for this problem so this problem we are in this problem we are dealing with band research tree so we need to know binary search property right binary search property ah so property is that so the left subtree to know the values so it's strictly less than the root value strictly less than the red sub tree values so this recursively holds for each subtree each and every sub trees so this is the binary search property so last we noticed that so we can iterate over different root values and then we can construct the binary surgery recursively so here in this video we first we are going to write a help function which basically generates the unique Banner research trees within a range and then we just call that function so with that said first let's look at the hyper function so we can see this is the utility function right so let's define let's just write it as F so work accept left will accept a rate so here this F asically generate or unique better search trees with values in the bond with node values him to close the Intel L and R in other words both L and R are inclusive so as for writing recursion so we know that we need to have a base case so here the best case is a following if L is greater than R so in this case we return null right so here we want to return a null tree and another case is that if L equals r so in this case so we just have one node a single node so we return this tree so we return this three node so the value will be you can write L you can write R same thing right so this is the base cases and then we want to make self call of this function and the mid connection with and the walk towards the base case so here let's initialize a result variable so it's an empty list at the very beginning so we want to return its final state so here we can choose different numbers in between L and R as root values and once we determine that root values we need to construct the left sub tree using values less than that root value and construct red sub tree using values greater than that root value so here we are going to consider for each possibility so for I in range so we start from L and ending at R so we write R plus 1 here and then let's first construct left sub trees left side F going to be F so we're from L to I minus 1 because that's the definition this is the inclusive right so which needs this thread value to be strictly less than the I we choose and the right side that's going to be now I plus 1 and up to R right so notice that due to the return format this left stage and the right side are two lists consisting of binary search trees and then we are going to iterate so for l in left side and the 4r in right side so we want to connect things together so we are going to consider the root so this is the tree node so the value will be I right this is the root value and then we are going to choose is left to be the left so here let me use uh left subtree um red sub tree to avoids using this IO and R with the bound rate so left because left sub tree so this way we construct a root node and it's left sub G is given by this here and the rest of G is given by the r sub G here and then we can add this until we append this to the results and then we return the result state so this is the hyper function so this is essentially doing the call work and for us we just need to call this function to uh return the house possible banners to choose so here the bond is from one to n so we write it one and in here so this actually forms a solution format to this problem so before we make any comments let's first do a test it passes the first example now let's look at the generic case yeah it passes all the generic cases so here as we mentioned earlier beginning so this problem is related to binary search tree I am a particular Baner G so S3 is a recursive abstract data type so when we maybe meet problems related to trees we can first think of a recursion to see if the problem suits the recursion technology or trick then for this problem here it's important to notice the binary search property so once we notice this binary search property and then constructing all the structurally unique better searches is basically very straightforward so with our stage basically that's about it so notice that there's a similar problem as unique Banner searches and so you can try that and if you can do this problem then the this one unique binary searches should be no problem so with that said thank you
|
Unique Binary Search Trees II
|
unique-binary-search-trees-ii
|
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 8`
| null |
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
|
Medium
|
96,241
|
1,359 |
Channel on Jhal Hello and Welcome so today we will question 1359 account all valid points delivery option is enjoyable what has been happening so basically it is given that so I will be Android this and at that minute its pickup and delivery will have been done okay means years was If it is opposed then its pickup has become even and life has happened and there is a golf condition in it that the pickup condition has gone 2. It is also natural that first you will pickup the model and then you will deliver it. Okay, so how many possible competitions can be made with all its permissions. If he is telling you then you understand that we will make it a cashier that you interesting our basically a way, it seems that it is a medical termination information question and if this [ __ ] grows and if this [ __ ] grows and if this [ __ ] grows up then there will be a dip in it too, okay let's see. Have you got DP or not? How, what will happen, Sapoch Karma is given here, very happy one on even, comedy one is on one stomach, this is also there now and one leg is given by you, it is Pintu and Dr two, everything is fine for him. We have vetted his permits, okay, whatever permissions he has, let us consider him as one, okay, support his answer, we have accepted that he has, we have accepted and supported that he will be one, okay, let's do this. X is that this one let's go man all Anjali none this explanation is now with you but here comes the new foot what is the name of that three and D3 speed was there what is your yagya if support you have to keep the smooth P3 there At the end, if you have to replace the pitta, how much space is there? One, you will either keep this here or keep this ready, keep this and either you will keep it here. Okay, so if this, how much if how much for the countries, here at the end, there will be a virtuous entry here. But how many places are there 123456 that they * Support answers-3 that they * Support answers-3 that they * Support answers-3 Fixing will be made so N minus one or any other sum or plus and ok how much of this is yours * - Naa aa naa hai how much of this is yours * - Naa aa naa hai how much of this is yours * - Naa aa naa hai jo yours to * jo yours to * jo yours to * 110 - World ok this Done, now I have to 110 - World ok this Done, now I have to 110 - World ok this Done, now I have to place the video here, if you can place the position of DTO, then there is an element here too, can come here, so this book. Ka U into a PAN, it is okay, this is your wallet but in this it is given in another practice that the delivery will always happen after pick up, so there will always be two options at the door, if not, then stop it before that or after that, the truck. There will be a notification of both of them, what will you do, you will divide the other, one is white, there are two options and you always have to keep the delivery person ahead, even I have understood in hand, okay now school A, as many permutations as possible. If you were of this, you will multiply that by that because you could understand it and maximize it, then That it will become normal, okay, let's try to find it is given in it that it is a very trend power, ninth class seventh, meaning the treatment will be male, what to do in it, long request one has to be taken, okay and we will take the mode, modems stop time. ki power loot 56789 yoga in india vs hai ab kya karna hai aur it is cost vs ricky high school student ips kar diya phir kya karoon tum rate school dress to m2di the finance bill * kya aaye tension aur divided over june 2012 * kya aaye tension aur divided over june 2012 * kya aaye tension aur divided over june 2012 add and no It is done, now what will you do with it, you will take it for MOT, what will you do in the end, will you return it, is the sass correct, let's see the answer is right or wrong, sleep will be wrong here because here we will have to do type casting, otherwise here we We will do this so that these people can see how much limit has been given for it, we have given the front key, we will see whether the find essay will come or not, will it be okay, let's run it and see if gas basil comes, then we will be right with you about tomato. Let's see, it's okay, it's done, okay, seriously, dinner 13 and if you like the content, then do whatever you want, I will keep the messages coming, like, share, okay bye.
|
Count All Valid Pickup and Delivery Options
|
circular-permutation-in-binary-representation
|
Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
|
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
|
Math,Backtracking,Bit Manipulation
|
Medium
| null |
406 |
hey hello there uh today's liquid in challenge question it's called q reconstruction by height suppose we have a random list of people standing in a queue so since it's killed there's the notion of franken front and back each person is described by the pair of numbers h and k h is the height of the person k is the number of people in front of this guy who have a height greater than or equal to h and we need to write an algorithm to reconstruct the queue and as an example we have six people seven zero four seven one so basically uh the if we look at uh a random person six one that person has a height of six and there is exactly one person towards the left that has the height equal to or larger than six the correct position this guy is here so looking at the guys before him or her there's only one guy who has a height of seven larger greater than or equal to six so this guy is definitely in the correct order just looking at him uh if we look at another present four there has to be four person with height equal to or larger than four before this guy everybody before him is height five seven five six so it satisfied the order requirement constraint or requirement whatever so let's think about how we are going to solve this if we just manually do this in ourselves so obviously something i uh we would do is to just grab a person from the you know set of people and try to place the guy into the right location so we're gonna have a empty kind of cue here uh have six slots here so all we need to do is uh grab a person at the time and try to put the person into the right location so the order that we grab people is going to be very important uh what kind of order should we do if we just follow this random order it will not be nice because we don't know what kind of person we have already placed and we don't know what yet to come so it's going to be difficult for us to reasoning about the number of people should have uh you know should stand before this guy and in order to determine the guy's correct location so obviously we want to do this in some sort of uh sorted order so let's say that if we sort people by the increasing order of the height and that gives us a very nice property if you look at the presence of high five and we are currently looking at a position try to find the location to place that guy we know everybody who have a height that's less than four less than five you know one two three four have already been placed into the correction corrected slot so if we do uh from left to right uh maybe some four guys three guy have already occupied the slot and the guy we are looking at has a height of five and you require uh you know two people to have same height or higher tools before this guy in the final q so what we do is to just leave this guy from the beginning and try to look for the right position towards right if we find an empty slot that's not we cannot occupy it because we have to reserve that for someone who potentially have a height that's uh equal to or higher than this guy but since that we reserved the slot we know that we can decrement this counter that position has to be filled by someone who has the same or higher height so we then move forward we saw a guy with high four we don't care three we don't care another empty slot we decrement this becomes zero but we still have to move on because that location has to be occupied by someone of high five or higher but definitely not this guy so the first empty slot we find when we are sure we can there has two people who has a height equal to or higher than this guy that's the first that's the location we should uh put this guy here so just in summary what we do is to allocate a empty queue and uh and just uh try to place people in their uh according to their sorted height ordering uh for every person we start from the beginning of the queue and if it's empty slot or if it's a actual place that already placed the person of the same height that satisfied the constraint the requirement about the number of people before him so we decrement that requirement once the requirement counter hit zero and we reach a new empty slot that's the place we place this guy uh so this leads to a you know nested four loop kind of a code it's going to be square time and the sorting is n log n so it's uh less than square so the total the uh the significant runtime is in the placing of people rather than the sorting but the sword gave us a nice property so what we're going to do is just going to initialize a queue which is just empty you know empty slots now we're going to have this to be exactly the number of people so everybody has exactly one location to go to and we're just going to sort the people for their height and requirement of number of people of the same height or higher we uh keep track of the number of people that's uh greater than or equal to this guy's height that's uh in front of him uh if there is a initially this is zero and we enumerate over all the locations if this location is empty or if there is a guy here but his height is equal to the guy we are looking at we can decrease it or we can increase this meaning that uh we definitely see one that's greater than or equal to this guy's height and if this number is equal to k and the location is empty what we can do is to place the per place this guy in into that slot and if actually place to the guy we should uh break uh and just skip to look at the next person so yeah in the end we should just return this cue uh it should be it uh let's quickly check if we have problems uh allocate enough space for the people according the same number of slots for the number of people we saw the people based down their height also if there is tie with sword on k and we're just going to look at the one person at a time we start from the left towards right we just keep track of the number for a slot either reserved or occupied by the person of the same height or higher so if it's empty slot or if the person in the slot has the same height we increment this or decrement you know if we set this to k at decrement testing for zero it should be the same thing uh if we have enough people of the same height and we're looking at the empty slot we just put the guy into that slot so yeah which looks good nope okay i'm so sorry all right let's submit this all right so this uh this is the square time algorithm and you can definitely see this here it has a nested loop here and the sorting is analoging yeah so that's uh this question in square time and uh realizing using processing people using sorted order and uh and just based on this definition pretty much oh you know what i think of i can think of another way to solve this let me talk about this so notice that if we do this in the reserve order from the highest to the lowest for seven zero we just insert that to the zeros location if the empty the real this is to using a uh fixed array but if we are thinking about in a linked list that kind of thing we can insert at each location and the runtime doesn't matter the runtime is still n log n because for every insert it's in i'm ahead of myself in explanation i can just grab if we're processing from the highest high to the lowest we see seven zero it's going to occupy a 7-0 here it's going to occupy a 7-0 here it's going to occupy a 7-0 here if we find seven one that's going to be inserted at the ones location then we process into the person of the second highest height six one the ones location is occupied by seven one so we just insert that guy here and then we processing on the height of uh height of five uh we got five zero we put this out here and five phi two zero one two so insert the guy here and four so one zero one two three four this should be the order right is this the order yeah it is all right so yeah it appears that uh if we do this uh from the highest to the lowest the code can be simple but the wrong time doesn't change so we're just going to have a queue this time it's a linked list for hk and for people in sorting order we're going to sort by the height in the reversed order so that's that do we want to sort this based on that too oh yeah if we're doing that from the highest to the lowest we want to process phi 0 before phi 2. if we do 5 2 before phi 0 the order gonna mess up so we have to put this here what i'm going to do is just insert that into the right location oh no uh list objective cannot be interpreted as an integer sorry it's index and volume we inserted at this location the value which is the prism okay yeah so it's working too uh but insert here you know it's sort of like a linked list we have starting from zero and just uh jump uh p1 uh the number of uh steps and find the insertion location to insert this person so it is still in square time but the code is simpler all right so that's this question today
|
Queue Reconstruction by Height
|
queue-reconstruction-by-height
|
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`.
Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue).
**Example 1:**
**Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\]
**Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\]
**Explanation:**
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue.
**Example 2:**
**Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\]
**Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\]
**Constraints:**
* `1 <= people.length <= 2000`
* `0 <= hi <= 106`
* `0 <= ki < people.length`
* It is guaranteed that the queue can be reconstructed.
|
What can you say about the position of the shortest person?
If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
|
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
|
Medium
|
315
|
1,846 |
so hello everyone today we will be solving the lead code daily challenge problem that is uh 1846 maximum element after decreasing and rearranging so we will be given an array of positive integers uh we have to perform some operations on the array so that it satisfies the given conditions we are given the conditions the first element should be in the array should be one the absolute difference between any two adjacent elements in the array must be less than or equals to 1 we are also given that every element in the array is equal to or greater than one so we can perform two types of operations that is decrease the value of any element of the array to a positive to a smaller positive integer or rearrange the elements of the array in any order so uh we have to return the maximum possible value of an element in Array after performing the given operations to satisfy the condition so our approach will be uh we will first of all sort the array uh we will check the first element if the first element is not equals to one we will set the first element to one and then we will iterate through the uh we will iterate through the array and check if the difference between two adjacent elements is greater than or if it is less than equals to one or not if it is greater than one then we will set the greater element to the smaller element Plus one and then we will get the maximum uh then we will get the array that satisfies our condition we let's start coding them so we first of all sorted the array with the ARR do sort function then we check if the first element is equals to one or not if it is not equals to one then we set the first element to one and now uh we added to the array since we have to get the maximum element we will add one to ARR of I we will add one to the I element in the array to get the I + one element in the array to get the I + one element in the array to get the I + one element so now we will check our array so uh perfect so we have got the array as 1 2 so here uh the adjacent elements are the so it satisfies the condition that the first element is one and the absolute difference between any two adjacent elements is less than or equals to 1 so we have the first element as one we have the second element as one so the difference is zero for the third element we have two so the absolute difference is one and for the fourth and The Fifth Element we have difference as is 0 so it satisfies our condition so our array is perfectly correct uh in the second test case we have uh got our array as 1 2 and three which satisfies our condition as the first element is one and the difference between adjacent elements is also less than or equals to one for the third array we already the array the given array already satisfies the given condition so now we will return our result we have to find the maximum element so we will get the maximum element as Max of AR and we'll return our result yeah so we got our result correct for every test case so now we'll submit it yes so our code is correct
|
Maximum Element After Decreasing and Rearranging
|
maximum-element-after-decreasing-and-rearranging
|
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109`
| null | null |
Medium
| null |
378 |
hi everyone welcome to tech geek so today we are back with the daily lead code challenge problem that's skate smallest element in a sorted matrix apparently this is a medium question of lead code that's a medium 378 if you ask me this question is quite common in your always and specifically your pr one so if you're appearing for a good company that's basically a product based company or the dr2 of any service based company then this question could be asked to you so uh it requires nothing just a simple thought if you know how to go up because we have been given a condition that the array is sorted okay now let's see what the question has the question says you have been given an n by n matrix okay in which each of the rows and columns are arranged in a ascending order okay you have to find the cape's smallest element in the matrix okay smallest element in the matrix note that it is the kth smallest element in the sorted order not the case distinct element that means there could be a repetition uh we'll explain you this particular and just explain you uh let's go forward and then in the next page we'll explain okay they have been given some complexity that if it's better you can go over the memory complexity of order of n squared okay let's take this matrix first let's take a 4x4 this is a four by four matrix that we required and let's write this 9 16 20 and okay now you can see that if you go around maybe down or you go this way each of them are arranged in a singling order like one three five nine one two five seven again three four so they are not violating so this is what the format says and you have been given some k let's say four or eight anything that's given to you have to find the k smallest okay now see first of all the thing comes you cannot take if it's code you cannot directly take this or you cannot directly take this time go with same but or any way why because when you arrange them in ascending order it won't be like this if we arrange them in ascending order it would be one two three four five again five okay one two three four five then after five we have seven then eight nine and so on now if k was four one two three four so four was our answer but if k was eight five six seven eight this was answer now why did there was a line that stated that it should be k smallest element in sorted order not okay distinct if we take 8 distinct in that case this would be an answer so for the fourth one this would be correct but for the 8th 1 5 6 7 8 9 should be the answer so that means even if there are repetition account won't change so this should be fifth and there should be six in that case okay so this is the thing they meant to say now comes to the thing how we will arrange them in ascending order because if we have this then obviously we can do it so for this concept we have a very beautiful thing in our data structures that is a priority queue okay we have a priority queue so that's what we will be using we'll run a loop for each one of them we'll store them in the priority queue and once we store them in priority queue we check until the priority queue is empty that means that size is greater than zero we'll run the node and start dequeuing it the kth value that means once we reach the count that's w equals to k that is what is the result that's required okay so whenever you do this in a priority queue so you as the name suggest a priority okay so you need some sort of priority to be maintained so as you know it's a cube okay let's see if you talk about the priority queue you know it's a queue first of all though q follows a fifo thing first and first out okay but as it says it's a priority queue so it will be done on the basis of priority and not the first in first out okay that's what comes up so that is what we'll be using okay let's see how things should go on okay first let's look at the code i'm saying where we follow the process because it's just an easy implementation of priority define your priority queue run and open the matrix and add this in a priority now you have a count and you have the answer is actually that you store the other side no count while your priority queue says while uh this queue is not empty that means it has something removed now the move function is being used here so we'll remove the element here okay priority queue we'll be removing that particular element and then storing it in some particular value okay so this remove function is actually that it will remove the single instance of that particular element only if it is present okay so we'll be removing this element first of all we'll be storing it in this remainder and we'll increment the count now if we've incremented the count if we incremented the count that means we'll be checking if the count is equals to k if it's the smallest one somewhere we got that smallest one that means we got the first smallest or second smallest first we'll get the first smallest and the second smallest and then so on so as soon as the k comes to be four or eight whatever we want you store it in this answer and now you can do one more thing you can add a break also here if you want so that once you have the sunshine then move out and print the app i'll just show you one implementation that's easy if possible because that will be more beneficial to you okay as we said for the priority queue let's add few elements to this priority and then we'll check 41 7 and 99 using the priority queue dot add function once you did so how would you know that it's being stored in the priority view right you don't know how it's being stored so it would be stored somewhere like this 2 7 14 41 and 90 so that's what it will be stored now when you lose the remove function so for the first remove function this shall be removed for the second this and so on so the same way when you wanted k equals to four so the fourth smallest here so until the count is equal to four you keep on removing and print this as us this is the concept that we are using i hope this is clear how to be done if there's anything then please let me know look at the solution it's quite easy even if there's something that's missing out you let me know in the comment box i'll be there to help you till then keep falling
|
Kth Smallest Element in a Sorted Matrix
|
kth-smallest-element-in-a-sorted-matrix
|
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
| null |
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Medium
|
373,668,719,802
|
35 |
and welcome back to the cracking fan YouTube channel today we're going to be solving lead code problem number 35 search insert index let's read the question prompt given a sorted array of distinct integers and a Target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with Big O of log n runtime complexity so let's look at an example we're given nums here which is 1 3 5 and 6 and our Target is five so obviously five exists in the array and it happens at index two right because this is index 0 this is index one this is index two and this is three so five occurs at index two so that's why we return two here otherwise in this example where nums is one three five six again and our Target is seven obviously we can see that seven is not in this array so if we were to insert it in the sorted order it would go at the very end because 7 is the largest element out of these ones and what index does that occur at so 0 1 2 3 4. so that's how we got four so it's quite simple to solve this question by just looking at the input and kind of driving it with our eyes but unfortunately computers don't work this way and we're going to need to write some sort of algorithm to actually implement this Logic for us so let's think about how we could solve this in you know a way that actually can corresponds to the requirements we have here okay so we looked at some basic examples and saw how straightforward it was to actually solve them by just looking at it but unfortunately like I said computers don't work that way so what can we use for our solution well we want to use a binary search and here's why in case it wasn't obvious to you for the first thing is that we're given a sorted array right and we're looking to search for the index of a given value so we're basically trying to see if a value is inside of a sorted array next we're told that it must be done in log and time so the only algorithm that will actually let us search through a sorted array in log n time is going to be binary search so for one if you guys are new to lead code if you're ever given a sorted array and you're searching for a value or trying to find some index where a value might occur at immediately think binary search right but how do we actually pull off this binary search well typically we set we have a two pointers one uh the left pointer will be initialized to the start of the array so that's going to be index 0 and the right pointer is going to be at the last element of the array right so this is going to be the length of nums minus one so in our case with this example it's going to be at what right so this is 0 1 2 3 so the length of nums is four so obviously the last index is 3 right so what we're going to do here is We Now set a while loop right and what we want to do is basically move the pointers down until we either find our element or basically the pointers cross over each other at which case we're done because we've searched through the entire array and the way that we're going to do this is with a while loop right so we're going to say while left is less than or equal to right what we're going to do is we're going to calculate the midpoint so we're going to basically see which half of the array we want to search so we're going to say mid and midpoint is always going to be the left plus the right integer divided by 2. so in this case 0 plus 1 integer divided by 2 is 1. right because it uh zero plus one divided by two is 0.5 which rounds up to one so two is 0.5 which rounds up to one so two is 0.5 which rounds up to one so we now have uh you know that our midpoint is going to be this three here so what we want to do is actually check uh is the value so we'll say oops let's kind of clean that up we're going to say nums of whatever the midpoint index is does this equal to our Target right does it equal to the Target so we're going to check does 3 equal to 5 it does not so that means that you know we have missed the mark with our search here but let's think about what happens right so we have one three five and six so we know that the array is sorted right which means that if it's sorted then everything to the left of three must be less than three instance 3 is actually less than our Target we will never find our Target to the left of three right because if our Target is greater than 3 and you know everything left of 3 is smaller we never have to search this half of the array again because the value will never be here it has to be somewhere on the right side because those values are greater than three this is really important for understanding binary search so if it doesn't make sense kind of think about it again remember that everything to the left of three is sorted because we're given a sorted array and if 3 is already too small then all the elements to the left of it will be smaller and all the elements to the right of it will be bigger so now with that in mind we actually don't need to search this entire half anymore we can search from three onwards and actually we already searched three so we can now move from basically five onwards and pretend like this is our new array right so in this case since our nums doesn't actually equal to the Target and because our num is actually less than the target what we want to do is our left pointer is actually too far left there's no point of searching anything else so what we're going to do here is our left pointer is actually going to now equal whatever the midpoint index was plus one because we already established that 3 is not the target therefore we want to move on to the next one so what is this index so 0 1 2 3 so now our left pointer is going to move to 2 right so we're going to go through our while loop again because 2 is still less than or equal to 3. so now we're going to recalculate our midpoint so two plus three divide by two so this is going to be 2.5 divide by two so this is going to be 2.5 divide by two so this is going to be 2.5 right 2.5 and this is going to essentially 2.5 and this is going to essentially 2.5 and this is going to essentially um round up right so we'll go to three and we'll check our value right so we'll go to 6 here and you know does 6 equal to 5 no right because it doesn't equal to five again we can play this apply the same logic right any numbers that come after six are going to be too big if 6 itself is too big and everything to the right of it is greater than six then there's no point of searching this array so we can simply search this way to the left right it has to be somewhere uh you know here and luckily there's only one element left so we can kind of see that's where it's going to go but in theory if there was more elements we would want to then search from wherever our left is to basically mid uh since the midpoint is pointing here minus one right so now our right is actually going to move down one so it was currently at three now it moves to two so we go through our while loop again and we're going to see that uh 2 is less than or equal to two so we still continue so we're going to get 2 plus 2 for the midpoint divide by two so our midpoint index now becomes two and the value at the midpoint index is 5 which is our value here so we would return the value 2. so that's the case for actually finding it inside of the array what happens when the value is not inside the array so what we want to do in this case is simply uh let the binary search play out and either we're going to find it inside here or we're going to break here and all we need to do is simply return um the left so let's kind of wipe all of this away and kind of see how it's going to work with this example here and we'll walk through it kind of line by line just because this is um you know a question where I want to explain binary search quite well so let me just see if I can actually select all this and make it go away there we go oh okay that's fine uh how do we okay that's fine let's just geez that is getting messy apologies here okay let's kind of clean this up all right that should be enough space let's stop faffing around so we have one three five six seven F6 and we're trying to insert seven right so we're gonna set our left pointer to zero our right pointer again is going to be the length of our array minus one so this is three so again we're going to do um you know zero plus three divide by two so this is actually what 1.5 so this rounds up to 1.5 so this rounds up to 1.5 so this rounds up to um two here I think I did my mouth wrong in the original problem but that's fine it doesn't really matter um I can't remember if we round up or down but it doesn't matter uh anyway so we checked the index five so obviously five is less than seven and it also doesn't equal seven so anything to the left of five is too small we don't want to search it we only want to search from you know to the right of five so we're basically just searching this half here so that means our left moves to three so you know we'd go through our while loop because remember it's less uh left less than or equal to right so now we have three plus three divided by two for the new midpoint so obviously this is three so we're going to check the value at the third index which is the six does it equal seven no so what we want to do in that case we want to move our left pointer up by one um so the left pointer actually becomes four and now we go through the while loop again but remember the while loop is actually while left is less than or equal to four uh right and obviously four is greater than three uh so we actually break here and all we need to do is simply return the left pointer because now the left pointer will actually be the value that we want to return which is that index four so in the case that we break out of our while loop we just want to return the left pointer and we're good to go so hopefully that makes sense if you've never seen binary search it can be a little bit confusing at first kind of figuring out how we move things up but you know it makes sense intuitively you just kind of need to see it a few times and kind of wrap your head around it hopefully kind of drawing out the diagrams and explaining how you know if it's already too small then everything to the left of it is going to be even smaller and then you know the opposite is true if it's too big anything to the right of that value is going to be even bigger because remember we have this sorted array so let's now go to the code editor and type this up it's actually relatively simple to code this I think that the harder part is just kind of explaining this and wrapping your head around it but hopefully you guys enjoyed this uh you know a little bit more verbose explanation of binary search given that it's an easy question and some of you guys may be new to lead code and new to binary search so let's go to the code editor and type this up we're back in the code editor guys let's type this up and like I promised it's really not that complicated so let's set up our binary search variables so left is going to equal zero and remember right is going to equal length of nums minus one and now we set up our while loop so we're going to say while left is less than or equal to right and if this is the first time you're seeing binary search this is fine if you've seen binary search before and you're confused on why sometimes it's left less than or equal to right sometimes it's left less than right or you know some combination well the reason for that is we're actually searching for an index inside of the array typically when you're searching for a value inside of your array and you're going to return that value if it's found then what you want to do is left less than or equal to right if you're trying to move your index down typically that's when you're actually using left and right but that's for another time you can just keep this in the back of your mind if you're returning from inside of the array then you want to use left less than or equal to right and in the other cases you just do left less than right but again this is a bit more advanced let's kind of stay on track here so we've set up our while loop now we need to calculate the midpoint index so this is going to be the halfway point between our two pointers so left plus right and remember that we use integer division here because obviously if we get an odd number then we're going to have you know a decimal and obviously you can't have decimal indexes so we need to use the integer division operator to truncate that value uh down to an integer so we now have our midpoint index now we need to check whether the value at the midpoint index actually equals our Target so we're going to say if nums of mid equals to Target then we're going to Simply uh return that midpoint value because we found the value now if it doesn't equal to Target either the target is larger than our mid value or it's smaller because here we've just established that it doesn't equal to the Target if we're actually hitting this point here so let's do to the first case where nums of mid so the number at the midpoint is actually greater than the target and in this case it means that everything to the right of the midpoint is going to be too big if the midpoint value is already too big then everything to the right of it because remember we have a sorted array is going to be also larger than the midpoint so there's no point of us searching that far so we're simply going to move our right pointer down to the mid minus one and obviously we had just searched mid so we can use mid minus 1 to get the value to the left of it right there's no point of us using mid again because we've just verified that you know this didn't fire therefore this mid value does not equal to the Target the L the else statement here is going to be the opposite of this case where nums of mid is actually less than the target therefore we don't want to search the left half of the array so we're going to say left is actually going to equal mid plus 1. so our while loop is going to run and obviously either we're going to return mid here because we found our Target or our while loop will break because at some point right will actually be less than left so when this happens remember all we need to do is simply return left here and that will be our solution so let me just run this make sure no little syntax bugs came up and okay let me submit this and hello okay that was weird anyway it was accepted we can see that it works so what is the how do I go back to my code okay cool what is the time and space complexity well we're using a binary search here and we know that binary search is always going to be log n time right and also the question tells us that we have to do it in log n time so that's kind of like a hint of what you do there so space complexity wise you can see that we actually don't create any variables except for the left and the right pointer which are just integers and because of that it's just going to be a constant space allocation so that is how you solve search insert position hopefully you guys found this video informative especially for you guys that are new to lead code and uh perhaps are just learning binary search this is definitely a really good question because it's quite easy to grasp and it's really easy to kind of walk through the binary search you know line by line and understand how the variables are changing and how we're kind of moving our left and right pointers up and down so hopefully again you guys enjoyed this little more verbose video obviously it's an easy question this might seem like a long video but it was really just me breaking it down piece by piece so you guys can understand how binary search works anyway that's enough rambling because like I said this video is probably 20 minutes long if you enjoyed it please leave a like and a comment it really helps me with the YouTube algorithm if you want to see more content like this to help you with your lead code Journey then please subscribe to the channel otherwise thank you so much for watching
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,488 |
Hello Everyone Welcome To Disseminate Now That's This Video Channel And Asked Question This Account Good Notes In Binary Tree In Desperation Video Subscribe Definition More Notes Printed Subscribe Must Click Subscribe Button 9 We Were Best Friend Advisory Services Sample This 3453 The Good Road Tarzan Ki UNAUTHORIZED PHOTO VOTE AND NOTE SIR GOOD DAY SWANDAV HE IS QUITE SIMILAR IN DETAILS SUDHIR AND JOURNEY SUBSCRIBE Subscribe Hai So Let's Talk About The Richest What Is The And Subscribe 4,320 Subscribe Video Subscribe Must Subscribe Let's Move It's Electronic Hai What Is Life But So Far Away With Active 1.5 Video not Will not experiment in this select month Was left side what is wali sirvi agrasit and lord to do a good amount of laddu subscribe button adhir wa subscribe for not withdraw from the I will click on let continue wazir will not three and 6 what is the 20 minute besan ke laddu setting ko Hydration Will Treat The Best Celebrity Assets Best Celebrity in Rugged Look The Orders in the Native Witch One Adhir Video Please subscribe and subscirbe The Left Side is Water 300 Dieters Subscribe subscribe and subscribe the report of what happened decision defined and lap conferred To the number of voters in a tree and avoid traveling in a free mode on it and not subscribe The Channel subscribe Video Route Maximum Kar Do Ki Adwise Amazon Bhuke Wa Helper Third Point Se Left Side 1 Cup Maximum Loota Do Subscribe My Channel Se Pind Chh Ki Andhra Mein Is Updated On The Song Old That Accepted Time Complexity Based Approach Is Border Of An E Want Instituted After But In The East With Synonyms Of Value From This Thank You For Watching Video Subscribe Sirvi
|
Avoid Flood in The City
|
sort-integers-by-the-power-value
|
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109`
|
Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list.
|
Dynamic Programming,Memoization,Sorting
|
Medium
| null |
1,200 |
Hello friends so today I'm going to solve the minimum absolute difference question in this question we have been given an array distinct integers a r we have to find all the pair of elements with the minimum absolute difference of any two elements and return a list of pairs in ascending order with respect to each pair a comma B follow a comma B are from array and B greater than a b minus a is equal to minimum absolute difference so what is the idea in this so we have been given array 4 2 13 the output will be 1 2 3 4 because uh the difference of the two elements 1 and 2 and 3 and four is minimum so I will go I will going to subtract these suppose in array in example two array is 1 3 16 15 so I'm going to subtract the minimum which is s is 1 three the difference is two so that is the answer uh so what will be the basic idea in this that I'm going to sort the full array if I'm going to sort the full array what I will see that when if we sort the input three see example three if I sort the input three then the elements will become -4 10 - 4 3 8 19 23 elements will become -4 10 - 4 3 8 19 23 elements will become -4 10 - 4 3 8 19 23 and 7 and if If I subtract the consecutive two consecutive Pairs and then again move to two consecutive Pairs and I am and I'm am going to conclude the minimum sum and I will find the minimum sum among all such pairs so that is the basic uh idea in this so what I'm going to do first I will sort an array then I will find the minimum of the difference in the sorted array by doing consecutive difference of two numbers and when we get the minimum element among the absolute difference then I will search that minimum element in the whole array and I will save the minimum elements in an Vector of vector and then I am going to return this Vector of vector so uh so for this I'm going to sort my array so for this I'm going to use the best sorting algorithm that I think is the best that is bubble sort so in bubble sort what we do we basically just compare all the elements suppose if we have given a array of any four numbers suppose 1 4 2 3 then I will compare the 1 with four so is 1 is greater than 4 no then I'm going to compare all the elements and then I will compare four with two if 4 is greater than two I'm going to swap four and two and then I compare four and three 4 is greater than three then I will swap three and four at this what we get is 1 2 3 and 4 so we get the largest element at the last index of the array so that is how I'm going to sort the array so I'm going to run two Loop suppose this outer loop is walking through the array and the other loop is for comparison and if this inequality holds then I'm going to swp my elements and this thing I'm going to do and then this and this is the main problem vector in minimum absolute difference Vector in address of array then first of all I will bubble sort my array so it will sort my array then what I will do I will declare M as int Max because that is the maximum reference value for the for which I'm going to compare it and then by itating through a for Loop in the array and I'm going to added in my sorted array and I will find the M which is minimum of M comma AR of i-1 minus AR of minimum of M comma AR of i-1 minus AR of minimum of M comma AR of i-1 minus AR of Y so I will get the minimum element then the last task is to find all the minimum elements in find all the M find all the minimum m in the uh the two consecutive difference arees so what I'm going to use in this I'm going to use maps in this we know we all know that if any property satisfy in maps then I'm then I will store these elements in map like this so what I will do I will first declare an Vector of Vector in answer array then I'm going to trade through for Loop and if check if array of I + 1 minus aray of I is equal of I + 1 minus aray of I is equal of I + 1 minus aray of I is equal m then I will going to then I'm going to push back the AR I comma I + one in the answer and that will give + one in the answer and that will give + one in the answer and that will give me the all the answer elements that difference is M and that is how I get the vector of vector answer array and at last I'm going to just return my answer because the return type is Vector of Vector in so I have returned and you can see that when I will submit this thing the course is good that code is good but when I will submit this I will get one problem I'm going to get a time limit exceed so time limit exceed is why it is showing that there is 34 out of 38 cases POS so time limit is showing because I have use the bubble sort use B of any square space complexity so in vectors we have an advantage that we use the predefined sort function in Vector we don't have to do all this bubble sort thing this is for the just basic concept thing so I'm going to just uh comment out this portion and I'm going to just also comment out this portion also and what I will do I will just use the predefined sort function of the uh of the vectors so I'm just going to sort my array by using the property of sort of array dot begin array Dot and if and then I and after writing this I will run the code yes it is showing all the things correct corly so yes the solution is accepted and the answer is correct
|
Minimum Absolute Difference
|
remove-interval
|
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference of any two elements in `arr`
**Example 1:**
**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
**Example 2:**
**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]
**Example 3:**
**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]
**Constraints:**
* `2 <= arr.length <= 105`
* `-106 <= arr[i] <= 106`
|
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
|
Array
|
Medium
| null |
1,024 |
all right let's talk about the video stitching so uh you are giving a clip array and a clip array contains starting time and ending time so you also have a time uh which is from zero to time interval and you want to know how many minimum clip you can add right so for example from zero to ten right uh i can have zero two right because there's no click starting from zero right so uh zero to two right and then four to six okay for right now i can use it right from four to six and for eight to ten yes i can still use it right now right but for about this one and nine right it looks like eye contains from here to right over here right so i don't need what i don't need phone anymore right because i took overlap uh the 189 already right so i mean four or four and six already right so i don't need this so i will move on one and five which is what we'll just overlap with one nine and move on to another one five and nine so five nine right overlap with one and nine so i don't need this so how many minimum clip you can have is what one two three so you return three so this is pretty much a solution so how do you actually need to do this is what uh let me close this all and then i will just draw this again so i will have well i will have a starting time and curve any time and starting time is going to be zero anytime it's going to be 0 by default and then i have a counter click counter right so just record how many clip i need to use so i will traverse my starting time with the time by i mean well for the given value right so if i start less than 10 and then i will traverse a clip try vertical clip right so if the star is actually greater equal to the clip at the beginning right so well what does this mean is actually i need the starting time and the clip zero index and which is has to be very equal so for example in my if my starting time is what is one the clip zero could be what to be zero could be one and these are all valid and this is also correct because if you want to say okay i want something from one to five right and my current clip is zero two zero one doesn't matter so if zero to four right this can be used right and one two three this can be used so only zero and one can be used in this case right so if this is satisfied right this is satisfied i need to what i need to update my current end right so i will say okay n equal to what the maximum between what the current end and also the clip at zero of quick wave one so i'll update the current n by just by the clip y index which is the value but i mean the interval between starting and right and then if this is happening and after the fiber so if the star is actually equal to the n it's equal to the n right i would know this is not about it because uh if the time is impossible to turn it in one right i'll have to return it in one because i know there's no clip i can connect with another one right so i would just after the traversal i was like okay now i know the starting end is still going to be uh still going to be the same right because i initially i 0 right so i will return negative 1 right there right so if not then i need to increment my click counting variable and also update my start to the end so i will know for the next iteration i will have to start at this time all right so let's start holding so i will have a themed variable i would say click time for people here and also store input video and you could do media right so well star is less than time all right so i would say return uh click on uh at the end so i will have to trigger subtree so if the star is what very good equipment you alright my turn and ask the update right there one all right so after the fabric so i will have just making sure does my n updated right so if the star is actually equal to the n i'll have to return negative one if not i need to increment click counter and also update my start to the end so i know like the next iteration i will have to traverse is something else uh it's not going to serve stockholm zero again it's gonna be something else right so let me run it and submit all right so let's double time in space so it's for the space is easy all of constant for the time all of t times all of c so t represent my time c represent what the length of clips so this is the time the worst case and this is a solution and i'll see you next time bye
|
Video Stitching
|
triples-with-bitwise-and-equal-to-zero
|
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.)
| null |
Array,Hash Table,Bit Manipulation
|
Hard
| null |
153 |
liquid problem 153 find minimum in rotated sorted array so this problem gives us an array that could be rotated something like this right so in this case the left side is sorted and the right side is sorted but the right side sorted array is smaller than the left sides of that array and then our goal is to find the minimum element of this array right and this is important where we have to use the drawing algorithm that runs in log and time that means we cannot just use the clients use the mean element right because the mean element in FIFA first is actually is in O and timing right so it's also we can't fit and just do this right so then go on a binary search we have to use a left pointer and a right pointer as well as a middle point right okay so our goal is to find now at which point do the array is in descending order basically right okay so I initialized some variables here and then okay let's begin well left is uh lower than right with this means that both pointers have not met so here we check right we track whether the whichever this number is lesser than this number which in a rotator array it will never happen but if let's say the array is not rotated at all and it is something like maybe something like this four or five where in this case the left will be smaller than right this number always more than this number and that happens we just return the minimum of output and nums left but in this case since uh output is the same as nums left so you just return the first element but it does not happen and we are like this right so you can kind of guess that this if statement will trigger when we are in the right side of the rotated array right okay now uh now that this did not trigger let's find out the mid so mid will equals to left plus right minus left right and then divided by two so this will be 4 divided by two this would be cool right okay so two is five okay before that we have a output and then we check whether or not this number an output is lower than this number in this case it's not since it's five so we don't do anything and then we check whether the middle point is more than the number on the left or not right in this case if the middle point is more than the number on the left we know that we are still in the left side of the sorted array right that means we have to move our left pointer forward basically right so that's what we did left equals to Mid plus one remember made a plus one this will be three okay after that let me check again zero one two three whether or not our left pointer our left number is smaller than our right number which in this case it is so we'll return the minimum of output and elect number right so remember output is three and the minimum is one more like the left pointer is one so we just return one okay uh let's go with a another example I guess we use this okay so the left is zero right is how many is this three six seven six okay I'll put this phone all right so we check again whether this number is smaller than right number it is not so we calculate the mid so mid is zero plus six plus zero divided by two so include this all will be three right which is around here which is this one okay then we calculate our output is a minimum of the first number and middle which in this case uh the first number State because it is the minimum and then we compare the Middle Point again right this is to check whether we are at the left side whether the middle point is at the left side array or the right side array in this case it is on the left side array so we have to move our left pointer up right so if you move it up then it'll be this our left will be three plus one four right on the three four and in this case we're at the right side solder array and then this will trigger and return zero all right that's all I have to show thanks
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
763 |
Hello hello everybody welcome to my channel let's all the record problem partition labels 100 spring fest of lower case english letters give you want to partition this string into as many people as possible so that is latest updates in the most one part and return list of Business reduce size of this can be divided into three parts 690 to-do list of this three parts 690 to-do list of this three parts 690 to-do list of this subscribe and intense pain in lower case english letters to gee so how will solve this problem subscribe in this 600 800 to 1000 for pain lost on this Is Pet All The Best Selected For Adab School Civil Lines Is Hair Oil Subscribe 13 Inch 9 F5 Thursday That Similarly For Depressed Saudi Send Text Message How They Can Solve This Problem subscribe Channel subscribe And subscribe The Amazing Luta Do Subscribe Appointed Tours Life But Last Index of India and you will gain from the day that and will check also create character J N Appoint Amazon will start from 60 in this method last index of the current character subscribe maths dot maximum of The Amazing and the last subscribe choose from current track - 30 to the subscribe like track - 30 to the subscribe like track - 30 to the subscribe like and subscribe the channel and yes subscribe 500 to 1000 binny kwangcho ki criminal situation like from where are the politicians that so let's call more than 100 subscribe changes 98100 will continue till difficult subscribe Indian Partition will do subscribe will update Subscribe good plus one so this is the benefits of but keep updating this and keep checking a subscribe this channel subscribe oil add that and half inch plus nor will update research into the Dr Reddy Labs we 10 and subscribe my channel subscribe start Partition hai aur whose daughter start point initially from 0 to 100 years will update verses from the con is on the last not subscribed till The Video then subscribe to the Page if you liked The Video then subscribe to the related Subscribe My Channel Star Plus Show I one and develop will give start bike plus 2 directions will get all partition will return with oo I is cord is compiling let's embed code that anti bacterial so what is the time complexity of dissolution services scanning all the character of rings two times in the internet and Subscribe please subscribe thanks for watching video subscribe my channel subscribe thanks for watching
|
Partition Labels
|
special-binary-string
|
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.
Return _a list of integers representing the size of these parts_.
**Example 1:**
**Input:** s = "ababcbacadefegdehijhklij "
**Output:** \[9,7,8\]
**Explanation:**
The partition is "ababcbaca ", "defegde ", "hijhklij ".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts.
**Example 2:**
**Input:** s = "eccbbbbdec "
**Output:** \[10\]
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1).
A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached.
Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached.
If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is:
reverse_sorted(F(M1), F(M2), ..., F(Mk)).
However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
|
String,Recursion
|
Hard
|
678
|
1,220 |
Hello hello everyone welcome back on the chain itself is going to call the next problems liquid July challenge has a problem account top sperm station so what to do in this problem is given to us and we can make and which this after that similarly around And by subscribing to us, we can see the total as many as they can and how to approach, what will be required in the input, which will tell us the length, which is the length of the lion, we have to make it, so let us see the example of medium two first. This is given us N2 okay we first see that one I you make first we have this which if in the later if then after that could well okay after that which could after that and okay after that i can't come rest four like e two u can come then after i there is only one poyo ok after that our over ok what can you say i love you i Love you is and after hey you I can only come ok so we just took ok so we made this I in which whatever is there is letter and whatever can come after shatter Wally let's see That and how will NCC cadets be cleaned? Well, in the beginning, any of our articles of our gender can start with any letter, this is how she can hear it from here as well. So, if you have a girlfriend, either she will start from this or she will start from there or she will start from this, is it okay to use this, so now see if it is necessary then the lion that we have become has become something like a ring. I have this next okay, now after that here we need length two, now Sringi is our length, that is Mari End and this thing is worried about only one letter edition, you can come, we will check its value, I will check the value of one in you, one by one. Bars can only be made, that is, the gender that will be formed after this will come in it, only the registries can be made only in the one that was formed earlier and along with it and its length will be bungalow two, so here we will develop this, our length will come, okay, so this Whatever our line is, we will set it as our country and we will take account in it and add it. After that, when we go here again, we can see that we can do it, that is, it is cool, what can we do. Okay, later that brother, we can add already and add or after I, okay, so these two lions will become 100 and after that, see in I, will 400 cements be made in I, so that after I, this can Hai Ganesha, what can I become, my lion, come, or can I become a queen, I have invited these powers, I love you and I have come here and you are okay and if we just talk about this, then I have become ours 1234 5 to 6 7 4 9 and two, okay, so this is our basic approach, we will do it carefully, chicken, we will create a map, initially, which will leave the next character of each letter, okay, and there will be more lipids in it, okay, once we press it will If we find out that a rapid call is being made then we will set it up for memorization. Ok these records have to be kept. If you write decoration then mention is not a big deal. These were the records. What are we doing? In the beginning we are sucking every character because The points letters can be any, there is a golden friend in it, but the ones that come after that will depend on the previous character, if the previous character is this then the next one can be the next one, if the previous character is inch then the next one is I may have come someone else appointed, now you have come you must have understood that we see the phone is on the side, so first of all let's see the basic but when what was our base, when our length is, our NK is locked. Then we have chopped it, so look, first of all, give us a question, is this function or will it be on the control, we have already done this, it is okay to mess with you, this is what I have declared here in private. Okay, I want the interior, whatever I want, for Romney and our interior, take whatever, hello, that is the same thing, okay, and whatever is ours, basically, you can live here in the tractor, okay, and this is our value, so our back. You are okay, the person is A because this chapter starts here, so we want vector, after that we took a turn in private, so this is I took all our volumes together, okay, the course phone of every letter is growing below or can't coin. Now we think why it is like this, which one started late at night, what is the pass here in the recursive function, the end is going in the grease function, now it is coming, okay and this is our previous character, see where the next one will go, it depends. We should know the previous on this so that we can choose what will come next or we will have to keep promised reviews, so in the beginning, I randomly took any specter and took it directly, in the beginning it is serious, okay if it is serious, then which one will be next? If we can and if it is a big deal then if I do it then it is okay and if Maharaj had discussed coriander basis, if our patients will get lens icon in then we will see what is the environment if it is the reverse. So how many can be made, can one be made, if the previous one can be made, then four can be made, and if our why am I here because A, okay, then I sold this and went to sleep, after that this is the work of this position, we will take the reason Surya. And we will put 1 lakh next, which is our character's next Yogi which is here, so this is now we are going to the next and, 3,000,000 calls on it and the columns will be 2017. Okay by default and, 3,000,000 calls on it and the columns will be 2017. Okay by default and, 3,000,000 calls on it and the columns will be 2017. Okay by default value - One will remain because the total value - One will remain because the total value - One will remain because the total tractor is 7766, so basically we will check this code here, if we have already calculated the value then return it, otherwise we will run it and will definitely submit it later. So Shaktidhar, I hope I have understood, verification is the main thing, okay, this is a job in making roti, so if you liked the video, please like and subscribe.
|
Count Vowels Permutation
|
smallest-sufficient-team
|
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules:
* Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`)
* Each vowel `'a'` may only be followed by an `'e'`.
* Each vowel `'e'` may only be followed by an `'a'` or an `'i'`.
* Each vowel `'i'` **may not** be followed by another `'i'`.
* Each vowel `'o'` may only be followed by an `'i'` or a `'u'`.
* Each vowel `'u'` may only be followed by an `'a'.`
Since the answer may be too large, return it modulo `10^9 + 7.`
**Example 1:**
**Input:** n = 1
**Output:** 5
**Explanation:** All possible strings are: "a ", "e ", "i " , "o " and "u ".
**Example 2:**
**Input:** n = 2
**Output:** 10
**Explanation:** All possible strings are: "ae ", "ea ", "ei ", "ia ", "ie ", "io ", "iu ", "oi ", "ou " and "ua ".
**Example 3:**
**Input:** n = 5
**Output:** 68
**Constraints:**
* `1 <= n <= 2 * 10^4`
|
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
|
Array,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2105,2114
|
155 |
lead code problem 155 means stack so this problem asks us to design a stack that supports push pop top and retrieving the minimum element in constant time which is o1 right so for what is mean stack I am using a vector as a stack inside the vector I'm storing a pair right so the most important thing to note is this get mean right so usually how when we want to get a minimum number in a vector we iterate through the vector and then find the minimum number by comparing like every number with itself but since we get to implement how we store the values when we push a new number right we push a new number it will store the number and then and the current minimum number as well right so what I mean by that is let's say using this example I guess so we have this and and then we push negative two right so let me push negative tool our stack looks like this when it's empty we just push the stack width speed value itself right so the negative two and the minimum value in the stack is -2 as well negative two the stack is -2 as well negative two the stack is -2 as well negative two after that we push back zero right so zero and then we compare the value and the stack right the back of the stacks second right which is negative two and in this case negative two is less than zero so when we return the get mail function you see how it will return the stack the back of the stacks second which in this case it is the front because remember we are using a vector right so change it a bit all right so this is how our Vector looks like and then simply push back so this will be at the back right so 10 degree the back of the vector is the top of Our Deck so when we get min we are actually returning the top of the stacks minimum value which in this case is negative 2 right which is correctly since we only push 0 and negative two is a minimum so let's say we push a new value called negative three and then we compare negative three with the current minimum value so is it smaller so in this case it is so we replace the new minimum with negative three right so this is what our Vector looks like and if we were to get mean we will be returning the negative 3. which is the current uh current minimum value but when we pop back when we pop right which means we remove the last element you can see the minimum value of the previous of the now topmost element in the stack is negative two right because we are back with negative 2 and 0. so that's why we need this right to keep track of the so-called Uh current minimum value so-called Uh current minimum value so-called Uh current minimum value that's all I have to show thanks
|
Min Stack
|
min-stack
|
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the `MinStack` class:
* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.
You must implement a solution with `O(1)` time complexity for each function.
**Example 1:**
**Input**
\[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\]
\[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,null,-3,null,0,-2\]
**Explanation**
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
**Constraints:**
* `-231 <= val <= 231 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
|
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
|
Stack,Design
|
Easy
|
239,716
|
377 |
Hello hello hi guys welcome to the video desi beats folding padegi to sab problem school combination complete selection are distributed more than possible combinations for example total number of element points 142 200 how to use element to make for support yash let's check first year using one To Make For So How Can You Make For Using One So Let's Shift Their Butt In English Use One To Make Forth The Evening Amount Free Is You How Many Adelaide Strikers Add One To Three And You Can Get Your Risk Weightage Sequence Fool Slide Song Singer Butt Sentence Elements in English to Support You to Make for Using Two to Two Which is the Best App a Meeting for His Mother Problem Night Scene Select Videos Been Reduced to Making Hadith Elements to Support You How to Make Free and How to Make two and how to make the best way three to the number of to make toys number one and all history will get to declare it is a contingent of the total number of district Etawah to the problem combination subscribe combination meeting free combination to total combination of values Which allows me to think in terms of that China and how to make Free Link Enfield How to make you know how to make you can give but how to make the elements help you to tell you how to make To Make Them A Fight Erupted In The Same Color Correction Gift Confusion So Now You To Make The Tree And You Can You To So How Can You Make Three Years Into This World Celebrates Its Elements In Use 323 B.C.E. Elements In Use 323 B.C.E. Elements In Use 323 B.C.E. Elementary Budget Date For This Is The Number of Elements Element Delhi-02 Elements Element Delhi-02 Elements Element Delhi-02 That Idea Second Way Will Give You The Total Number of System One Thing Notice Against Problem in the Know How to Make Two 9 News Elements 12328 to Make the Evening 121 Use This Element Plus To make to you can not see any body can not limit and you owe you for the account it is the number of waste to make the number Ramesh to make two is equal to see the number to make one plus number 101 one will give You Think You Can Do A Lot To Make Wedding Problem Reduce You Want To Make To Use Elements 12345 Videos 25th Number 1 In 2013 I Okay Now This Is Your Just Make One So And Twitter Account For This Is It Is Equal To See The Number Of Waste Make Yourself How to Make This Element 18102 Nothing Donted Ballu He Entered the King of Kings 112-jazz 102 Number Story 112-jazz 102 Number Story 112-jazz 102 Number Story Based on the Results of Humble Waste Make Sure This Dam Software Reduce Problem Solve Kyun Na Ho Vinod The Number of Waste To Make This One After Target One OK Number To Make 132 Number To Make The Number Of Waste Is Equal To One More Value The Best Of All Elements And Use This Point To That Point To The Number Of The Year Phone Number 10 No. West Macrame Uninstall Super Soft Colors and Disturbance No. West Macrame Wave Smackdown Wave Equal Two The Best All The Speed of Your Net Also this number and vest Speed of Your Net Also this number and vest Speed of Your Net Also this number and vest macrame school number of vest macrame top number and vest is one plus one two you element in different color element meaning of 1234 useless comment and using for loop in the Existing elements which the can servi and saaf and chilli total and contribute for sudhir west macrame element so let's do the defeated and let's go forward-forward news24online's soft target three account and shrink * soft target three account and shrink * soft target three account and shrink * for hand if but this deep and fragrant victims pain and let's Go back to our final problem no problem you all the problem of the best way to make the sum of the problem itself problem free lettuce blue color aa to lakshmi so this blue color change number of making and 324 ok so I know that is the problem The problem is, we will give it a number, the number of WWE super star plus two equal to account for the meaning of the Radhe-Radhe and finally the arrangement of Bigg Boss is back from hair oil ad MP Essays MP let's move wedding reception also tomorrow morning top to Its Murti Hai 100 First Term Another DCP West Also Address Will Have Decided To Run Away This Step Will Make The Depend Acid Rain From Target For Target Of 280 subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the people Gas Perimeter to N0 K0 P0 Equal to One Switch on the Number of Making Nothing in Just 120 Days When Fasting is Written in Problem Solve Combination Subscribe to Phone Number in Target and Period 109 What Do You Do a First for Boy Okay So This is Positive Values Have Already Dahej Bintu Values Have Already Dahej Bintu Values Have Already Dahej Bintu Hairstyles For Target Subscribe - - - 1the Will Not Let The Time Be Now And Start The Point Mintu And Subscribe Now To Receive New Updates For Example A Joe Hair Account On 11072 Ok Account 5512 Developed Call To The Different Target - 12345 Developed Call To The Different Target - 12345 Developed Call To The Different Target - 12345 Video then subscribe to the Page if you liked The Video then subscribe to get मिनर मिनर मिनर का नाम शोप आई तो दूरा ओर डेसेलेक्ट them का नाम शोप आई तो दूरा ओर डेसेलेक्ट them का नाम शोप आई तो दूरा ओर डेसेलेक्ट them in a relationship with in a call to the parameters are subscribe The Channel subscribe to the Page if you liked The Video then subscribe to the Page A Small River During A Bigger Elements And This Element Ismail Half An Hour And Finally Returned To Subscribe To How To Define Languages Time Tense How To Define Languages Time Tense How To Define Languages Time Tense Effective Always Miss U Gift Bindh On This Website
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.