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,832 |
let code pangam check if the sentence is a pangam what is a sentence that is a pankam is a sentence that contains all the English alphabet characters at least once for each character at least once so does this contain a yes H does this contain B yes so basically it contain all the characters so the answer is true if you look at the next example so the code does not contain a it does not contain P so it's not a pangram should contain all the English letters at least once and with that let's move to C an answer actually two answers okay so in the solution we construct a sin variable names we name it sin basically in programming interviews we want to have a set of variable names that we already know we don't want to think about which name to give to a variable we have enough problems in a programming interview so we just use sin answer for answer or result and we could have a fixed number of variable names that we can just shoot in the programming interv okay so we construct the sin variable which is a set we put all the letters in the sentence in the scene and next we scan all the English alphabet and check if C from the English alphabet is not in the sin and sin was the input sentence as a set then we immediately know that we can return false because hey we found a character that is not in SC is not in the input if all the characters are in SC then we return H true and next let's see solution number two so although this is an easy an question solution number two will get rid of this for loop with a python trick and we'll get rid of this for loop with another python tricks although this is an easy question with these two tricks they will help us with harder question let say solution number two lines of code so we can just take an input string and put it in the Constructor of a set and we'll get a set of scene no need to do a follow loop on the sentence on the actual sentence string just do a set of some string a b c d and you'll have a set beautiful next in order to know whether H we have all the English letters in the scene we just check its size because a set would have a single item H per English uh character so if the length of sin is 26 it must have all the English uh characters and basically that's it of course uh we are assuming here that sentence did not have here some special characters H probably in the definition of the question Yeah we actually see that the given sentence contain only English characters so you see we have here two tricks one trick was to construct a set by an a by the input string and the next one was to check for the length of a set and if it's 26 so we need to remember 26 if it's 26 then it has only English character so these are two solutions to identify if a string is a pangram
|
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 |
81 |
Challenge and today's question is your absolutely amazing question because this question will be already understood okay so first okay and what we have to do is we have to do all these things but one thing is said in it that Note: It is not necessary to have a distinct value. Note: It is not necessary to have a distinct value. Note: It is not necessary to have a distinct value. It is not necessary that it should be distinct. The snake has been given to us and this is our question on this very thing. Okay, so let's go first. Brother, how are we going to live it, so let's go to our board. Okay, so friend, one small thing, if I say that if you have not seen part one, then first watch part one, search in Rote Rotted Sorted Hey, the part that was made because friend, if I talk about one small thing, that after all in that What we had done in it was that whatever we had, we did not have all the things, we had all the unique elements there. Okay, so friend, whenever such questions arise, not when we have to go to the duplicate. If we have to find out the key in duplicates, then first of all and to create a unique solution, think about how you can create a unique solution. Okay, so for unique, first it is not in the solution, then go to the duplicate, so what will happen to you will mess up some test cases and then If you tackle them as you are, you will benefit from it, so I will do it. If you tackle them as they are, first of all you understand the basic questions. Well, after all, if you are unique and it is sorted out, then how will you do it, then for that you go there and Watch the video, basically what we did in it, if I want to tell you a little, in that we had shorted it and one is our left shot, this was a right shot, one was short, we said that if we applied binary search. We took out a value and compared it with our loss and on the right side, ours is right that brother, if we give our migrator, then we said brother, this is software, so much part is short and if that part of ours will be short, take it, that's it. Lo you mate, so what did we do brother, this part is short, so then we applied binary search in it, so basically we tackled it in that way, okay, so we were trying to identify it, sort it and arrange it there, basically, what are we doing? There was identify there, so if I say, first of all, we have to do the same step in this question, brother, we have to identify the software directly, it is ok, absolutely friend, how to do it, let's see once, what is the example, if you think, brother, this is in the question. Seven one you three four five okay I took mine, I took this, I took mine, yes, this is okay and mid I took mother, our 3 does not come, otherwise, how can I do it like this, whatever is yours is okay, compare it, so this is You will find out brother, this is not the part, then by comparing from here to here, we will come to know that it is greater, yes, it is a duplicate, but what have we done as greater, brother, okay, no problem, this is our donation, this is correct, less. He is doing yes, absolutely right, he is [ __ ] now friend, let's take absolutely right, he is [ __ ] now friend, let's take absolutely right, he is [ __ ] now friend, let's take one like this, if I say brother, what have we taken, this is what we have, given 3 and in rotten too, friend, it is 33, okay, that means complete, hey three. Based on three and here on the story, in one part I have written that brother, in one part I have changed what I have done. Okay, so what happened here, if the condition has happened, then this is here, in such a question, when what will we do, equals you. Equal you are of made and equal you are equal, so brother what to do then always try to do what you do by shrinking the search space to the search space. Basically I understand the meaning where like Aayi se type gaye there, move the search space one by one L plus do and hai plus l bana liya zero number size le liya Jo hamari add on condition hai ye humne par duplicate lage hai Then what is the use of going down, who knows, you have to continue equal already, then what should you do if the target of your basic is the same, then what else can you do, hey, if you are not able to understand this, then I am still asking you for this. What I will refer to is that search in sorted one, look at it, okay and from there you will get this clear thing And friends, we have written this code, how have you done this, what is ours, what is happening, the target, they have given zero, have you 100% users basically had no idea what 100% users basically had no idea what 100% users basically had no idea what we were doing here we had given separate IF condition and there it seemed to be continuous, neither were they confused that if you remove the continuation then There is no problem, it's okay, I was going to continue here, there was a mistake in this matter, so I did it here, okay and please comment and tell me how you liked this video and see you later
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
490 |
It is the problem number 490 liters that is called you have in this problem what we have is a two-dimensional arrangement that represents a two-dimensional arrangement that represents a two-dimensional arrangement that represents a labyrinth so to speak where the cells with a value of zero are places where we can move a ball to a hypothetical ball and when we reach a 1 we have to stop, choose a wall from the visual habit, let's look at this way, they will give us a coordinate where we are going to start and a coordinate where we have to arrive, so what it is about is knowing if it is possible to reach the final coordinate, now how This is done, for example, they are going to give us a crown. In the example, they say it is zero, like four, the ex is turning blue. The ball can only move in one direction continuously until it hits a science wall with a limit of the wand or with a wall and there it can only move in three directions towards any of the remaining directions sediba downwards actually writes when there are four but well you can't move like that where the stop came because it only mentions three what else well then we simply have to see if it is possible to reach the for example in this one because the path has to be like this and if it can be reached but for example in this one it is impossible because it is like this in fact I think that a good validity is that we can say that if the destination is not surrounded by anything we can rule it out or if it is surrounded for example so its 12 that is a beacon that can continue like this from the beginning but well the problem is interesting because it helps us understand which These are the advantages of forster compared to bread for search and because sometimes you have to choose one instead of the other. In this case, if you do the solution by the first search, the time is not enough. We remember that the first search is that we are going to see what so deep can we go, that is, by way, it refers to the fact that we have a starting point and one continues to explore all the possible paths, not one by one, we are going to grab one, we are going to see how far we can go, if night, if we come across a limit, no longer and I couldn't find the exit we went back towards the last value towards the last this place where there was another option that we could take let's say we went back to the last fork and we tried that path if it can't be proven ourselves and that's how it is and that's how to say e but the problem of doing it That way is that if we have a labyrinth that is too big, it will take a long time to explore all the possible paths. However, force search does everything at the same time by levels. Let's not say that a cancún advances to a possible direction, let's say its movement advances and It checks all the possibilities without any is of advances in all the other possibilities and so on until it finds one then the un continues like this and let's say that finding the shortest way to get to the solution if there is a solution is good to do it by brett for search Chisco is a type of the first search but it is different and I advise you to see the solutions proposed by not politicians but by other people and there are two very interesting solutions to become by Brett Fraser is that it is not the most efficient and by far but It is worth doing it this way so well, like everyone in everything in depression we have to do with an active one of arrays, we remember that the file is a linked list and this led to changing that I like to use variables with such long names when a Tourist, don't do it like this, they will tell your interview with progress in the variables that are as descriptive as possible with fine elevations so as not to be typing too much. We are going to make an arrangement, Williams, who is going to call for a visit from those of us who we have, let's say that of the cells that we have visited and it will obviously have all the cells of our email that we are not going to put, that is, go ahead and we are going to put in our art and we are going to do this while well present you go to any we visit the beginning and well while and it is not like that, this is let's say that the blue print is from everyone from forest search and we do it with a cube we take the value of that q at that moment is the size of esequibo and we are going to get the values of esequibo depending get the values of esequibo depending get the values of esequibo depending on the size at that time moment this is what you have to learn by heart this structure this your balance to understand it because many times you have to modify the small modifications and mix 16 and mix now how can we do for our cloning arrangements well we can do let's do the same that proceeds the same is the term that they give us and we are going to get this first value of our in this team the first value of the asset is true we are missing something the possible movements those who have seen other videos that I have made that I believe that the big one I have a video visit so I don't know why I always talk like there's someone else besides me in the videos which is a little depressing but I don't know I have geeks at some point I would ask someone who wants to prepare for a codina interview in a funk or something like that and something the school is not good because in English it's not worth it you don't see any Spanish I really don't have a lot of content in Spanish that's why the edition in Spanish is created in English celebrities in English to practice but good in all the possible directions that we can take so since we have this we are going to make it a no it is not true we are going to move it in all the possible directions and I like we can do it and we have the value here and we are going to see if or now well we have to do this until you can with a wall so as long as this is valid max and if the next move is valid and we are going to pass mx our matrix we are going to pass x first x m and a very important thing was missing We wanted to know it later this then well because if we start at the beginning then we will no longer be able to do it once and for all here to see when we reach the end no then it is the same if of that inequalities of one is equal to 1 with true and if we do not find anything of trumps ok then good to see if the function is textual and let's assume that the next moment is valid then we are going to add the next move is the same and so on until we reach a point where it is no longer valid then yes we have not visited this then let's go to add to here if do nothing and now we are going to do this function very well and what we are going to do this function is a string of x a coordinate m no in fact this is the matrix and the mode then do this same thing from here I don't know if this value is valid so since it is not valid well first if x is less than zero then it returns to fons or if it is less than zero because of that falls or if the same m point I return to fonz or the most important thing that can happen if mx and that is equal to 14 that photo that we did come across a wall like this then it would be called then second this is the whole problem to be it works at night I escape some I was scratching this problem a lot precisely because of the issue of performance which is this here it is also bad where it can be most bad we go where it can be most bad I think we already hope it works I am scratching many problems precisely because of the issue of performance It has very good solutions out there but the truth is that they are solutions and it does n't work because it doesn't work it's using falls when it should be you yes ok it's equal to 1 it's fine for us and I'm lying of course now you have in me like said the meme on the wiki, he lost his cool and said something about lópez dóriga in passing, and that doesn't make sense, here we are and what's happening gee, and list that it works with its function with I was scratching a lot and I see the horrible solutions like This one that we are with the spouse here but it is good faith is a solution this is the solution of someone else that I wanted to try and well now and it gives us to have show why because we are going to have limits well of course and because we visit because when we do it and approved this is a solution it is not bad but it is the best girl in other solutions in fact there is a solution even though I am saying that here brett for search is faster than frasier crane there is a person among the solutions I had to find a way to say it much faster in the presets but he made some modifications so he hasn't studied that solution maybe 4 but I guess it's worth it
|
The Maze
|
the-maze
|
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return `true` if the ball can stop at the destination, otherwise return `false`.
You may assume that **the borders of the maze are all walls** (see examples).
**Example 1:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\]
**Output:** true
**Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right.
**Example 2:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\]
**Output:** false
**Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
**Example 3:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\]
**Output:** false
**Constraints:**
* `m == maze.length`
* `n == maze[i].length`
* `1 <= m, n <= 100`
* `maze[i][j]` is `0` or `1`.
* `start.length == 2`
* `destination.length == 2`
* `0 <= startrow, destinationrow <= m`
* `0 <= startcol, destinationcol <= n`
* Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
* The maze contains **at least 2 empty spaces**.
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
499,505
|
1,338 |
Hello everyone welcome back to my channel Suji we are going to discuss the problem who has problem in July 4 inches reduce the size to only so what is said in the input and we have a setup in this teachers have taken out the true part in this way. Whatever entries we will take in Somerset, we will remove all the increments and all the Akram Sit from these gestures. Okay, let us make the set of medium size, we will click on these teachers about this and if we put it in the set, then it will be of the set. The size should be minimum, that is, it should have minimum elements. The root of the classification is remote, that is, it should be removed from your maintenance. We have such interiors to choose from, like if I use soft, then if I use cheese, then I take a set, I put it. If I have removed all the free elements from my clothes, then what will be the remaining editor size? It is just fine, but if we want to make a list then what will be the total time size, then what will be its half, that is, apart from the free elements, I will have to remove the element once. So that the exit poll searches for integers like this is the size of many and the minimum size of my set i.e. the minimum element that set i.e. the minimum element that set i.e. the minimum element that came out of this, how to set one or two on top of this, what are you doing to me, this letter is also the total size, take it from all. That is also time is disgusting I please fiber can be less for 933 weeks but apply should be student in which to set that dream if I take out free from this i.e. dream if I take out free from this i.e. dream if I take out free from this i.e. fish sarees will go to Francis i.e. for from this - and my to will go to Francis i.e. for from this - and my to will go to Francis i.e. for from this - and my to I Right now, love is what we need, if we want 535, then I am at home, or will I commit infidelity, will I put you with me, and how much size, as soon as I have it, I went down from there, lunch is done, if I want it back, then I want the next one. And we need less than China, that is, how many elements are there in our minimum set? Ok, now you will understand the question. Okay, so let's see what we are making it from. We will take at least elements in medium size, which I have done quickly. So basically what will we do in this question? In this question, first of all, we will take all the elements that we have by leaving sequences with their elements. It is okay in the crush, like passengers, how many accounts of phones are there, then three of ours would be okay. And the value has become our for. Similarly, that is three times, that is the account of five, how much is done. Okay, at the time of which, when it is two, that is again, then your work is done. 247, that is once, that is of seventh. The work is done, okay, so let's know that we have shifted them along with their real brothers in decreasing order. 4312 and chicken, we have shifted them in decreasing order i.e. in descending we have shifted them in decreasing order i.e. in descending we have shifted them in decreasing order i.e. in descending order. Now we will make a tweet in which it is okay or else Its name is A, let's take the answer, okay, right now, take zero ad in the beginning, okay, and this is our country, those are the people who will tell what is the size of the penis, okay, right now, we will start with zero again, that is, till the week, our We have an account, we came into the present perfect, what will we do when our fiber goes, we are in the village, we started from the first element, okay, we took fennel, we have put what is our account in it and our answer Have taken your possession yet have four * The * The * The enlightened by this minute Android which is the attendant itself night is inch and plus two to two be which is the protein what is the judgment i.e. be which is the protein what is the judgment i.e. be which is the protein what is the judgment i.e. here in our set this verb has been done and which is of three languages Two such elements have come about Rani which if we are in the country Mohan Roy our but I am our here our about us is good then the reality would have been understood if we discuss again first of all what did we do we did with one hand Okay, I made it in it, in which whatever is there is the element. Hey, and the value which is there is the account of that element. Okay, in that part, we have taken a set, in that we have jogged. These are all ours, which are all the hopes from our poetry. We will put them in the set and we have shifted that side in decreasing order. Okay, so now what do we have to do? We have to take a loop on account of this, which will also leave our current, how much element we have salted, how much we have removed. The size woman will be surprised as I told you that how many elements will be understood soon which will be the size to take our total and after that we will lick it, we will hook it up to the wine shop which is our account, this is * If the to the wine shop which is our account, this is * If the to the wine shop which is our account, this is * If the garlic size is there, everything is fine. And what will we do plus and whatever we do in our account, let's set it smooth, that is, we have taken so much, we have removed so much, so this is our approach by doing this, so let's see. Okay, first of all, what did we do in 1981 for ourselves which is India which is Potato Bhindi Chicken like we discussed here which will happen and for that because we have done the basic right now which is What we are making may be possible whereas the messages which are there will be addition and we can mix them as per our wish because now the time entry of the kernels can happen so it is okay so we took the interior and took the grater because we If you look here, we have shifted in the decreasing order, it is okay, then doing them in the decreasing order is Islam, not great, otherwise, if this, which we whatever ghee, then we are going in and which is i.e. if in the support three. If it is and which is i.e. if in the support three. If it is and which is i.e. if in the support three. If it is four, then this EPFO step is fine and this is your EPFO step is fine and this is your EPFO step is fine and this is your business, it is fine, so we will put the balance in the second set, then after that, we will make the same in China in which the size of fast and every other tractor will be made which will be made in the beginning of the set. Let's type the account from Dr to Z and glue the value on it, whatever it will be like back to And this will be 201, okay, so let's first of all, it will be here, so when we write all, then the value which is big on this ID in our account i.e. 418 will go. Okay, so let's value which is big on this ID in our account i.e. 418 will go. Okay, so let's value which is big on this ID in our account i.e. 418 will go. Okay, so let's return the answer in the last, then we will submit. That is accepted and the code of the item is given in the description. Same approach, now assistant of a professor, if you liked the video then please like, subscribe and like.
|
Reduce Array Size to The Half
|
queries-quality-and-percentage
|
You are given an integer array `arr`. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return _the minimum size of the set so that **at least** half of the integers of the array are removed_.
**Example 1:**
**Input:** arr = \[3,3,3,3,5,5,5,2,2,7\]
**Output:** 2
**Explanation:** Choosing {3,7} will make the new array \[5,5,5,2,2\] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array \[3,3,3,3,5,5,5\] which has a size greater than half of the size of the old array.
**Example 2:**
**Input:** arr = \[7,7,7,7,7,7\]
**Output:** 1
**Explanation:** The only possible set you can choose is {7}. This will make the new array empty.
**Constraints:**
* `2 <= arr.length <= 105`
* `arr.length` is even.
* `1 <= arr[i] <= 105`
| null |
Database
|
Easy
|
1773
|
309 |
today we're gonna be working on it called question number three zero nine um best time to buy and sell stock with cooldown now you are given an array prices where prices of i is the price of a given stock on the ith day so we have been given the prices of the stocks uh find the maximum profit you can achieve you make complete as many transactions as you like so we can do multiple transactions uh with the following restrictions uh after you sell your stock you cannot buy stock on the next day and there is cool down one day you may not engage in multiple transactions simultaneously so if these are the stocks the output is going to be three because he said you can buy on the first day then sell on the second day that's gonna be a profit of one then you cannot buy or sell on the third day you need to cool down okay and then you can buy again at price zero and then sell and the next profit is going to be of 2 so our total profit is going to be of 3. uh we're going to be doing it using dynamic programming kind of for dynamic programming um we are going to have three things here um we're gonna say that uh first of all let's just have the sanity check that if the price is uh like the that array is a null or it's like if it is only if the length is equal to 1 just like over here in example 2 or less than 1 the profit is gonna be zero so if the price prices is equal to null enterprises start length is less than equal to one return zero okay we're gonna have uh three things here we're gonna have a by zero by one by two representing that we bought uh today zero means today 1 means we bought sorry this is going to be by 0 and by 1 right by 0 means you bought uh today and by one means you bought a day before that okay and in the in selling we're gonna have three things either you sold today or you sold yesterday or you sold a day before that so we're gonna have three of these right so if uh and be zero like on the first day uh if you bought something that's gonna be the price the value of the price is at index zero and because you bought it so the profit is going to be negative so that's how we're going to be initializing b0 b1 is gonna be exactly same as b zero uh in selling we're gonna initialize our s1 uh sorry s0 s1 and s2 meaning selling today selling yesterday or and selling a day before that all of them equals to zero okay we're gonna go through all the um all the stocks starting from day one because we already calculated for day one uh day for the first day uh zeroth index like the zeroth day um we already calculated that even if we just have one we can return zero we cannot uh earn anything because we need to buy first in order to sell it so we're gonna start with i one uh through uh we can i trade enterprises from i one all the way up to the end i plus and then uh the way we're going to be calculating uh like buying and selling is as follows so let's say if we are buying today what can we do so if we are buying on that particular day either we can take the previous early bot value so meaning we just rest we don't do anything so we're gonna say math.max so we're gonna say math.max so we're gonna say math.max between the previously bought value and let's say if we do sell it so we cannot sell the thing which was sold today right we cannot sell the thing we cannot buy if we have by using uh if we have sold yesterday we can only buy if we have bought some if we have sold something a day before that uh minus the prices of today so that's gonna be our b0 now talking about selling today so if you want to sell today right there are so if you want to sell today either you just rest and keep what you had yesterday right sold yesterday or you can say that okay you bought something yesterday and you wanna sell it today so selling means getting the price of today so that's our that's going to be if we are trying to sell today and last thing is every single time we want to say that the b 0 is going to become equal to b b1 is going to become equal to b0 uh because we are going we are about to enter the next uh next day and next stock so we can just say that b 1 has become becoming equal to the b 0 similarly s 2 has become equal to s 1 and similarly s 1 has become equal to s 0. so all these values have become b1 becoming b0 as one becoming s0 s2 becoming s1 and once you come out of this loop you can just return as 0 which means and the best you can get is that okay i sold something today that's how you can get uh even if you have bought something today uh it's not gonna give you the best profit like if you have to return the profit which was uh which you got after selling something so it's always gonna be returned as zero did not like that is right you can't do it in one line like you can but i mean yeah instead of commas we have to place it with the semicolon looking good and it works
|
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
|
973 |
hey guys so today we are going over the code 973 question okay closest points to a region so we have a list of points on the plane find the uh k closest points to the origin zero here the distance between two points on a plane is the you calidean distance you may return the answer to any other um dancer is guaranteed to be unique except for the other that is in um okay so it's a little bit confusing but let's look at example so point one three uh minus two k equal to one output minus two uh so the explanation is that the distance between one three and the origin is square foot of uh ten and the distance between minus 2 to the origin is square root of 8 since square root 10 is bigger than square root of 8 so the point -2 is closer to the origin point -2 is closer to the origin point -2 is closer to the origin we only want the closest one close escape equal one points from the region so the answer is just like that so for example if our we want the closest two points to a region and our points is has three numbers so we output um the closest two points uh yeah so you can see that in the note um our k is always bigger than one and uh it's less or equal to the points of length um okay um so if we're coding python we can use the um sort least sort and lambda function and this should be like two or three liners first of all let's check one corner case is when k is equal to the number of points so when it's equal we just output the points so if our length of points is equal to our k we don't need to sort or anything we just need to return our original points and it says that it doesn't have to be like sorted right so it can be any other otherwise it's different um it's so the points is always bigger than the k um and we just need to sort the points um so points we can use the python's building function called sorts and it can take a optional parameter called key so key is the criteria that you want the list to be sorted and we can create a lambda function here so lambda function if you're not familiar definitely check that out but um yeah so if we are in the sword least sort and we can create a lambda like this so key equals lambda um x and uh um column x and we can say that x zero time itself plus x 1 and time it does self and we can have a class here uh so this is basically saying that for each of the points we um multiply its uh first index by itself and multiply its second index by itself and that's basically um the our distance um multiplied by the distance and that's how we want it to be sorted and the sort function by default sorts the number from the
|
K Closest Points to Origin
|
stamping-the-sequence
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`.
The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`).
You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in).
**Example 1:**
**Input:** points = \[\[1,3\],\[-2,2\]\], k = 1
**Output:** \[\[-2,2\]\]
**Explanation:**
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\].
**Example 2:**
**Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2
**Output:** \[\[3,3\],\[-2,4\]\]
**Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted.
**Constraints:**
* `1 <= k <= points.length <= 104`
* `-104 < xi, yi < 104`
| null |
String,Stack,Greedy,Queue
|
Hard
| null |
1,534 |
let's go over number 1534 count good triplets given an array of integers so we have an integers array of integers uh and three integers a b and c so we're going to be given an array of numbers and a b and c they're all going to be numbers too uh you need to find the number of good chippers so what a good drip is a triplet is array at index i j and k is a good if the following conditions are true so a good triplet is one that satisfies these three conditions um okay i think you can just you can read the first one and the first one says the absolute value of subtracting the number at index i and j is less than or equal to a and second one is this and third one is this so these are our three conditions they all just have to be less than or equal to a b and c where absolute value of x denotes absolute value of x so we want the absolute value so we want the numbers to be positive return the number of good triplets okay so we have our input array which is this and we're given three numbers right so whatever combinations that we have or we get it has to be less than or equal to all these three numbers and possible numbers are uh given over here and if you look at our example two um we're given another array and it says that none of the triplet satisfies all conditions meaning less than or equal to all these three numbers so it's gonna output five so if we have good triplets we're gonna increase our um count variable by one each time if you guys find this helpful make sure you guys like and subscribe thanks guys uh now let's code our solution so we have our function which takes in four parameters array and three integers and first thing i'm gonna do is i'm gonna make a count variable that's gonna count number of good triplets and i'll just return count here and next i'm going to iterate through my array so for that i is equal to zero and i is gonna be less than already done length and increment by one and i'm going to actually use the array i mean four method uh three times because i want unique um i want unique different kind of sets if you say or combinations so we'll let j is equal to i plus 1 because you don't want any duplicates j is gonna be less than array.length j is gonna be less than array.length j is gonna be less than array.length and increment by one and another for loop this is going to be j plus one k is less than array not length and increment by one each loop all right so it looks good and remember that we have to fulfill all these three conditions in order to have good triplet all right so what we can do is you can use if statements to check all these three conditions and if it's true you can increase the count by one but i'm going to show you a cleaner solution so what i'm going to do is i'm going to make an array called conditions and i'm going to have all my conditions in here so math absolute value of array at index i minus array at index j and this has to be less than or equal to a okay yeah and this condition came from here this is the first one and i'm going to make two other conditions let's just copy these and let's change our condition this is suppose b i this is supposed to be k also and this is j all right so we have our three oh yeah and this has to be b and this has to be c so this is our uh conditions that we have to fulfill or make true in order to have a good triplet and that and as i said before this just came from over here so what you can do is you don't have to do this i just think this is actually more cleaner that's why i did it so we just have our conditions in here instead of an if statement and now what i'm going to do is i'm going to make one statement over here so if conditions dot index of false is equal to negative one i'm going to increase the count by one okay so what this is basically doing is going to check if any of the conditions result in false so if we don't have any false index of is going to return negative one right so if it doesn't find any value that's passing here what index of does is it returns negative one um if we did find false it's going to return the index so let's say that the first one is false where when these two are true so it's going to return zero so it's not going to increase our count by one but if all these are true and if we don't have a false that's going to result in negative one and again that's how indexof works um what we're going to do is we're in we're going to increase the count by one so what this does is if all true increase count and if we do that we should get a result but something's wrong we get 20 and 10. all right we got made a mistake somewhere so we have our full i j k conditions turn count if condition index of false is equal to negative one we're going to increase our count by one maybe my if statements uh minus or a j is less than or equal to a okay oh my uh statements were all so i put the parenthesis in the wrong place that's why we got such a different number and you guys probably caught that so if we delete that we get four and zero and that should be our solution so first one four and output zero and there we go um don't be thrown off by this it's just simply this is basically our uh a statement if you don't like this you can chain three if same is if you like but i think uh that's just a little bit hard to read that's why i use this one and it's just good to learn new ways to do stuff i hope this helped
|
Count Good Triplets
|
minimum-number-of-frogs-croaking
|
Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]| <= c`
Where `|x|` denotes the absolute value of `x`.
Return _the number of good triplets_.
**Example 1:**
**Input:** arr = \[3,0,1,1,9,7\], a = 7, b = 2, c = 3
**Output:** 4
**Explanation:** There are 4 good triplets: \[(3,0,1), (3,0,1), (3,1,1), (0,1,1)\].
**Example 2:**
**Input:** arr = \[1,1,2,2,3\], a = 0, b = 0, c = 1
**Output:** 0
**Explanation:** No triplet satisfies all conditions.
**Constraints:**
* `3 <= arr.length <= 100`
* `0 <= arr[i] <= 1000`
* `0 <= a, b, c <= 1000`
|
keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak".
|
String,Counting
|
Medium
| null |
128 |
Consecutive element sequence so basically the problem is 1004 200 132 how four came like this, you can see van tu three four is formed in such a sequence, right van tu three four is not present in it, so our count will stop so what should be its length Gaya four means four hundred, you can see, if it is not 99%, then its length is also van, if it was like this, give 199, let it be 200, then it would be if it is not 99%, then its length is also van, if it was like this, give 199, let it be 200, then it would be if it is not 99%, then its length is also van, if it was like this, give 199, let it be 200, then it would be for him, then if man lo is 9900 then or man lo van, then it would be for him. You do it like this, if the sequence is there it should be like this, you do hundred three like this, if the sequence should be like this, if there is no sequence like this then we will say for the element, van is right and you can see here, what is there for this, zero is first. So for this one or zero again then for this we will say start now 1 2 3 4 5 6 7 8 so till 8 is present so 012345678 means nine so basically we have understood the problem statement right so let's solve it. This fasting approach is very simple, its principle is very simple, you can see that it is 100, what will we do, if we keep a van count for 100, then we will also keep a van count for 100, if there is a van, then we will keep a van for 100. We will also keep van count. If tu means its next element is found then we will remove this van and make it tu. If its next element is found three then we will remove this tu and make it three. Next we get 11 by removing three. By doing this we will return the maximum among these three, so you can see four max, so we will return four full, so how will you do it will be very simple, very cute, there will be a code, you can see what I did. I have created a function, leave it for now, let's see later what it will do, come to this, after coming to this you can see which is the longest take, then you will make it zero because brother, A will be our output, now what will you do? You will run a loop, take man in the loop, do this and it will be traversed. Okay, for this you will run a loop, so its time complexity will be, remember, it will be right. Now you will name a reason and create a variable in which what you will do is store it which is the President element. If you do this, now present eye will be pointed to 100. So what will you do? You will store 100 in it. Now look, the reason is straight, we will make it default WAN. Okay, now we will compare with this longest, let's see the current later. What will you do after this, you will run another for loop, you will run follow up, run the volume, it is very easy, after this, there will be an in time complexity for this also, because I have to traverse, hence, it will take in time for this also, here is a function call. Which function will I call? Brother, what is this function in this function? The meaning of this function is very simple, what will it do, what is it? 1201234 Will it find from this whether the element which is passed in it is present in it? Or haven't you understood? If you haven't understood, then tell me, what element is this? It will pass. What was our current number? It was 100, so it will be A. Because I have sent it by doing plus one, now by doing + 1, when I plus one, now by doing + 1, when I plus one, now by doing + 1, when I sent it on this. The current element is 101. Now this function will check whether this array has 101%. If yes then 101%. If yes then 101%. If yes then return it. If not then do positive. If it returns false then what will you do. You will tell the positive number as the current number. If you tell , tell the positive number as the current number. If you tell , tell the positive number as the current number. If you tell , then 200 will be paid and the current state will still be WAN, so what will you do, check the longest one, now you will apply a next function, the longest one is still WAN, right after this, 200 will be paid, here you will have 200 WAN. Will go because I have done plus one right, we will check again whether it has 201% or we will check again whether it has 201% or we will check again whether it has 201% or not, if it is present then it will be positive, you can see, first will retain, if it is false then what will you do, you will make the cardient number plus one, then one will pay a. After this, the current is straight, it is okay, whatever the current is, you will not do anything about it, there is still a van, so I can see that there is a van, now after this, when the van comes, what will you do, you will send it by making it van plus, right on it, you will come, now this Banda will check, are you present in this? Han Bhaiya, if you are present in this, then what will you do? If it was straight then it was the default van, you will do it, then now the current check will be done for you. 2 Right now, when you come here, you will check. It will be three because I have sent it with a plus van, so this three will go here and check whether all this is three percent. Han Bhaiya, it is 3%, all this is three percent. Han Bhaiya, it is 3%, all this is three percent. Han Bhaiya, it is 3%, if it is 3% then return it true. If you if it is 3% then return it true. If you if it is 3% then return it true. If you return then you have to plus one card. If the current state becomes plus, then you are A, it will become three, now what will you do, come here, remove 3 and make it four, right, because +1 is also equal to us, if we because +1 is also equal to us, if we because +1 is also equal to us, if we make plus one then what will you do on it, brother, there is 4% in it, make plus one then what will you do on it, brother, there is 4% in it, make plus one then what will you do on it, brother, there is 4% in it, right, if 4 If there is %, then remove three, remove right, if 4 If there is %, then remove three, remove right, if 4 If there is %, then remove three and make it four, rightly make it four, it will become four once and you check the maximum, what is the maximum out of 1 and 4, right, so our longest side will become 4, after this here We will pass 5, if we don't get five then nothing will happen and we will break by doing this. And the maximum you will get will be four right van one and four out of four, you will get the maximum. By doing this you can put a solution but you can see on this that I have put a loop here and also a loop here. I have put a loop because I have to travel linearly. I have to check whether the element is present on it or not, otherwise the time complexity will be O N K. If there is space, it will be O V O N OK and what will be its code. So you can see, I have done the same thing, here you can see, I have created a function which is a function to check the content, you will just travel on it and check whether the element that was passed through it is present in it. Or we are passing it the right if there is present in it, okay you can see, I had considered the longest take as zero man for now or make it a van, okay I had taken the longest take as zero, after that take the card take as van. And in this you can see, I used to run a for look like we are doing, here also it is right and if in the last we will check the longest one then you just return it. If you do it like this then its time complexity. The number and space complexity will be O. Van, it will have to be optimized a little, so let's optimize it. If you make it 100, 200, then very easily you will get 1, 2, 3, 400. So you can write what I did earlier, put three for loops. That's why N was saying so, you can do this shortening with one loop also. Right, if you shorten it then it will be done from one group because we will not have to find the length from the unsotted order, meaning one. If it is mintu then it is okay to count one. If the next element of the tu is 3 then make the count plus-plus. If the next element of three is four plus-plus. If the next element of three is four plus-plus. If the next element of three is four then the count will be plus. If the next element of the fourth is not 5 then make it plus-plus. In this situation, next element of the fourth is not 5 then make it plus-plus. In this situation, next element of the fourth is not 5 then make it plus-plus. In this situation, what will you do, you will reset the account and take the longest one by one pointer, people who will point to the van, now what will you do, you will compare whose length is more, 1 out of 100 will get it, by doing this whose link is the longest. You will get more, by maxing with that you will compare and you will get the output that four is the highest and if you do this then what will you do, first you will short it, I told you if you do shot then it will be 1 2 3 4 100, after this you will be variable. Longest Tree: after this you will be variable. Longest Tree: You will pass two variables down from Van, after this you will run a loop in which one loop will run. Is I - 1 or not? Meaning, Hey I, what is it I - 1 or not? Meaning, Hey I, what is it I - 1 or not? Meaning, Hey I, what is it now, Hey I, you are right, then you check people, Are you not equal, you Van? If there is, you will come to this, will you check? Hey, I = come to this, will you check? Hey, I = come to this, will you check? Hey, I = 1 + 1, if there is main, it is like this, it means, 1 + 1, if there is main, it is like this, it means, 1 + 1, if there is main, it is like this, it means, if there is less, then you are right, if you are present in this, then it is okay if there is this. If there is present in Ari, then you will say, okay, you give it a plus-pass, that will say, okay, you give it a plus-pass, that will say, okay, you give it a plus-pass, that means there was already an initial, you do it, okay, after doing this, when you come to 4, what will happen to the current, it will become four, right after this, when a√5. Will do okay you will check the after this, when a√5. Will do okay you will check the after this, when a√5. Will do okay you will check the note of five is equal tu kya four hai so you will come to this look but when you will check this then you will see that five minus one plus one is five and in this are five is not present if so If not then what will you do, you will reset the cardinstick, then we will max out and get four A, here we will check once for right so also, we will check once for 200 also, then we will match once more and check. Which was the maximum time in this, then you can see that four will be the maximum one, so four we will return, you can do it like this and what will be the time complexity of this, you can see, I have shortened it, so it is these people in time. Complexity, so what is the solution, its time space, topic, city will be Vani, if you do a little modification, it can be on, it can also be right, so you can see what is less than me, Arid and shot, I did the same thing here. After this, I ran the loop, here you can see, after this I have done the if statement with irstatement. Okay, its time complex is from the design complexity. On this, I have done max. After this, I have done the same on this also and I have compared. Retain the higher one, so what is the value in this case? What is the greater of 41 and 1? If it is four, then return four. It is simple. Okay, so let's optimize it, which is the solution that we did in blue. This is the solution. It is very similar, so if you have identified the Rude solution a little bit, then come here and visualize it more, then you will understand, first we will make a seat, okay, so what will be in the set which is 1004 200 132 like this We will put it, okay here you can see it is 1004 200 132, so what will happen first, our pointer will point to 100, okay now take the 100, first I put it in the set by applying volume, now I And played a photo in which the first point is pointing to hundred. Now what will happen from 100, I will mince 100 - 1, Now what will happen from 100, I will mince 100 - 1, Now what will happen from 100, I will mince 100 - 1, okay if 100 minus van means 99, if it is present then it is okay, if not present then plus. Van it if it is present then it is ok if it is not present then you can see 100 + 1 100 should have become 1 then you can see 100 + 1 100 should have become 1 then you can see 100 + 1 100 should have become 1 which is not present on this side then what will you do, you will move this pointer forward, now you check. 4 for 4 - 1 Is there a present in this set - 1 Is there a present in this set - 1 Is there a present in this set Han Bhaiya Three is present if three is present then ok if three is not present then what will you do Skip will be cut A4 + 1 Will do but if there is a present in it then A4 + 1 Will do but if there is a present in it then A4 + 1 Will do but if there is a present in it then what will you do 3 - 1 You will do 2 - 1, you what will you do 3 - 1 You will do 2 - 1, you what will you do 3 - 1 You will do 2 - 1, you will do 1 - 1, but one minus one, brother, zero is will do 1 - 1, but one minus one, brother, zero is will do 1 - 1, but one minus one, brother, zero is not present in this set, if zero is not present in the set, then you will stop at this and put four plus on, four plus one five in this. If it is not present then you will not do anything. Now look at the length which is present. So its length was presented earlier. Right, the working strike was that van. I will remove this and make it up to four because you can see van tu three four. Total four is done, now what will we do, you can see here there will be a stop for A for four because it is not present, now our pointer will go from four to A at 200. Now what will we do for 200 also, from will do 200 - 1 will do 200. - If 1 199 is not present 200 - 1 will do 200. - If 1 199 is not present 200 - 1 will do 200. - If 1 199 is not present then we will try 200 + 1, that too is then we will try 200 + 1, that too is then we will try 200 + 1, that too is not a pigeon, we will stop, after this our point will be crossed 200 and will go to van, now we will check for van minus van zero, it is not present but van plus. Van is present in this You are present You can see You are present in this You are present So you can see 2 + 1 can see 2 + 1 can see 2 + 1 3 is also present You can see 3 + 1 4 is 3 is also present You can see 3 + 1 4 is 3 is also present You can see 3 + 1 4 is also present You can see Four plus van is not So if it stops here, what will its length be? 1 2 3 4 Total will be four, but there is already four in this, so we will have to do something for this also, he sees, so what will we do after this pointer is this Pointer is placed here, ok, after this you will check whether three mines van are present in it, Han Bhaiya, if you are present, then what will you do - 2 - 1 Will you do, is it then what will you do - 2 - 1 Will you do, is it then what will you do - 2 - 1 Will you do, is it 1%, Han Bhaiya is 1%, 1 - 1%, no, Bhaiya 1%, Han Bhaiya is 1%, 1 - 1%, no, Bhaiya 1%, Han Bhaiya is 1%, 1 - 1%, no, Bhaiya 1 - If 1 is not present then what will you do? 1 - If 1 is not present then what will you do? 1 - If 1 is not present then what will you do? If 11 is not present then you will try to blast it. What is 3 + 1? Han try to blast it. What is 3 + 1? Han try to blast it. What is 3 + 1? Han Bhaiya, it is 3 + 1% so it is four Bhaiya, it is 3 + 1% so it is four Bhaiya, it is 3 + 1% so it is four plus one. No brother, if fourth plus one is not present then its longest one is that. What will happen 1 2 3 If it is already four then you will not update it because it is already four and its length is three Now what will you do, after coming here there is a break so now you will go to point A, now you check for 2 Will you do 2 - 1 Is there a present now you check for 2 Will you do 2 - 1 Is there a present now you check for 2 Will you do 2 - 1 Is there a present in the step? + 1 is present no brother four + 1 is present no brother four + 1 is present no brother four plus van is not present then what will you do you will check for this van tu three is already four so you will not update it so the maximum length is 4 but you will be able to see that the length is here For this also the fold length will be A and for this also you can see the van for this, if 1234 folder comes then we will check 100 minus 19, if it is not 99% then we will van comes then we will check 100 minus 19, if it is not 99% then we will van comes then we will check 100 minus 19, if it is not 99% then we will van 100 plus then we will do nothing, we will van it because 100 is already painted. Now we will come on fourth. 4 - 1 is 3%. Right, three is patient, 4 - 1 is 3%. Right, three is patient, 4 - 1 is 3%. Right, three is patient, then after this, if three is present, we will skip it. We will do 4 + 1. We will check 5. If there skip it. We will do 4 + 1. We will check 5. If there skip it. We will do 4 + 1. We will check 5. If there is no five, then we will remove four and go to 200. Now you tell brother. 4 - 1 After this, Now you tell brother. 4 - 1 After this, Now you tell brother. 4 - 1 After this, why didn't I do three mines vans like this, then you are saying this, why did n't I do it like this, when you see people, once you do mines vans and if you get the value of it, then you will tell the calculation for it. We will do it later when that element comes i.e. three is already in the set, you will comes i.e. three is already in the set, you will comes i.e. three is already in the set, you will be able to see that 3 is already in the set, if three is found in the asset then you will say, if this is there, then there will be no calculation for this also, so we will not talk about the calculation for this. Skip it now, okay, so you will not do the calculation of A now, for this what will you do now, you will check for 200 mines, you will say, okay, it is 1989, so it is not present in the set, make it 200 + 1, 200 + 1 What will happen, + 1, 200 + 1 What will happen, + 1, 200 + 1 What will happen, one is present in the stack, no brother, the stag is not present, now A will go here van on van mines van zero already, if it is not present in the stack, then what will you do, you will skip it, you will come to one plus van, now see when there will be van plus van. Meaning there will be plus van, so if we get that in the technique, then we will calculate for that, we will not calculate for -1, but for plus van, not calculate for -1, but for plus van, not calculate for -1, but for plus van, we will calculate, see when van plus van happened, we have got you, then what will we do with three. Now we will check that if you plus one three is already present in the stack then 3 + 1 will make it 4. If three is already present in the stack then 3 + 1 will make it 4. If three is already present in the stack then 3 + 1 will make it 4. If four is already pressed end then it will become four. Four plus one five is already present. In this you will say ok, four is already pleasant. Here is the link for it. Remove the four van, make it four. Okay, now you will check for three. 3 - 1 will become 2. you will check for three. 3 - 1 will become 2. you will check for three. 3 - 1 will become 2. Han Bhaiya, you are present. If there is a mine van, you will skip. Now you will check for 3 + 1. 3 + 1. What will happen will check for 3 + 1. 3 + 1. What will happen will check for 3 + 1. 3 + 1. What will happen four right three plus four plus van What will happen 4 + 1 will become five right so plus happen 4 + 1 will become five right so plus happen 4 + 1 will become five right so plus van we will check now you see 2 + van we will check now you see 2 + van we will check now you see 2 + when 4 will be 5 what will happen for it 1 2 3 right van tu three So you will say ok if van you are three then for this it is already four so we will not do anything to it ok now you will check for 2 - 1 then already ok now you will check for 2 - 1 then already ok now you will check for 2 - 1 then already present is ok then you will say skip for this van already Press the button, calculation is already done, so skip this. If you do plus one, then if you get it in the set, then what will we do. You will do +1, then you will count. So You will do +1, then you will count. So You will do +1, then you will count. So basically the algorithm is such that when you - If you do 1, if it is found in the set then you - If you do 1, if it is found in the set then you - If you do 1, if it is found in the set then you will skip it and if it is found in the set after doing main low key plus van then you will continue with less, so the calculation is being made like this, so let's see how the algorithm is. If it is made then you can see the code that I have done it in the same way, first I had made the set, so I have made it here, after this, what I have done is that all the elements have been included in the blouse set, so we can see. Run the look and add OK, after this you make the longest one zero, now after making the long one zero, what will you do, if Man Lo I - 1 is not present in the set, then what will you - 1 is not present in the set, then what will you - 1 is not present in the set, then what will you do, you will van the Cardinals take, OK and if Main lo i plus van is ok i plus van is available in the set then you will say ok continue make cardient i plus van and current state is i plus van. Man lo i plus van is available in the set then you will say. You will continue, okay, I told you on the algorithm, if you get I + 1 in the current state, then what will you do, you will I + 1 in the current state, then what will you do, you will I + 1 in the current state, then what will you do, you will continue and you will keep passing OnePlus, okay, the state will become plus, okay, OnePlus will become one, okay and if this happens. If it is I - 1 then you this happens. If it is I - 1 then you this happens. If it is I - 1 then you will not do anything as it will remain the same, after this you will check the max. Ok, which one is more in the longest track, then we can see which one is more, then I will return it. By doing this, you You can do this and if you do this then how will it be, so you can see that I have made it like this before, like this, after this the look has come and I have added it, after this on the set, longest tu zero is okay, after this if I take it is like this. We will run a loop. Okay, we will run a loop. What will we do after this? If it happens that the one which is N-1 happens that the one which is N-1 happens that the one which is N-1 is not present in the set, then what will you do? You will name us in the current and will not do anything with the current. For this you will do man lo war ok, after this man lo key at any time this happens the condition becomes current name plus van and it is present in the set ok so what will you do you will van the step meaning continue. You will keep doing it and count it, you will also count it, after that you compare, I did the max, I have done the same, after that you just return the longest, I have done the same here, you can solve it by doing the same, if you like the video. If yes then like it and if you have any doubt then you can ask in the comment section and subscribe the channel so bye
|
Longest Consecutive Sequence
|
longest-consecutive-sequence
|
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
**Example 2:**
**Input:** nums = \[0,3,7,2,5,8,4,6,0,1\]
**Output:** 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Union Find
|
Medium
|
298,2278
|
732 |
Hi gas welcome and welcome back to my channel so today our problem is my calendar three what is given to us in this problem statement here we have to implement a class my calendar three class in which you have a constructor and the second book function is book You have been given two arguments in the function, start and end. You can say this is the interval of any event. Okay, the interval is start which will include and this will exclude you. What we have to do here is to see all the previous events that have happened till now. How much is common among them? What is the maximum common that must have happened here? What do we have to do by returning it? Okay, so first let us understand this problem through an example, is this our problem and then we will see how we can solve it. Okay, so see what you have given, there is a Mike Calendar three class in which there will be this constructor like mine, what is the answer here? In the answer, there is null in the output because there is no return type of the constructor, so there will be null here, okay second. What is the function of your book? Okay, so it is a book. What is given to you in the book? Durgments Start and End. So here you have to see how many common events have happened till now. Okay, what will we do here, we will look at all the intervals, here we have 10. And what is this 20, if it is excluded, then there has been one event here so far, then what will be the answer here, it will be your van, okay, after that, if there are 15 and 60, then 50 will be somewhere here, 50 will be 60, what will happen here, we will see how much is common till now. This is the only event that has happened, this is also one like, there is nothing common in both, so till now only one has happened, the answer will be van, yours is ok, after that, what is your 10 and 40, so your 10 will be here and 40 will be somewhere here. Okay, so here these two have become common, then what will be the answer of your two because till now the maximum is two, this is your common, this is the only one, if two are common here, then you will give two as the answer, after that it is 5 and 15. Five will be somewhere here and 15 will be somewhere here. Right, so what is your three event here? These three events have become common. So what will be your three event? Then what is your 5 and 10? So 5 is here and 10 is what is excluded. If it is 515 and 5 10, these two events will be our common but till now in the total previous function you will see how much is common, maximum so these three are common till now right, meaning we do not have to see this, we do not have to see among the internal given. We have to see overall, all the previous events that have taken place, who has maximum common among them, how much count will be there, who has to turn, so till now it is free, so here the answer will be three, okay, then you have 25, so 25 somewhere. Somewhere it will happen here and 55 yours will happen here. Okay, this event will be common to two events, this one and here, these two are happening here too and let's see overall. So, if three is happening here then what will be the answer, your three will be right, so this has been done overall, among all your friends, who has more in common, that count has to be returned to us, okay, I hope you have understood. Will the problem be ours, after that we will see how we can solve this problem, okay, what we have to do is see how much has happened overall, we have to see that, so what we have to do, here we have to take a variable, maximum. The account tells you what is the maximum count so far, what is the common count, okay, it is possible that the interval we have given, what we will get there will not be the maximum, but we will know the maximum that has happened till now. We will take the same and update it. If any less or more is found from the maximum account, then what will we do with the maximum account. If we update it, then what will we take with the maximum account in the initial. We will take zero and this count will be taken till now, we will see how much. It is okay, we will start from zero, we will take the map, what will we do in the map, what is the value of start, when the value of star comes in the map, what will we do with it, now why are they doing this, I will tell you why they are doing. Okay, let me tell you here, why are we doing this, see, your event is 1020, so 10 is 20, okay, so what to do with 10 will be the account van and 20 will be the count minus van, because what I am telling you is slice. What will happen to you, it will go from zero to right, when you declare it will not slide from zero. Everyone's account will be zero, whatever amount you have, it is okay, when you do plus, it becomes one, when you do minuses then it becomes one and in the end, the mines become one. It will be okay, what will it actually do, this is a van, this is a mines van, okay, what will we see if this event is happening, then we will count it as an event, at least when we do this, till the time we reach here, it will mean that - It will become 1, then whatever you that - It will become 1, then whatever you that - It will become 1, then whatever you add to the count, then you will add it to the account as Mines Man, it means that the count will not end, first Van will be added to the right count, then Mines Van will become overall, what will happen, the date will become zero. Mainly, what will happen is that your event which you had added has ended, it means understand that event has ended, so now again will you count it, what will you not do, if there will be some events here also, yours here was 5630. Right was 563, here 50 and 60, so you started an event from here, okay then yours ended at 20, right then here 50 started at 60, 50 will be plus and 60 what will be -1, then plus and 60 what will be -1, then plus and 60 what will be -1, then at 50 then you are plus. You will get van, then you will get 60 pay mines, what will it mean that your overall of 20, 10 and 20 has ended, that event had happened here only, there is nothing common between these two, that is why we will take pay-1 here. why we will take pay-1 here. why we will take pay-1 here. This will help us a lot. Okay, look, what will happen here? What will you do? You will start the event from here. Okay, when the event starts, people will do the count up. Okay, one count, you have got the event, one event is happening, do you know? If it is successful then you will see in your maximum account whether this count is more than this or if it is more then update it that we are having an event, earlier it was zero then we will update it, okay when When it comes to 20, what will be the count? It will go to zero again. Okay, but we have come to know that one count has been reached. We are having an event, so what will we do with the return here? Will we do it? Okay, we will do it once again. What's next, there will be a van for 50 and 60 also, there will be a mines van for 60, a van for 50, a mines van for 60, then we will start from here again, I want to see the overall, so we will start from here then What will be the count? Here it will become one, then you will start the count from zero. Okay, we are looking at the second element. The count will start from zero. You will get 20. Its account is -1. If it becomes You will get 20. Its account is -1. If it becomes You will get 20. Its account is -1. If it becomes zero then you will understand that your event is over. So this is the maximum gem till now, okay then you will come to 50, this will be one, if you update plus then there will be one, okay one is our in and till now, so the maximum is only one in the account, there will be no need to update then mines. Once the van is done, we will understand that till now there is only one common account, there is not more than one, okay this is done, after that what is our 10 and 40 then what will be the less of 10, what will be the account of 2 and 40? What will happen -1 Okay, then we will start from here, till now it is more and more common, we already had a van, so what will we do here, you will keep it, okay, what will we do here, you will keep it, what will we do after that -1 OK This keep it, what will we do after that -1 OK This keep it, what will we do after that -1 OK This event one has ended, one event will be left on 20, then this mines van will become this, it means the event is over, the second event has also ended, the common has become zero, now it has become zero, then it will come on 50, ok plus. Van has become P plus what will happen after Van 1 - 1 will become zero but here the maximum account we got two, these two events which is happening common are two, we have got two so this is what we will do. Here we will dance, okay done, what will we do after that, let's see the next event here, 5 and 15, sorry 515, where will it be, okay, and here it is three, so which of the two is more, this one is more, so this one Operate people, see, three are common now, so three will be kept here, we have kept it ok, what will we do after that, 15 will be -1, what will we do after that, 15 will be -1, what will we do after that, 15 will be -1, what will happen to you, these two will go, both together will become van, here it will become van, then What will we do in van 1 - 40 will become zero, it is we do in van 1 - 40 will become zero, it is we do in van 1 - 40 will become zero, it is finished then van will be added here ok van has been added see zero here we will not update because van will be found here already we have three so here you will also see it Who will have the maximum three, then will get overall three, then three, what will happen here, the answer will be okay, after that we will see for whom, it is okay for 5 and 10, you will get one, okay, this is done, so now here now. Look, what will happen here, you were here, this five, 10, five, what will happen, this will be your 2 to 1 and this will become from you to van, okay, overall we will see, then count what has happened here, this will be three, okay this. If there is a three then what will happen here is that already Apna is free then it is okay Maximum is already three is mixed with three Okay then what is there here then what will happen This is both will go Then if there is a van then what will happen This From here, mines will become van, it will become van, then this mines will become van, then it will become zero, then what happened here, what will we add to it of 5, we will add plus van to 50, then mines will become van and it will become zero. Look, whatever is yours here, you will get it. You will get the count van, you will get it, but three is already your pass maximum, so there will be no need to update, okay, here also you will return only three, you will return the maximum count, okay, you will not return the maximum count, now you will see which is the maximum till now. If it is the same then you will turn now, 3 will be returned, okay only then what will you do now, then 25 people ok 20 and 25, what will happen here, look here, you will get three here, then you will go here, you will get it, let's do it and This mines van, then this is your 25 but you are getting common. Okay, we already have three, so we will not need it. Then what will we do here? This mines van is ours, then this is our 21, then what will we do here? We will add van on 50, okay it will become zero, you were the one who was found in the middle, but already we have three, right, so three, what will we do, will we turn, okay, so I hope you must have understood why we are decrementing here to start. Okay here what we have done is here we have taken the map okay now here we have given start and end in the book functions so we will do star plus in these we will take minuses and which zeros will we take okay now I These are your starting elements. We will see till the last element. What will we do with the second element? The second i.e. count will be yours by we do with the second element? The second i.e. count will be yours by we do with the second element? The second i.e. count will be yours by adding it to the count. You see, people are updating the maximum count. Has this account exceeded the maximum count so far? Maximum is done, it will be updated here, it will be breaded, overall, what will you do when you get the maximum account, you return the maximum account here, people, if it is ok, then this will be your answer. I hope you must have understood. If you liked the video, please. like share and subscribe
|
My Calendar III
|
my-calendar-iii
|
A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)
You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events.
Implement the `MyCalendarThree` class:
* `MyCalendarThree()` Initializes the object.
* `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar.
**Example 1:**
**Input**
\[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, 1, 1, 2, 3, 3, 3\]
**Explanation**
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1
myCalendarThree.book(50, 60); // return 1
myCalendarThree.book(10, 40); // return 2
myCalendarThree.book(5, 15); // return 3
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
**Constraints:**
* `0 <= startTime < endTime <= 109`
* At most `400` calls will be made to `book`.
|
Treat each interval [start, end) as two events "start" and "end", and process them in sorted order.
|
Design,Segment Tree,Ordered Set
|
Hard
|
729,731
|
929 |
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video today guys we are going to solve question number 929 unique email addresses of least code before i start with the video guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos and now let's get started so basically guys in this uh problem statement we are given an array of strings and all these strings are email addresses okay so for example in this case you can see that the input is a array of email addresses now an email address contains two things one is the domain name so all the uh string part after the other it symbol is your domain name and the string part which is before that the red symbol is your local value okay or i can say it's your local name so uh as per the rules of this problem statement if you have got a dot in your email address or if you have got so if you have got a dot in your email address uh you can simply replace that dot with an empty character okay because if uh we have got an email address like this so let me scroll up so example if you have an email address alice. you send an email to this email address eventually alice zed will eventually alice zed will eventually alice zed will only get the email so uh in our scenario you can see that this email address with the dot and also without the road are all uh are both same okay also if an email address is having a plus in it so for example if this email address has plus so m dot y plus name at the then when you will send the email to this email address the guy who is going to receive the email is going to be my address by an empty character and all the string which is after the plus sign is simply going to be ignored okay so uh remember two things if you have a dot in your email address replace it with an empty character and if you have or i would say simply remove that dot because it is not needed and if you have a plus in your email address uh in your local name of your email address then the string which is coming after that plus simply needs to be scrapped okay so now that we know uh this much we have to find out uh you know once we uh we traverse through all the email addresses we convert these email address values into their actual email addresses that means without the dot and without the plus signs we just we left with a few email addresses which are unique right and we actually have to just return the number of unique email addresses so for example in this case we have got test.email plus alex at test.email plus alex at test.email plus alex at test.email test.email test.email dot mailplus bob.kathy at dot mailplus bob.kathy at dot mailplus bob.kathy at and something else which is test email plus david at the rate so so so when we are going to uh you know simply process these email addresses then eventually only test email at and test email at dot lead. will only be sent dot lead. will only be sent dot lead. will only be sent the email okay because you can see that after plus the entire thing is going to be ignored so this will eventually becomes equals to this one and the last email address has a different domain name so that's why it's also unique remember that all these plus and dot rules only apply to the local name and not to the domain name okay similarly we have got another example here let's come to the constraints are pretty straightforward we have got the length of the array going from 1 to 100 the value of the email address length going from 1 to 100 email address only contains lowercase letters plus dot and at and for each email address it only contains one at the right character so it's not going to be that it's going to be an invalid email address it's only going to have one address character all the local and domain names are non-empty local names are not going to non-empty local names are not going to non-empty local names are not going to start with the plus character and domain names are always ending with a dot-com suffix okay dot-com suffix okay dot-com suffix okay so now that we know about all the constraints we are clear with the problem statement let's jump to the solution part okay so first of all guys i am going to declare a hash set here because we have to return the unique email addresses so whatever will be the size of this let's name it email set whatever is going to be the size of this email set we are just going to return that in the end so email set is going to be our hash set which is going to contain all the unique email addresses now simply i will start a loop from 0 to i less than emails dot length in which we are going to process each and every email address one by one so first of all guys we know that our email address is having only one other character so let me just split our email address becomes equals to emails i dot split and we are going to split it by add the red character once you split the email address now an email address uh the local address so the local name sorry the local name will become equals to the first part of email address and the domain name will becomes equals to the second part of the email address okay so now that we have got both the domain name and local name variables with us it's time to actually process a local name so first of all if our local name is having any dot so if the local name is having any dots then replace it with an empty character so all the dots are replaced with an empty string okay now if the local name contains so if local name dot contains plus then we are just simply going to replace uh that with a value going like we are simply going to remove all the string characters after the plus so local name will become equals to local name dot substring we are going to use the substring function here so our new local name is going to start from the first character because we know the first character can never be plus so it is going to start from the first character but it is going to only go up to local name dot index of plus okay so when you are using index of function it gives you the index where the plus character is present the first index where the plus character is written and then you do sub string 0 to that index it will only include the string from 0 to the character which is just before plus sign okay so finally my local name will be free of all the characters which are occurring after the plus sign now finally we are just going to do set dot add local link because once we add this in our set will only have the unique email addresses so once uh the entire for loop will be over all i have to do is return set dot size uh sorry email set that size so email set dot ad and email set dot site let's run this code guys let's see if this works uh okay so we have got one small issue here um oh okay so my what i only added a local name i had to add the date plus the domain name uh so we have to add the full email address and not just a local name so now i'm gonna run this again and there you go guys you can see that it is uh passing for one example and hopefully it will get accepted for this as well and it does so that was the solution guys i hope you guys uh like the solution now let's come into the 10 time complexity so the time complexity on the surface actually looks like order of one order of n guys because we are using a for loop which is going from zero to all the inverse length but definitely we do have uh functions like substring and functions like index of here so i can say that it is going to be order of n into the length of the string so if uh into the length of the string however we can you know just to simplify it because we have to use in java functions like split or stop string to simplify it i can say that just by the loop it looks like it's order of n okay also the string size is pretty limited so we can say that it is order of n not talking about the space complexity so space complexity is definitely order of n guys because we are using a set in which we are storing all the email addresses so let's say all the email addresses of our array are unique then the set size is going to be equal to the email address uh emails string array size so hence the space complexity is also order of n okay so that was a video guys i hope you guys like the solution and i hope your coding practice became a little bit better with it if you have better solutions for the same problem feel free to post in the comment section guys everyone is just going to be uh really helped by uh by those solutions as well uh if you have any feedback for me anything you want to say write down those things also in the comment section would be happy to read your feedback and your comments like this video share this video with your friends guys and do subscribe to my channel hit the bell icon for future notifications thank you so much for watching guys i'll see you guys in the next video until then take care and bye
|
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 |
1,680 |
hey guys today we're going to look at a problem from lead code weekly contest 218. this one is called concatenation of consecutive binary numbers so given an integer n you need to return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order return this in modulo of 10 raised to 9 plus 7. so you see this modulo thing in problems where answers can be really huge once you do this modulo operation what it does is that it make sure to wrap around the integer value within 10 raised to nine plus seven so you can handle bigger cases as well so let's get into our problem what does this mean if we get ns3 let's take the binary representations from one two three binary representation of 1 is 1 of 2 is 1 0 and 3 is 1. concatenating these you will get 1 0 1. now we need to convert this longer binary string in decimal format this binary string is basically 27 in decimal system so we just need to return that to convert a binary to decimal we take each digit from the least significant to the most significant and multiply incrementing powers of two with each digit and add them all together it may sound a bit too much but this is all we are doing so in this case multiply 1 with 2 raised to 0 plus 1 times 2 raised to 1 plus 0 times 2 raised to 2 plus 1 times 2 raised to 3 plus 1 times 2 raised to 4. add them all up and we get 27 for this problem we also need to know the properties of a modular operation mainly you need to understand this particular property to solve these kind of problems but we'll get to how we can use that later to solve this we could create a binary string by converting all of the n numbers to their binary equivalent but we don't really need to do that we know that n will be the last binary string and lesser numbers will be towards the left in the binary string so we can simply iterate from n to one now let's put the current number into a variable bin we'll keep track of the variable and as zero this is for keeping the value of the sum of multiplication of powers this whole thing we'll also keep a variable pow which will keep the current value of power so this will keep the value 2 raised to 0 initially which is 1 then 2 raised to 1 2 raised to 2 to raise to 3 and so on at later points before we do the next part we need to understand a couple of things number one checking if the last bit of a number is 1. to check this we could use the bitwise and operation if this returns 0 last bit is not 1. this returns 1 then the last bit is 1. remember we don't need to convert an integer to binary to do this how to consider the second last bits or the consecutive bits to the left we have a bitwise operation called right shift if you have a binary string like 1 0 1 which is 27 in battery if you do right shift on this we'll get 1 0 1. if we do right shift again we get 1 0 again and we'll get one next time we'll get zero we can combine these two techniques to our advantage in this problem first we can check if the last bit of the pin variable is one if it is then we can add the current power value to the answer variable next we need the next last bit for this we can simply right shift bin by one now we need to update the value of pow if we notice here we can see that the pow is multiplied by 2 each time so we can do that in our code as well we should be doing this till we go through the entire bits in our current number so we can do this while bin is greater than zero ultimately we can return ants but now we have a problem if we try and include like 12 we'll get a negative value in the answer which suggests that there's been an integer overflow this just means that the value is greater than what can be handled by the integer type in the problem it is given that we need to return the answer modulo 10 raised to 9 first we'll keep a value 10 ratio 9 in an integer now we need to look at the points in our program where we could be having an integer overflow two points are when we are updating the ans value here and also when we're updating the pow value here all we need to do is to take mod at these points now if we try and submit this we'll get an accepted solution this program now works for bigger values of n as well just to recap we discussed how to check if the last bit is a zero or one how do iterate from the last bit to the first bit of a number how to convert a binary string to a decimal and how to use modulo generation 9 in your solutions use these techniques to your advantage in future competitions i hope you enjoyed this video if you did please consider subscribing see you soon you
|
Concatenation of Consecutive Binary Numbers
|
count-all-possible-routes
|
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: ** "1 " in binary corresponds to the decimal value 1.
**Example 2:**
**Input:** n = 3
**Output:** 27
**Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ".
After concatenating them, we have "11011 ", which corresponds to the decimal value 27.
**Example 3:**
**Input:** n = 12
**Output:** 505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100 ".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
**Constraints:**
* `1 <= n <= 105`
|
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
|
Array,Dynamic Programming,Memoization
|
Hard
| null |
1,601 |
hey there everyone welcome back to lead coding in this video we'll be solving a really interesting problem from lead code and name of the problem is maximum number of achievable transfer request so we have n buildings numbered from 0 to n minus 1 each building has a number of employees is a transfer season and some employees wants to change the building they recite in now you are given an array request where request i is from i to i represents an employee's request to transfer from the building from i to the building to i so from i and 2i are the building numbers an employee wants to transfer from the building from i to the building to i all buildings are full so a list of requests is achievable if for each building the net change in the employee transfer is zero this means the number of employees leaving is equal to number of employees moving in for example if n is equal to three that means there are buildings starting from the number zero to two and two employees are leaving from the building zero one employee is leaving from the building one and one employee is leaving from the building two there should be two employees who are moving to the building zero one employer moving to the building one and one employee moving to the building two so as to neutralize it and we have to return the maximum number of achievable requests so let's quickly see an example and then we will come to it here we have in total five buildings starting from the building number zero till the building number four now for the building number one we can see that the number of employees who wants to enter the building are x and y yeah so two employees wants to enter the building number one and then there are two employees a and b who wants to leave the building number one so plus two and minus two for the building number two there's one employee a who wants to enter so plus one and one employee that is employee z who wants to leave this building so for this minus one now for the building zero there are two employees who wants to enter and two employee wants to leave so again plus 2n minus 2. so for all these buildings we are having the submission of the employees who wants to enter and who wants to leave is equal to 0. so the net change in the total number of employees in these buildings is zero for the building three and four we can see that here the changes of minus one and here the change is of plus one because one employee wants to enter the building four and one employee is leaving the building number three so from the list of request how many requests do we have so this is one request number one this is request number two three four five and six in total we are having six requests out of which these five requests over here they are acceptable and they request this is not acceptable because this is causing an imbalance in the number of employees in these buildings so in total five requests can be accepted or these five requests can be achieved again looking at the constraints of the problem here we have the number of request is equal to 16 at max so as the constraints are really low we can think of a brute force solution so for example if we have two requests here request number one and the request number two what we can do is we can select the request number one we can select the request number two or we can select the request number one as well as request number two also there is an option to select none of the request so there is an empty set so in total we will be having 2 raised to the power 2 number of subsets similarly if the number of requests are three that is request number one two and three what we can do is we can try selecting the request number one alone then the request number two alone and request number three alone then one with two one with three two with three then one two and three together and then there's an empty set which denotes that we are not taking any request so in total we will be having 8 subset and this is 2 raised to the power 3. so in the worst case we are going to have 2 raised to the power 16 which will be accepted so that is why we can brute force the solution for each request we will be having two choices either select this request in our final configuration or define the collection of request or do not to select this one so let us quickly go to the coding section and we can actually see that how we can do this we are going to do this with the help of recursion so we are creating a function help in this function i am keeping a pointer i which denotes the request we are currently on and we will be keeping the vector request with us all right so the base case is if i is equal to read or size that means we already exhausted the request array so in this case we have no option but to return otherwise we will be having two options either to select this request or to not select this request now we will see what all are the operations that we'll have to do when we are selecting this and what all are the operations that we have to do when we are not selecting this so as i told you that if we ignore this request then the total number of employees coming to a building and total number of employees which are moving out of the building are 0 for each of the building we just have to ignore this request so we can maintain a vector of size which is equal to the number of buildings so this is 0 1 two three and four now for each building let us say we are selecting the request number one if we are selecting the sequence number one so what we are going to do is we are going to increment the number of employees in the building two so we are going to add plus one here and we are going to remove one employee from the building one so minus one over here then we are selecting the request number two so in request number two one employee is going from building number two to building number zero so plus one at zero and minus one at two then we have the request number three so in the request number three one employee is moving from the building number zero to one so plus one in this and minus one in this if we are selecting the request number four then one employee is moving from zero to one again so again minus one and plus one finally in the fifth one employee is moving from the building number one to zero so plus one here and minus one here so if we see the net change is zero at this position 0 at this position this is already 0 and we ignored the request number 6. so this way we are going to ignore each request one by one that means we are going to generate all the possible subsets of requests that we can and we will see for each of the subset that if the final vector which stores the number of intake in the building is equal to 0 or not and if it is 0 then this is one of the possible answer so we can maximize the answer now let us actually see that how we can code this i is the current request that we are working on v is the request vector then we have int l which denotes the how many requests that we have already taken into account these are the number of requests that we have selected all right and we have to keep a vector which will denote that how many employees are moving in and how many employees are moving out so that will be a vector of type int and let us name it as temp all right now when we reach the end now this is a time to check the temp that if any entry in the temp is non-zero in any entry in the temp is non-zero in any entry in the temp is non-zero in that case we will be knowing that this subset of request is not good so let us go to each of the entry of this temp and if it is not equal to 0 if a is not equal to 0 then in this case we are going to return all right let us create a void function and if all the values are 0 then in that case our answer is equal to maximum of answer comma l where l denotes the number of requests that we have already taken into account and then return otherwise we will have two options one option will be to select this request and one option will be to ignore this let us first ignore this request so when we are ignoring this request we don't have to do anything we just have to move to the next request and we have to call the helper function with i plus 1 and v l and temp done now we will try to go and select this request now when we are selecting this request we have to make certain changes the first change will be in the vector temp so in the vector temp we have to decrement at the position from the building the employee is moving out and we have to increment at the position of the building in which an employee is moving in so temp of v of i this is the current request vo5 is the current request and v of i 0 represents from so at this position we have to do minus and v of i 1 this is 2 so we have to do a plus here because employee is moving at this position now after that we can call the helper function with i plus 1 move on to the next request with v with l plus 1 this time because we are incrementing we are actually taking this request into account and temp finally after coming back we have to undo the changes that we have done so we have to undo this change that v of i zero plus and temp of v of i 1 minus also we can take them as reference yes we have already taken it as reference and finally we will return out of it now we are going to call this function from our main function and for that we will create a vector of int temp which will be equal to same as the number of buildings available and initialize it with 0. now call this function help and pass i is as 0 and then request and ls 0 then temp and then finally written answer now answer we can take a global variable but you can also pass it as a reference in the helper function so let me for the sake of simplicity take it as a global variable answer is equal to 0 and written on so let us try to run this it is giving us correct answer let us try to submit and it got accepted now we have already discussed the time complexity of the solution it is going to be 2 raised to the power 16 in the worst case the extra space that we are using here is of size n which is given as 20 so it is almost constant so it is basically an exponential time solution but the constraints are so low that it is passing the constraints and the space is a constant space so this is it for this question if you like the video please subscribe to the channel and please share it with your friends to watch regular videos on data structures and algorithm please subscribe to the channel and please hit the bell icon so that you can get notification to our latest videos thank you
|
Maximum Number of Achievable Transfer Requests
|
maximum-number-of-achievable-transfer-requests
|
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.
**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.
Return _the maximum number of achievable requests_.
**Example 1:**
**Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\]
**Output:** 5
**Explantion:** Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
**Example 2:**
**Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\]
**Output:** 3
**Explantion:** Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
**Example 3:**
**Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 20`
* `1 <= requests.length <= 16`
* `requests[i].length == 2`
* `0 <= fromi, toi < n`
| null | null |
Hard
| null |
1,187 |
hey everyone welcome back today we are going to solve problem number 1187 make array strictly increasing first we'll see the explanation of the problem statement in the logic on the code now white stab into the solution so in this problem we are given two input arrays array 1 and array two so we need to make all the elements in the array 1 strictly increasing so to make the array one strictly increasing I can replace elements from array2 so the goal of the problem is to find the minimum number of replacement that I need to make from ra2 to array 1 to make array one strictly increasing right so for example assume my ith element is Phi so in this case 5 is greater than 1. so here 5 is greater than 1 right so the left side of 5 is valid so the after element of 5 should be greater than 5 to maintain the increasing order right but in this case 3 is less than 5 so 5 is the invalid element in this position so we need to replace Phi using an element from array 2. so we need to find an element that is greater than 1 and less than 5 for the what is the first element here so 3 is the first element that is valid in this position so if I try to replace 3 here so here 3 is greater than 1 so the increasing order is maintained here but the I plus 1 element of 3 is 3. which is not strictly increasing right they are equal so 3 is also an invalid element in this position right so we pick the next element that is greater than 1 so that is nothing but 2 here so I need to replace 2 here so the increasing order is still maintained in this window also the I plus 1 element of 2 that is nothing but 3 which is a element that is greater than 2 right so the increasing order is maintained here as well so 2 will be a valid number in this position so what if I try to put 4 if I put 4 still that particular condition fails right 4 is greater than 3 it is not increasing right so what we are going to do here is we are going to sort the ra2 so in this way always pick the minimum element that is greater than the I minus 1 element which will guarantee that there will be no clash between the ith element and the upcoming elements in the future so we will use binary search to pick the minimum element that is greater than the I minus 1 element from the ra2 right so now we will see how we are going to do this so initially we will create an hash table DP where we will initialize with negative 1 as key and value as 0 right so here we are going to maintain minimum number of replacement required for each element in my array one so the element will be in key and the number of Replacements required will be as values right then I have sorted the array2 here so first I will pick the first element from the array 1 that is 1 this will be initialized to num1 variable and also within the loop I will initialize an empty hash map new DP right so now I will pick the key from the DP that is negative 1. now I need to check whether the num1 is greater than key so in this case it is greater than key right 1 is greater than negative 1. so when this condition is valid I will take I will check whether num1 exists in my new DP dictionary or not so here num1 is not present in the new dictionary so we will take Infinity then I need to take the value of the given key in my original dictionary that is 0. then we need to take minimum between these two so we will be getting 0 right so now I need to update my new dictionary with key as the current num that is 1 then the value will be the value we found using the minimum function that is 0 right so 0 will be at value for 1 right then we will use binary search to locate where the key can be inserted in the array too so here negative 1 can be inserted in the zeroth index right so we pick that location 0 in my location variable then we need to check if the location is a valid location in the array too yes zeroth index is a valid location right then this is true we locate the element at the given location then we need to locate one in the new dictionary if that particular one is not created before we have to create that one since in this case one is already present there we don't have to create a new one so now we need to update the value here so first I will check whether is there any one is already present in the new dictionary or not yes one is already present right so we pick the value of 1 that is 0 then we pick the value of key in my original dictionary that is 0 right negative ones value is zero so we pick zero and then we need to take minimum between these two which is nothing but 0 we have to just replace with 0. so we need to update this 0 right so in this case it's already 0 we don't have to do anything here after that we need to make the new dictionary as my original dictionary so we just have to replace the original dictionary completely as my new dictionary which is nothing but 1 and 0. so now we will reset the new dictionary then we need to pick the next element from the array one that is 5 so it will be our num1 value then we will check all the keys in my original dictionary so in this case there is only one key so we pick one as my key then we need to check whether num1 is greater than key yes it is greater right 5 is greater than 1 so we need to update our new dictionary so here num1 is not present that is 5 is not present in my new dictionary so we pick Infinity then we pick the value of the key that is 0. so the minimum between infinity and 0 is nothing but 0 so we update our new dictionary key as my current value that is 5 that is the current number so the value will be the value we just found now that is 0 then we need to find the location where the key can be inserted in the array too so here key is 1 so where one can be inserted in Array 2. so here at zeroth index there is already 1 so we cannot insert one there but we can insert one in the next index that is one so the location will be 1 so then we need to check whether the location 1 is less than the length of the array 2. so the length of the array 2 is 4 and one is my location Which is less than the length of the array2 right so in this case this is valid when this is valid we need to update our new dictionary again so what we are going to do here is we are going to check whether I need to replace 5 or not using this location so basically we are going to check whether we need to replace 5 here or not so we are going to pick the value in the ra2 using the location that is in the first index in Array 2 there is value 2 so we pick 2. so this 2 is not in my new dictionary so we will create a key as my two since there is no 2 previously in my dictionary that is in my new dictionary so we need to pick Infinity then we need to pick the value of key which is nothing but 0 Plus 1. so minimum between 1 and infinity is 1 so this one will be the value for my key 2 right so in the previous step uh when I was checking for Value 1 I forgot to add 1 in the particular stage but the answer is not going to change this will be the same right 1 and 0 will be same since there was already 1 and 0 was present in my previous stage so we would have picked 0 only so the answer is not going to change here right then we need to replace my original dictionary as my new dictionary so if we keep on doing this we end up having in the last element as 1 as my value so we take minimum between all values right so we are going to get 1 for this particular input that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we will create our original dictionary where negative 1 will be key and value will be 0. then we sort the array2 right then using a for Loop we will pick each and every element from the array 1 and for each and every array 1 we reset the new dictionary then using another for Loop we pick all the keys from my DP that is the original dictionary and we check whether the current element num1 is greater than the key if this is true then we need to update our new dictionary where we will initialize the num1 as my key then we need to check whether num1 is already in my new dictionary or not if it is present we pick the value of it yes we pick Infinity then we need to take the keys value in my original dictionary then we need to take minimum between both of them where that value will be updated as my value to my current element in my array one then we pick the location of the key where the key can be inserted in my array2 so to do the binary search we are using bisect right library right then we need to check whether the location is less than the length of the array2 if this is true we need to update our new dictionary again then using the location we pick the element from the array2 if that particle element is present in my new dictionary we take the value of it yes it will be Infinity then we need to take the value of the key in my original dictionary then we will add 1 to it then we need to take minimum between these two this will be the value for the element that we picked from the array to using the location in my new dictionary right then we completely replace the original DP that is the original dictionary with my new dictionary so if we can replace any of the values in the array 1 we need to return the minimum values in my original dictionary else if we can't make the array 1 strictly increasing we return negative 1 as my answer right that's how the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
|
Make Array Strictly Increasing
|
print-foobar-alternately
|
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9`
| null |
Concurrency
|
Medium
|
1203,1216
|
905 |
hey everybody this is larry this is may 2nd um i think yeah uh second day of may hit the like button hit the subscribe button join me on discord let me know what you're thinking let me know how you're doing this problem and all the good stuff and also uh for my viewers who are celebrating uh it hopefully i'm saying that right uh but yeah i hope y'all are having a good time in general and hope everyone's having a good may so far as uh as the month begins let's do today's form sorted away by parody okay so i think the so it was supposed to do i didn't even first second okay so the easy way to do it is just do like you know numbstar uh or return sorted nums key is equal to lambda x of lambda mature right so this will definitely work uh but then yeah uh so there you go you have a one-liner right but the thing is of one-liner right but the thing is of one-liner right but the thing is of course what's the complexity here right this is going to be compared with comparison-based comparison-based comparison-based um sword so it's going to be and log um the thing that i'm thinking about uh and i probably did it this way previously to be honest if i've done it before i don't remember these problems anymore because why would you have to remember it if it's one line um but i think what now it reminds me is kind of like uh oh man i always forget which country it is but the frag problem like is it dutch the dutch frag problem uh where you're trying to like you know sort them by uh but this is a easier variation of that um i think is it going to touch let me google real quick okay it is a touch flag album okay but um but basically what i'm thinking right now though just for funs because okay i know that this works we can even submit it doesn't really matter um for fun and up sobbing at home is trying to figure out think of a linear way to do it and the way that i'm thinking about uh because this is easy so and you hopefully you have enough time to spend to observe um and another way of doing it is by like i said the pseudo kind of diet or you could even think of it straight up as dutch frag algorithm but with only two colors right so that's basically the way that i would do it uh just by using two pointers so let's just think about how that would look like so basically i would have i think i've ever pointed in the front end point in the back and then yeah and then just as i go from left to right i swap the odds and evens right so that's the way that i think i would do it though i'm gonna be going a little bit slow because i it's not something that i do very often um so we'll see okay so n is equal to length of nums um and this is going to be in place as well just to be clear so that this will be actually over at one uh space so let's see so that's just um let's have a current index right and then now we have a left index which contains so basically the idea here um that i'm trying to think about is that so let's say you have an array right you have an array of many elements uh and of course it only matters where they are even so i'm just going to replace this for symbol sake uh just ones and zeros right because art and evens right so then now i basically have a pointer to the front and a pointer to the end and a processing so then here i go one okay we want the one in the back so then we move it to the back right so then we move it to the back um this is a one so then we move it to the back uh let's say we move here you could do a couple of things for sure uh but you do a couple of optimizations but basically yeah now that you see a zero you move this one to the back and now you have a zero here right and then now here of course you can move this to the left and this to the right oops yeah you get the idea um now let's say we're processing here okay so one and zeros so then now we can swap again so then basically that's maybe the idea um is that we have yeah so basically we just keep on swapping zeros with once and then that's basically it uh let's play around with that let's actually rewrite this in a different way so then we have left is equal to zero right is equal to n minus one uh let's just say wow left is less than and if uh well and num sub left is equal to or matu so basically if this is even we can move forward is what we're doing uh and then we do the same thing for right uh yeah and now we just keep on looping until we have one number and i think that should be okay for these two so that now that means that at the end of these two things um that means that uh rather uh well it could be at the end i suppose but that means that at the end that means that numbs up left is uh mod two is equal to one dimension we have an odd number on the left side and an even number on the right side so let's double check if left is less than right then num sub left number right as you go to each other and then that's pretty much it otherwise this would break next time we loop so i think this should be okay and then when we loop again then this thing happens i think maybe we're okay but it would also not surprise me right we have uh an infinite loop so let's give it a spin because i maybe i missed some silliness but that looks okay so yeah let's also test it for a little bit more and also i guess i already typed one this is just a random example i don't have any um you know and the good thing about using simple numbers is that you can look at the solution very quickly and know the answer it seems like we are getting a wrong answer or at least a time limit exceeded so now we have some fun things to do oh actually that when it's just that the computer is slow well not the computer but the server because 29 milliseconds pretty slow or pretty fast i mean the internet is slow maybe okay so let's give it a submit let's give this let's give it a go uh and sound we go cool 760 day two streak uh and as we you can see this is going to be a linear time uh and over one space algorithm uh in price of course you have to say in place just to make sure but yeah um yeah that's pretty much all i have i think i probably did it the other two ways with sorting previously uh okay yeah so we use the sort by key made it explicit here i made the one liner yesterday or not yesterday a year and a half ago almost two years ago now well but today we did it linear time and i'm happy for that okay cool um that's all i have for this one let me know what you think hit the like button hit the subscribe button join me on discord hope you all have a good rest of may we're going to be doing this or a month or whatever whether it's 762 day streak so it's going to keep going uh so yeah stay good stay healthy to good mental health i'll see you next time bye
|
Sort Array By Parity
|
length-of-longest-fibonacci-subsequence
|
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
Return _**any array** that satisfies this condition_.
**Example 1:**
**Input:** nums = \[3,1,2,4\]
**Output:** \[2,4,3,1\]
**Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted.
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 5000`
* `0 <= nums[i] <= 5000`
| null |
Array,Hash Table,Dynamic Programming
|
Medium
|
1013
|
1,287 |
hello guys and welcome back to lead Logics this is the element appearing more than 25% in a sorted area problem more than 25% in a sorted area problem more than 25% in a sorted area problem it is a lead code easy and the number for this is 1287 so in this problem we are given with an integer array which is already sorted in non decreasing order and there is exactly one integer in the array that occurs more than 25% time of array that occurs more than 25% time of array that occurs more than 25% time of that actual array actual size of the so we have to return that integer so let's see through an example suppose we have this example 1 2 66 710 so the size of this array is 9 so the quarter of the 25% the quarter of the 25% the quarter of the 25% occurrence will be uh two here more than two so we have to find any element which is more than two times appearing so we'll take one we'll check if it is appearing more than two times no we'll take to we'll check if it is appearing more than two times no it is appearing two times but not more than that so we'll not consider this as a perfect answer so we'll check now for six is six appearing more than two times yes it is return the answer so for this you can also use hashmap or frequency calculation methods but I'm going to tell you a super simple method uh with the help of which you can do it in the help of single path that is O of M time complexity and without any space complexity so for this first of all we'll uh Define a size uh and then we'll Define a quarter this quarter is actually the number of times the element should appear so that it is more than 25% so appear so that it is more than 25% so appear so that it is more than 25% so I'm defining this because we'll be keeping count of the variables and if at any point of time the count becomes greater than the quarter we can return the answer and break and there will be some other variables such as account and a PO pointer variable okay and how we are going to do this we are always going to check for if a r of I equal to a r of I + + + 1 if it is correct then we'll do a uh count Plus+ and the I + 1 element count Plus+ and the I + 1 element count Plus+ and the I + 1 element becomes the p and at every point we'll check if the count exceeds the quarter or not and if this condition is not true we'll reset the counter to one and the pointer becomes the I + one and the pointer becomes the I + one and the pointer becomes the I + 1 element so this is simple so let's try with the coding section for this problem but before that do like the video share it with your friends and subscribe to the channel so see here first of all we'll Define the size then we'll Define the quarter we'll also need a count variable and we'll need a pointer variable so it will be at AR now what we are going to do is that we are going to iterate over the array and since we need to check the ith element with the I + one element so element with the I + one element so element with the I + one element so that's why we are starting this loop with one not zero because we want to check this zero element with the first El the element at the first index that's why we are starting this with one so okay we have put this equal to one now we check if P equal to a RR of I yes what we have to do count Plus+ Plus+ Plus+ otherwise what we needed to do we need to reset the count equal to one okay reset the count and at every step you check if the count exceeds the qu or not if it exceeds I return the answer otherwise replace the pointer now we have replaced the pointer with the i element and afterwards we can simply return the pointer because if all the elements are same this pointer will be at the last element and this needs to be return so let's check for the sample test cases are past cases the sample test cases are past let's now try to run for the hidden test cases as well yes the solution passed with a good time it and good memory complexity earlier I submitted the code so it gave 100% I submitted the code so it gave 100% I submitted the code so it gave 100% I don't know how it is giving 64% now so don't know how it is giving 64% now so don't know how it is giving 64% now so anyways the time oity for this solution is O of n where n is the size of the input array and we need to iterate through the array and space complexity is O of one as we use a constant amount of space for variables let's try to submit it again and check if it gives net percent or not see it gives 100% so if you want the Java C++ Python 100% so if you want the Java C++ Python 100% so if you want the Java C++ Python and JavaScript code for this solution you can go in the solutions panel and check this solution my solution and you can go and check the Java C++ python you can go and check the Java C++ python you can go and check the Java C++ python JavaScript solution yes remember to up for so I hope you understood the logic how we are going to do solve this problem thank you for watching the video have a nice day like the video share it with your friends subscribe Channel thank you guys
|
Element Appearing More Than 25% In Sorted Array
|
distance-between-bus-stops
|
Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105`
|
Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.
|
Array
|
Easy
| null |
329 |
hey everybody this is larry this is me in uh oh this is day oh and i just got back from uh all my travels you can see on instagram but yeah this is me doing day 19 of the may lego daily challenge hit the like button in the subscriber enjoyment discord and of course at least for when i'm in traveling mode uh so i'm you know hit me up on instagram to see what's going on you'll see the drawing shot from earlier hopefully i remember to put it in but um otherwise you'll just be like what is larry's going on well yeah what was the other thing i was gonna say oh first things first i do want to thank all the people from atlanta and georgia in general uh all my viewers to kind of give me tips uh i don't know about i don't know okay i want to this is just a general shout out i guess i actually forgot to ask them if they would like a shower so i don't want to you know put people's name on the spot or whatever an accident definitely dox anyone but anyway thanks for all your input been checking out places uh very happy with some of the photography i've been doing uh i didn't the sunset today was beautiful in atlanta but i didn't get a good shot i wasn't at a good price i didn't have a good um i didn't go to i didn't have a good conversation sometimes it is what it is um and the place that you know a lot of it is just not luck per se but just timing right like everything else in life in that i mean i'm here in the summer so the you know the light angle there's the sun uh axis or whatever or the earth axis really but you know and the angles are a little bit off with how i would like my conversations to be but uh but you know you never know there's still i'm still here for another day or so uh so yeah we'll see anyway uh that was a long intro hope you uh if you didn't like it i hope you skipped it if not but yeah um so i'm i wanna you know yesterday was a rough one obviously the daily contest i mean or the daily um challenge uh you know these things are i just wanna give you a reminder these things are recorded live i do solve them like without seeing them because if i have seen them that would be just really embarrassing to or i don't know it's a really weird script to get it wrong on purpose for an hour right but uh so i think you know my goal here is to of course try to educate and help uh however i can with the thought process and sometimes algorithms and stuff like that but my main focus is to kind of show you that two things right one is that you know i consider myself pretty good maybe i had a bad week last week but you know i was top 100 on the code like two weeks ago say uh so you know i'm pretty good on like contest real life or real time waiting or whatever and i'm a good engineer i think maybe not depending on who you talk to but i think so anyway um and these things still happen these things you know so i think there's something there and also sometimes in the struggle is where you see all the learning and the creativity right like uh hopefully that came out and you find it useful because um it does come out sometime like this um occasionally but if i already if i knew how to explain everything about problem that's fine but you know i think it's less interesting maybe i don't know let me know what you think in the comments uh below or on this chord because people have different opinions but i think i'd like to kind of show you like all my strengths and all my weaknesses and yeah they'll do a lot of good fast problems and you'll be like oh of course um but also that i sometimes do struggle sometimes just giving on reading comprehension reading is hard right anyway okay so this is a really long intro um my apologies became just for that uh i guess the additional thing is that wow start i just got back it with no internet today uh the stock market what happened yeah hope everyone's doing okay uh what a weird year for that right okay all right maybe i'll talk more about the stock market another time but for today let's focus on today's farm my apologies if you're here only for the problem uh you know this is uh this is a you know this is a daily style but also um you're doing with me i'm doing review what however you want to think about it i appreciate it by the way um so now let's do it together let's get that streak going again all right finally let's go longest increasing path in a matrix 329 okay so given m times the n matrix we turn the link with longest increasing path matrix for each cell you can either move in four directions you may now move diagonally or move outside the boundary so where do we start oh i guess you don't have to stop from anywhere okay um there are a couple of ways you can do this the way that i like to think about it is by dynamic programming right i think that's maybe the most intuitive way uh let's see if there are any constraints just before so okay so this is i think um this is not a great because i think this yeah i think so one cool part about um so a couple of things right one is that this is still a dag right uh and what is a dag is a directed a circular graph and there's no cycles here okay so i just will go but it's a directed graph uh because well you can make it draw a line whichever way you want meaning from a number to its neighbor that is bigger or to its neighbors that smaller depending on which direction you want to go of course for this particular problem this is there is symmetry right what i mean by that is the longest increasing path is the longest decreasing path um so you could kind of think about it both ways and under uh so this is a directed graph right because you know one pointing at two does not mean there's a or if it um given a node one that points at the node two that actually means that there's no uh edge from two to one right of course uh in an increasing pathway so that's the second one um and then from that you can try to um yeah and then there's no cycles because uh how does it explain those cycles asynchronic i mean there's no cycles because there's no way to you know like if a is greater than b there's no such or and b is greater than c say you know there's transitive obviously but there's no such way such that you know uh there's no such way such that c is greater than a right in a normal at least not for the uh regular numbers that's probably not the right phrase but you get what i mean for numbers that are normal-ish uh for numbers that are normal-ish uh for numbers that are normal-ish uh that's not true right so there's no cycles here and from that means that you can do this with dynamic programming and you can implement it in two ways one is um a gym mccoy bottoms up or top down for this particular problem i'm going to do it top down um and we'll go for it together and hopefully we'll you know make some magic uh because for dynamic programming it's just about the recurrence right and then the recurrence is of course something that is just defines the function but the better way to get the recurrence is asking the right question and what does it mean by asking the right question it means that asking a question or finding the problem if you want to be technical where you can express the problem in terms of its subproblem in more in asking the question sense you want to ask a question that allow us to answer itself in smaller and smaller pieces um and the dag will obviously help you kind of figure out that uh in a way um but yeah so then now here we get longest uh maybe x y right and what does that do this gives i don't know why this is in close oops gives us the longest path starting at x y uh longest increasing path starting at x y right so i think that's basically the idea here um okay uh we'll do the caching part or the memorization part in a second so for now we're just going to do the brute force e thing as well but that said let me change that over let me take that back because i think one thing that i've seen a lot uh at least on my discord and discussions uh a lot of people just kind of you know they implement it in brute force kind of way and then they add you know they add memorization and then hope that it works um for this you really should at least prove to yourself that this works before implementing it otherwise you just you know try you know i mean it's um if you have no other way of doing it i'm not going to judge you on it you know like it is what it is you do the best you can and that's the best you can but i do urge you that when you do have your own time like you're in a contest you don't know it's fine it happens right you get lucky better than not lucky um if you're an interview it's a little bit less so right so definitely um i definitely always kind of understand how memorization works and how to um calculate the space right but this one um you know what are the possible x right is it 200 i think yeah so x can be 0 to 200 y can be 0 to 200 right and then now you those are the possible inputs right so the total complexity uh time complexity first let's say it's just equal to the total number of inputs times uh time per input right and of course time for input is just time over input and then the inputs cancel out if you want to do unit analysis and then you get the total time right so then the total number of inputs so here the total number of inputs is equal to um let's call this i don't like this m n so i'm going to call this r and c right so x uh let me rewrite this is equal to 0 to r y is equal to 0 to c so the total number is equal to r times c right and then how much work does each input do well and this is i do this for most problems before i solve it obviously but sometimes i don't think i showed that in a good way to be frank um in general so hopefully this time is a slightly better but you know you can put i think well what am i doing which input well the only the worst or the most things you can do is go i think up down left right can it go diagonal uh no diagonals okay well obviously you can't move outside uh i guess maybe not obvious oh they're weird but anyway so for each cell you're gonna only make four chords right up down left right um and keeping in mind that there's no cycles so really the only three of those directions because one of the directions you came in except for the first one obviously but you know that's fine um and that's a lot of this is implicit anyway because you can't go back because then you're going to decreasing number anyway right so that means that oops uh time per input is to go to uh of one let's say three or four checks right um so in that case then total time is to go to o of r times c times over 1 and that is equal to o of r times c which is linear of course linear in the size of the input because the size of the input is r times c um and then total space uh we're going to do that later but that's spoiler alert it's just me r times c because that's the uh total and this is the same idea right total space complexity is equal to the total number of inputs times space per input uh in this case space for input is going to be over one because we just use you know one where sorry my allergies i saw it acting up again i need to do my benadryl but uh anyway so then in this case uh times o of one and that's gonna be o of r times c right um yeah okay so that so i did this very quickly in my head um i'm like okay so that sounds good so then now i this is when i actually implement it um everything you see here um i did in my head very quickly some of it is just from experience right like i you know from experience i know i'll do this in my head very quickly because i recognize it right but if i were to kind of um articulate it out this is what i would do before coding to be to emphasize it right so okay um and this is a re-memorization we um and this is a re-memorization we um and this is a re-memorization we don't then it's gonna be exponential because now each time per input is exponential and or is it i don't know what it probably is because it's four times whatever uh fortune or whatever rather and then space is fortunate or whatever as well actually i guess space you don't use extra space because you're not memorizing but anyway yeah okay so the other thing i want to do before maybe i don't cut it off uh okay it's just set directions and this is something that i do a lot right it's just setting up the four directions uh i think i don't know how i feel about this anymore but uh but it used to be pretty like just fundamental right so okay so then now best is equal to one this is our default best this is the base case if you will basically if we can't go anywhere else then our we need to learn the best but we can't go anywhere else we are at one space because the longest increasing path has one node which is itself right and then here so this is an implicit base case um and now we do for dx dy and directions hopefully this is similar to what you've seen from me and breakfast search step for search stuff like that or not sorry not that stuff i just mean like grid-based problem this is very gritty grid-based problem this is very gritty grid-based problem this is very gritty uh type of thing that i do almost every time so yeah uh and then we just checked that oh i didn't play this obviously you go to length of matrix i love setting the things first uh make sure that is at least one so we don't have to check for it uh and then now we check that nx is you know we've been bounced and y is within bounce and then also that we're going to an increasing number right so that means matrix of x y is less than matrix of n x and y right if this is the case then uh best is equal to max of best longest uh of nx and y and that's pretty much it except for the caching part as our memorization part um but that's basically the direction right like you go okay what is the best way what is the longest increasing path starting from x y well it's this website oh i did mess up sorry once uh is the adjacent note if it's increasing go to the next note plus one that's basically the idea and that's pretty much it uh yeah okay and then here for best we just have to figure out uh which cell to start from right and the cell to start from is just going to be well you could you don't have to guess you just try all of them so yeah so this is what we're gonna do right oops and press of course and that's pretty much it of course this will time out but i'm just going to run the code just to see if it uh compile errors or something not compile errors but you know what i mean ah this actually doesn't time out but i mean for bigger cases it would definitely time out anyway um okay syntax error it was just the word i was looking for but anyway so now we just have to memorize right and the way that i like to memorize is just you know for every possible input um the idea here is that if you give the same input you should get the same output every time right and so for that you memorize um so that the next time you do the same input you already know the answer so just return it that's basically the idea um i call it cash for that reason uh because it's like storing it on cash um but you know that's up to you uh and then here now what we have to do is go if has cash that means if we already cached this then uh return cache of y at the very end we go has cash x y as you go to true because you know we have it and then cache of x y is equal to best and then we turn uh before it's 44 milliseconds or something like that i think i don't know if it's gonna be faster i mean it is slightly faster but you know we don't have a big case right so maybe we could have a big case just for fun um or like not a big case but at least a bigger case so we could kind of see the difference a little bit i don't know if this is that good but uh yeah let's get rid of the cache for now so we don't set hash cache to be true so there's no cache let's see if this is fast enough i think this is actually fast enough because of the dag but wow this is actually faster than i expected okay well nonetheless uh if we have has cash it isn't that much faster okay i failed in the illustration but nonetheless uh it is faster but let's say i have a really big case that'll be true um okay i think what's that love is me just double checking if i have any silly mistakes uh let's check this one yeah okay let's give it a submit done apparently i did it twice before one time ever once i don't know how but let's take a look at that and that there you go there we have a completion streak 779 days um this time i did the uh analysis first so hopefully that makes sense uh what did i how did i get it one time huh oh i just missed the empty space one what is this oh this is me doing bottom up uh okay i guess that's fine maybe i was just trying to be fancy uh but yeah uh that's pretty much all i have let me know what you think this is the first half this is the second half of the code um yeah i'll see you later uh stay good stay healthy take a mental health take care and i'll see you later bye
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
1,176 |
today last song Lead code 1176 diet plan performance okay so uh the question is so we have a director to consumes calorie eye calories on the ice day and with an integer k for every consecutive sequence of cake days okay starting from calories I to calories I plus K minus one we have the total calories consumed during the sequence of case consecutive days starting from calories I to calories I plus K minus 1 okay so if the t is strictly less than lower so they will lose one point if the t is quickly greater than upper they will gain one point otherwise nothing change okay so uh initially they have zero points and our task is to return the number of points that the data has after uh calories not land days okay one of us is the total points can be negative um okay so last check at the sample one we have uh one two three four five with the K is one lower is three and upper is three which means we need to check for every uh for every consecutive sequence that has the length is one and for its sequence we need to check for these conditions okay uh okay so for example we have K is one it is less than lower so we have minus one and two also less than lower is minus one so now is okay so for example we have one two three four five and then K is one so first we have uh one less than three right so our answer now is minus one and then two also less than three so we have minus one and plus minus one so we have minus two so three okay so three equal to lower also equal to Upper so nothing change so it's still minus two okay and so we have four and five they both uh they both strictly greater than upper which is three so we have uh minus two plus one for each sub sequence and then we have zero so that is the output so I think this example is quite special so it's hard for us to think about the overall solution so I think let's use the example free is more generic okay so we have calories 6500 okay it's two lower is one and upper is five okay so uh okay so to solve this problem I think we can think about the sliding window technique right so we will uh have a sliding window has the length is K okay so first we have uh the window has the lens is a equals to K and then we keep sliding that window until risk the end of the array okay and for every sub array every window that we slide we need to calculate the total of uh this sub array and then we will compare with the lower and the upper to update the results okay so for example one we have the window starting from six right and five so we calculate the total it is 11. okay 11 and we compare with lower and upper and then we can adjust the final results so after that we slide this window to the right and then for this sub all right we don't need to recalculate it we only need to add the new element value into the total why we can subtract the first element since it's no longer belongs to the current window okay so I that is the idea so let's dive into out the implementation okay so first of all I think we might need to check for some s cases so for example for this problem I think we don't have any s cases okay so we can Implement its strength forward okay so uh we will need to declare a variable to store the answer and then finally we return the answer okay so first of all I will uh have a for Loop prove the first pay elements and then I will calculate the total of the first scale element okay so we have total is equal to zero and then for every Loop we will update the total plus equals calories at I okay and then after that we can check the condition if total is less than lower okay so we will it if it less than so it will lose one point which is answer is minus equal one if total is greater than upper so the answer now is plus equal one okay and then we will check for own orders windows so we will have another for Loops starting from K keeps looping why I is less than calories dot lens and I Blood Plus okay so first we will need to add the new element value to the total and subtract the element does no longer belongs to the current window which is we need to Total plus equal calories I and total minus equal calories at I minus k okay and then we will check for this condition again right uh I think let me copy it okay so that's it Okay so let's try oh we have compile error okay calories dot lens land is not a method okay so accept okay try to submit okay access
|
Diet Plan Performance
|
design-a-leaderboard
|
A dieter consumes `calories[i]` calories on the `i`\-th day.
Given an integer `k`, for **every** consecutive sequence of `k` days (`calories[i], calories[i+1], ..., calories[i+k-1]` for all `0 <= i <= n-k`), they look at _T_, the total calories consumed during that sequence of `k` days (`calories[i] + calories[i+1] + ... + calories[i+k-1]`):
* If `T < lower`, they performed poorly on their diet and lose 1 point;
* If `T > upper`, they performed well on their diet and gain 1 point;
* Otherwise, they performed normally and there is no change in points.
Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for `calories.length` days.
Note that the total points can be negative.
**Example 1:**
**Input:** calories = \[1,2,3,4,5\], k = 1, lower = 3, upper = 3
**Output:** 0
**Explanation**: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
calories\[0\] and calories\[1\] are less than lower so 2 points are lost.
calories\[3\] and calories\[4\] are greater than upper so 2 points are gained.
**Example 2:**
**Input:** calories = \[3,2\], k = 2, lower = 0, upper = 1
**Output:** 1
**Explanation**: Since k = 2, we consider subarrays of length 2.
calories\[0\] + calories\[1\] > upper so 1 point is gained.
**Example 3:**
**Input:** calories = \[6,5,0,0\], k = 2, lower = 1, upper = 5
**Output:** 0
**Explanation**:
calories\[0\] + calories\[1\] > upper so 1 point is gained.
lower <= calories\[1\] + calories\[2\] <= upper so no change in points.
calories\[2\] + calories\[3\] < lower so 1 point is lost.
**Constraints:**
* `1 <= k <= calories.length <= 10^5`
* `0 <= calories[i] <= 20000`
* `0 <= lower <= upper`
|
What data structure can we use to keep the players' data? Keep a map (dictionary) of player scores. For each top(K) function call, find the maximum K scores and add them.
|
Hash Table,Design,Sorting
|
Medium
| null |
969 |
welcome to my channel so in this video i'm going to try to solve this problem do some live coding work at the same time i'm going to try to follow the general interview steps while trying to solve this problem so first of all let's try to restore this problem get a good understanding about the question so given an array of the integers array sort the array by performing a series of the pancake flaps so you want pancake for if we do the following steps choose an integer k where k is anywhere between i to the length of the array then we reverse the sub array from 0 to k minus 1. so for example if i raise three two one four and we perform a pancake flip choosing ksc the three then we are going to reverse the sub array three to one so after the pancake flap it is going to be one two three four after the pancake flav at k equal to three okay that makes sense so return an array of k values uh corresponding to a sequence of the pancake flakes that sort the array so any valid answer the source area is 10 times the read that lens flip will be just as seen as correct okay so let's see the constraints so the length of the array is anywhere between 1 to 100 and also each number within the array is anywhere between 1 to the length of the array so all the integers in array are unique okay so that it means you're going to have like something like one two three four until a red lens okay uh that makes sense so currently based on the constraints it doesn't seem to have any ash keys that works to think about so if you want to think about some ash case i think if the array has only one number we don't need to do anything but anyway this can still be covered by the general algorithm i think so let's try to find the solution how to solve this problem so i think one thing uh what i can think about is so for example uh let's say we have an array something like three two four one so we are going to follow the general steps so one time so for each step we focus on putting the biggest number towards the end so for this one we are going to do a swap do a pancake swap so after that so the first pancake swap is something like we are going to put the first number for the largest number as a first number which means we are going to try to do a pancake swap after that it will be something like this and then we are going to do a full swap it and it would be something like this so after the two pancake slips uh two funky flips so we are going to put the largest number at the end so similarly we could uh we could put the straight and the second largest which is second largest and the second uh towards the end so it's something like we are going to do a pancake swap for the first two numbers and it's going to be something like this then we are going to do pancake swap for the first three numbers and it is going to be something like two ones three and four after the step so on and so forth um so each time we try to focus on putting the largest number towards the end towards the current end and um so we are going to put to do that we are going to do almost two pancake flips so that's pretty much it i think uh so for this algorithm is going to be uh n square so n is the length of the array that is because uh we try to focus so we try to sort one number at a time and for to sort one number um you're going to do two pancake flips each pancake flip is going to be open recording runtime so in total it's going to be n square uh for the runtime so having said that uh let's do some coding work on top of this solution so first of all um we are going to so what are we going to do something like uh you're going to so each time we are going to try to focus on sorting one so num let's say num to sword is from us and the sort is larger than zero minus num to sort so every time you're going to focus focusing on sorting this number so the next thing for us to do is to find where the number is um so it will say idx num to sort it'll be anywhere so we start from the next zero so um okay so this in this formula we don't need to do anything and uh oh maybe something like all right next to sort it's not equal to uh num to sort plus idx time to sort something like this and by the way we also need to initialize the result we are going to finally return so i would say it's going to do very last something like that so here after we kind of find so okay so in this for loop is actually just the empty stuff don't need to do anything after that we have idx num to sort and though you're just going to let's say you're going to define a helper function so let me define hopper function so the helper function is going to reverse the sub array so it will be something like we have the array and we have the start index and we have the end index and we are going to reverse theory actually so i will just leave it as a to do and finish it afterwards so here after we find the corresponding index we are going to call it reverse of the array from zero until so until idx num to sort and then we are going to do like a reverse on top of array from zero to this is num to sort so now the swords minus one okay um so this finishes the thing but in the middle so here we also need to update the result here so result dot add uh here it will be something like a result dot add uh idx num to sort plus one and then result.add and then result.add and then result.add num to sort so after that we are going to just return the results and uh that's pretty much it so let's finish this helper function so here it would be something like um well okay so we just have this well start is smaller than end uh what we are going to do is in temp as equal to array dot start array start is equal to array dot n array n is equal to tap this is plus start and minus n i think that's pretty much it uh we will just rely on this platform to help us do the debugging okay so let's do some other testing all right so it seems like it works um let's try to okay so it seems like everything works well and that's it for this coding question so i have any question regarding the solution or regarding anything 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
|
Pancake Sorting
|
number-of-recent-calls
|
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
| null |
Design,Queue,Data Stream
|
Easy
| null |
228 |
Hello Hi Guys Welcome To Kalpeshwar Today's Question Summary Ranges In This Question Byagi Vanaspati Unique Interior And Better Returns This Molested List And In This Date Cover All The Number Hindi Are Exactly Dentist Italian Top Namaskar But By Yashwant Ranges And Ignoring Teacher X Dot X In Bhi mono friends but not in that so friends in one also in this list monk updates that agro benefits not equal to meat and eggs equal to be so let's understand this time with the help of example directly requested and unique suid 0124 57 and events which can for btc -2012 And Continues events which can for btc -2012 And Continues events which can for btc -2012 And Continues Unabated During Each Rate By One And Hair Cutting Actually 2012 Can Be Represented As One Range Butter 0124 Card Representative Vikas CO-0124 10 Card Representative Vikas CO-0124 10 Card Representative Vikas CO-0124 10 Best Wishes Not Mean That There Should Be Just To Do The Number In Incomplete Range Which Continue And Different 1051 Natural Anti National Number 124 Indore Se From Single Range And 7 Here Single Elements Of Vitamin B12 Single Range Sudha How To Will Be From CO2 10425 And 7 Days Without U I Example To Is Video 2 3 4 6 8 10 Vacancy Date 15012 Is Great And One Should Know This Encounter Single Bench Dandruff Tour To Three Four Continues In Nature And Different 1234 Can Be Called As One Range Dad 02-02-2014 Chhath Par 206 This Encounter Single 02-02-2014 Chhath Par 206 This Encounter Single 02-02-2014 Chhath Par 206 This Encounter Single Range Se Zordar Encounter Asli Single Bench And Ward No. 2004 Return Me Das Ka Putra Returns MP3 Whip Tantrums Hai Single Rally Only When Will Just You Return Aa Single Believe Only E 209 Let's Just Driver To Record Discovery Sport Forward Subha Field Of Twenty20 Only 15 Numbers And Size 1120 World Tour C First Character Of Witch To Return To Field First Minute Craft AVector Spring Also Nov15 Attacks Zinc Vitamin E Attempted Mother Has Been Know What Will Do It Will Take To Reverse Points 220 Ki End St End Physical To No Start Person Starting Point Of Creation And also depending on the age of old I will simply travel over and dark in a single pass only in 512 MB College develop of no s already been considered and I lashes Namaskar size and I plus a n c e I let the alerts for Reducing this simple test 0124 5700 start and both Vivo v5 youth no0 9 visiting a lot from one from kindle storecircle updates what will happen seat this time different plus one is 112 number site that in this case and 104 and answers-1 no One that in this case and 104 and answers-1 no One that in this case and 104 and answers-1 no One is equal to number dial early morning will do it is it means reduce problems of will also be taken into account of the current and more current range sweater dual updater and equal to phone number light bill updater and goldsmith starting point will be 0n more Point Offer Current Trend Is One Such Stupid Wing Commander Single Bench Know Him Till This Hidden Difficult Poonam Like And Imprisoned Decide It Means The Best Friend Plus One Is Not A Good Number After Seats First And 107 151 And Equal To One For Any Positive One Nine welcome to meet again when contacted condition dates and plus one is equal to two numbers of one plus one easy-to-read 250 per poonam site sud and easy-to-read 250 per poonam site sud and easy-to-read 250 per poonam site sud and updated 908 currently no current events for android 630 and it's two souls will smith attend plus One is not equated to plus one simply this is not equal to the number of seats in this world will do will form a series of this type of also stipend of network vector of string sweater dob that no that behavior from the particular and which they starting and important Features tattoo converted into a string into this format and painting and vep test draw the volume to condition button 212 just and not equal 20 form like this and fear and where issued a new uniform like this morning first draft bill check weather then start this 112 and Which suit network sunshine will take a string Not able to edit and easy case what will you declare stuffing extend will contain two strings a tourist in start that boat x plus is equal to get started and articles will have a growing but instead she told oh and Andher Nagari Express Equal To The End It's Two Strings Tu Hai Na Mein Naav Doobie Brothers Ped This Vector Discern To Our An Answer Actor Latest B Subha Kuch Bax Noida Extension Sarovar Subha Ek Number Six Digit Number And Have Already Been Formed A Strange And They Need A different * are in Strange And They Need A different * are in Strange And They Need A different * are in 12th but nowhere to know update start and end position also morning sun start 2012 number six which hair narmada river delta force and logical 2nd gautam like this yesterday morning pendant also start and position in air tight and position in all the Condition of final edition soon after 10 rupee dollar vacancy date of birth over wide IT and auto sector will contain other inch add this 4258 will not contain during last days will not be plastic note also acidity final back service tax return for this short encounter today and Last Not On The Matter But Will Do Will Simply Repeat Difficulties Exactly 2010 What Will Happen And Wealth And Sifiso Not Include Some Will Repeatedly Step Also Again A Reduced Episode Ata Last Can Also Be Included In The Final Actor Sudhir Chaudhary And Tire Code End Chapter This And after disco divisions in the written e 's brilliance setting on that is justin bieber gandhi a vector vikas navdeep actor will contain buddhi rangers all the avengers west and with indian tourism return gift from here election near code that medical that dedicated volunteers were submitted 13000 patients Prayog Aisi Lady Video Thank You A
|
Summary Ranges
|
summary-ranges
|
You are given a **sorted unique** integer array `nums`.
A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive).
Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,2,4,5,7\]
**Output:** \[ "0->2 ", "4->5 ", "7 "\]
**Explanation:** The ranges are:
\[0,2\] --> "0->2 "
\[4,5\] --> "4->5 "
\[7,7\] --> "7 "
**Example 2:**
**Input:** nums = \[0,2,3,4,6,8,9\]
**Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\]
**Explanation:** The ranges are:
\[0,0\] --> "0 "
\[2,4\] --> "2->4 "
\[6,6\] --> "6 "
\[8,9\] --> "8->9 "
**Constraints:**
* `0 <= nums.length <= 20`
* `-231 <= nums[i] <= 231 - 1`
* All the values of `nums` are **unique**.
* `nums` is sorted in ascending order.
| null |
Array
|
Easy
|
163,352
|
47 |
hi everyone uh today we'll be doing question 47 we code called permutations two so it's just like permutations one except this time the collection of numbers contains duplicates and we still want all possible unique permutations so in this case um if you haven't seen my video on permutations one uh you might want to take a look because i'm using the template from there and we only need to add two things to actually make this code work the first thing is we want to sort all the values the reason behind this is because we want to make all the duplicates uh end up next to each other so that once we do our iteration over here we can skip any of the duplicates that occur so we can say if zero so if the value that we're passing the same values of the one that represented before let's see if this works which is fine works just fine cool the right thing is still of n factorial because we're running over all the values in the numbers array and yeah that just about sums up for this question a pretty short one because you're only adding two things from my previous code um so with that i'll put a link to the question as well as my github down below and i'll see you guys next time
|
Permutations II
|
permutations-ii
|
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Constraints:**
* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking
|
Medium
|
31,46,267,1038
|
404 |
welcome back guys today we are going to solve lead code problem 404 sum of left leaves uh before we start looking this problem i just want to mention that i often create lead code solution videos in java technology and i also create java j2e interview related helpful videos so please check out my playlist it has a good amount of stuff in it like it has lead code solutions bfs dfs dynamic programming and linked list related videos also it has a videos for java that we interview questions and answers so please check it out and please subscribe to my channel now the subscription is really helpful so let's look into the problem so given the root of a binary tree return the sum of all left leaves so this is the binary tree that is given to us and we have to return the sum of the left leaves right so let's take this example over here so uh we are going to solve this problem using recursion so what we are going to do is we are going to traverse the binary tree from top to bottom from root we will start and every node we visit we will ask the question whether it has any left node which is a leave right which is a leaf so leaf node is a node that does not have any left and right children so we will ask now we are at 3 which is the root right so we are going to go left and go right so when we are going left we will ask first when we are visiting three we will ask do you have any uh left leave right left leaf so it will check if nine is the left leaf it has so three will say that i have a left leaf nine so it will give us the sum is equal to sum plus nine so our sum becomes nine right so then we will visit nine now again we will ask do you have any left leaf here so there is no left leaf right null so nothing will happen so sum will be zero in case of null right so uh we will our sum is still nine so now we will go and we will visit 20 so 20 when we are visiting we will ask again the route 20 do you have any left leaf so it will check if it has any left leaf so yes it has a left click 15 right so it will add 15 to our sum so it will become 9 plus 15 which is equal to 24 right so 24 now when we are visiting 15 do you have any left leaf no right it is null so it doesn't have any left leaf when we are visiting 7 also do you have any left leaf no there is no left leaf right null so we are done we have visited all the nodes of the tree so we will return our sum as 24 right so that's what you will see here the 24 is coming so that is the implementation uh using recursion so i am going to show you the recursive function that i implemented so first thing i will show you is i implemented a helper function here called as is leaf so it takes the tree node and it checks if it is a leaf or not right it just checks if it is leaf so it checks its left is null and right is null and it itself is not null right then it is true it will return true otherwise it will return false so it checks if the node is leaf so now we will call the recursive function from the main function and we will just pass a root here in the recursive function we have defined a sum variable 0 and whenever root whenever node is equal to null right then which means that when it is checking if it is a left leaf you know it will uh when it finds its null then we will just add a 0 to some right because there is no any left leaf there so we will just add 0 and we will return a sum from this function okay and otherwise it for every node that we are visiting we will check if is leaf right we will and easily we will pass its left child here see we are passing the left child here and we are checking if its left child is there and it is a leaf if it is the case then we will add that nodes left value into the sum right for example if we are at 3 node 3 we will add 9 value here into the sum right so that's what we are doing i just uh have this println to show you that the sum how it prints the sum actually we i will just show you and then we will take it out and then after we are done with the is lift check then we will just recursively call the function because we once we visit three we want to visit the left sub tree and the right subtree so that's what we are doing we are calling the recursively we are passing a left node here and we are passing the right node here because we have to we want to visit the left sub tree of the node that we are visiting and the right subtree of the node right so that's what we are doing and finally we will get the sum out of it and we will just return the sum so that is the approach and these are the test cases that are given to us here so let's just quickly run and make sure it's working fine so as you see here so sum is 9 first and 9 plus 15 it will add and it becomes 24 right so that's how we are getting the correct result here so we will just remove the sum or just comment it out and we'll just submit and make sure the submission is working so our solution is hundred percent faster and it's zero ms and on the memory also it is 94 so it's pretty good so this is a solution that we have for some of left leaves so it is just recursion so it's just question if you understand the recursion of the binary trees you know you can easily solve this problem i am going to add this solution into my github repository and i will give you the link in the description check it out i already have placed a lot of code in my github repository about lead code solutions and other things so check it out there um also please subscribe to the channel you know it's helpful if you subscribe to the channel it uh so it can reach to more people thanks for watching this video
|
Sum of Left Leaves
|
sum-of-left-leaves
|
Given the `root` of a binary tree, return _the sum of all left leaves._
A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 24
**Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively.
**Example 2:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
297 |
hi folks today we are going to solve some tree civilization and destabilization problems the first question is the code 297 and we are going to serialize and decelerate the banner tree if you haven't raised this problems you can spend some time so let's see how to solve it first of all the root note is one so we can write a one here and we need to leave some blank since uh for the most naive question for the most naive um solution we are going to use the two string method to convert the integer to a string since some sign integers for example 1000 the lens is for ten thousands lens is five so the lens is not fixed so we need to write a blank here so for two we write it like this can we write three uh write of two now since we don't know if three is a chart of node two or if three is a child of node one so we need to write the noun node here it's very important in civilization we need to write the noun node so okay next we can write 4 and which is a noun node and we can write 5 with this non node okay so let's implement it okay so for this series and we can pass we have data then we call serialize we can pass the root node and um and data and we can return data okay let's implement the serialize function can pass this train node route here and we can pass this data as reference data so how do we serialize it if uh if roots is a non-pointer you can write a and we need to push back blank here okay return otherwise we need to write the value first so we need to do data plus yes to string root value and we can push back a blank okay and we just serialize that left and right parts texas serialize function let's implement the dslr function this live function since each token is separate separated by a blank firespace yes so we can use string data okay stream and we can just return deserialize data of ssc okay visualize function return a tree node okay first and we need to read the net next token if token starts with if your token is a non-node if your token is a non-node if your token is a non-node okay and we can just return the non node otherwise it's just it's a normal node so we can use um s2i to get the integer and we can um new this node new tree node v then can visualize the left part and the right part i can't return this no okay let's see if it works unknown type is string i can check c plus class let's change string okay sharpies says live stream okay this relies on type name stream okay oh so nice 9117 we can make yourself for the function okay since it works yes but um for this solution that's one problem for example sometimes the integer let's say on an integer is less than one thousand the length is less than four but most integers let's say maybe um ten thousand one hundred thousand when serialize them size of them is greater than 4 on average so we are using more space and we are also using some space to separate each integers since the length of each integers are after serialization they're not fixed so we need to add a space it's a way to make the integer unfixed so and there is another solution uh first we can write a byte if it's not a noun node we can write first if it's a noun we can write true anyway we need to tell you if count node is none or not now for example the first node one is it's a normal node it's not a no node so we write on zero then for the integer one it's an integer it's four bytes so we can copy the four bytes here and for two it's a normal node so we need to append the first bytes but to have has two um non-children has two um non-children has two um non-children so we need to write choo after two then three is not a noun so we write first then write three for four when you write first four then we need to add two here since two four has two and non-children and five also has two non-children and five also has two non-children and five also has two non-children non-children non-children so we need to write two true after five so this is how we serialize it let's see how to implement it reset okay for serialize first very similar string data serialize use data return the data void sterilize okay let's change the time okay first if our shoots is now we will append a bit it's a no node so we can just push back a y here it's a now node otherwise we will add a node here it represents true it represents force okay now we need to copy the four bytes of the integer to our string how do we do it we can use destination sauce okay the destination is buffer sauces roots value size of lint okay then we can for loop data push back buffer okay so we serialize left children and the dry children okay let's see how to visualize it for this one we cannot use string stream since there is no space between each token so we need to pass index serialize um data position okay train node data position okay first we need to read if it's a y or no okay right yes no node if it's y then it's a no node okay switching plus okay if it's normal we just return a no node otherwise i need to um when you get the value you can use and copy the destination sauce size of the end okay position plus size of it we consume the data so we need to move the position okay train node new train node let's see it's then we deserialize left path and right part finally return the node okay and copy okay this now node going to return okay it works okay now we solve this problem let's take a look at another similar serialization problems this one is a bit different previous one the tree is normal tree now this one is a binary tree so for binaural surgery it's very similar to the previous one but um as long as we keep the count minimum value and maximum values and we know how to visualize it for example previously um for this three if we use this dial we don't know three if the children of two or one but if it's a binocular tree then we can determine it let's see how it could look like so first series is very similar in this case we don't need to write if it's non-node on it's non-node on it's non-node on not now node if it's not we just return then we copy paste the integer to this buffer and write the buffer to data it's same next we just serialize left part and red part but how to like how to visualize it since it's a binocular tree so we pass the minimum value and the maximum value here for the root nodes and maximums that they don't have any limitations now we need to reconstruct it this is not necessary actually first we have the value and we need to uh we can use memory copy to get the last next four bytes to our value if the value is not within my range then now this value does not belong to me it belongs to other nodes so i can just return now otherwise i can just new node and move my position and digitalize my left children and right children then i can just return this node actually we need this code since um for example for my last node it has two empty children but at this time um if i don't have this line i will copy and the four bytes from my buffer but i already use up my buffer if it's my last node since i'm if it's my last leaf node i will call i will try to visualize the left children of my last node then i will go to this reconstruct function again but now position is my like my last position if i use my memo copy then there will be some memory error memory access error so when we need to keep this track yeah okay yes and now let's take a look at an airport interview question the question is where we have a banner tree and for each node the value is a character the character is from lowercase a to a location and from up can be up case a to up case c those question is how to serialize it and visualize it of course we can use the solutions in problem like 2 9 7. let's see how much bytes we need to encode each e um to encode each node we need to write uh like a true or force and we also need to write the data so for each node we need at least two bytes and we also need to write the num node it's a better way to achieve this let's say is a us let's say a smarter solution so we can use six bits to encode this data since we this will only have 52 possibilities for each node right from low case a to locate c and from up case a to upgrade c so two to six just six hit four so we can use six bits to enclose the data and we can use one bit to tell if we have five children and we can use one bit to tell if we have right children so to link code f it will be like lex disease we can hard code like uh the lowercase a is zero locus b is one location c is to locate the s3 so anyways this we don't care about this first six bits here since f has left children right children so the knight two bits is one for d the next two bits is zero since it does not have left children not right children and for the uppercase f it has one for d is zero for a is zero okay so the in implementation is not very difficult when serialized for each node we have the character then we can just look up our table to um then we have a variable and there's a first six bits of this variable we use them to encode data then we track it with tests left children and right children if it has have children we write out one bit here if it has a right children we write another one bit here yeah so um that's basically the knowledge about trade serialization and we know how to serialize and decentralize a normal tree we know how to serialize and deserialize a burning tree and we also know how to use some tricks like to like and to better serialize the data let's say two inc and two civilizations we only use five bytes right so it's a very good solution and this is almost everything thanks
|
Serialize and Deserialize Binary Tree
|
serialize-and-deserialize-binary-tree
|
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,2,3,null,null,4,5\]
**Output:** \[1,2,3,null,null,4,5\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
271,449,652,765
|
682 |
welcome to tim's leeco challenge this question is called baseball game you are keeping score for a baseball game with strange rules the game consists of several rounds where the scores of past rounds may affect the future round scores the beginning of the game you start with an empty record you are given a list of strings ops where ops i is the i operation and you must apply to the record and is one of the following integer x where we record a new score of x see a plus where we record a new score that is the sum of the previous two scores it is guaranteed there will always be two previous scores d record a new score that is double the previous score it is guaranteed there will always be a previous score and c invalidate the previous score removing it from the record it is guaranteed there will always be a previous score at the very end we want to return the sum of all the scores on the record so immediately we know we want to store the previous information we want to be able to pop it off so what's the best data structure for that it's going to be a stack right and really there's nothing complicated here we just need to calcul um write a if else statement fl statements and do exactly what they asked us to do so i think that's why it's an easy i also think that's why it's so down voted i guess people thought it was just too easy and kind of a waste of time but regardless i don't think it's a waste of time i think it's important to go over these easy ones as well let's go ahead and try um so we'll call it 4-0 in ops and try um so we'll call it 4-0 in ops and try um so we'll call it 4-0 in ops what are we going to do well there's four possibilities right so we'll start with the plus we'll say if o is equal to plus what do we want to do uh we want to take let's see the previous two scores and add that to our stack right so okay take our stack uh append the pre previous two scores so we wanted stack negative one uh plus the stack and we know there will be two previous scores always it's guaranteed and that should be it there else if o equals let's see d then we want double that previous score so we just take our append it's attack negative one and we'll double it multiply it by two otherwise else if o equals c we want to invalidate the previous score so we want to pop off pop um the thing at the very top of the stack right finally everything else should be just numbers but remember these are strings so we're gonna take our stack and we're gonna append an integer version of whatever this o is all right so after that just return the sum of the stack and that should be it let's make sure this works looks like that's working and that's it so that's going to be of n time complexity technically it's 2n but whatever um yeah i don't think there's anything else to add here so maybe you think this is a waste of time but personally i think it's always good to get these reps in so all right thanks for watching my channel remember do not trust me i know nothing
|
Baseball Game
|
baseball-game
|
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new score of `x`.
* `'+'`.
* Record a new score that is the sum of the previous two scores.
* `'D'`.
* Record a new score that is the double of the previous score.
* `'C'`.
* Invalidate the previous score, removing it from the record.
Return _the sum of all the scores on the record after applying all the operations_.
The test cases are generated such that the answer and all intermediate calculations fit in a **32-bit** integer and that all operations are valid.
**Example 1:**
**Input:** ops = \[ "5 ", "2 ", "C ", "D ", "+ "\]
**Output:** 30
**Explanation:**
"5 " - Add 5 to the record, record is now \[5\].
"2 " - Add 2 to the record, record is now \[5, 2\].
"C " - Invalidate and remove the previous score, record is now \[5\].
"D " - Add 2 \* 5 = 10 to the record, record is now \[5, 10\].
"+ " - Add 5 + 10 = 15 to the record, record is now \[5, 10, 15\].
The total sum is 5 + 10 + 15 = 30.
**Example 2:**
**Input:** ops = \[ "5 ", "-2 ", "4 ", "C ", "D ", "9 ", "+ ", "+ "\]
**Output:** 27
**Explanation:**
"5 " - Add 5 to the record, record is now \[5\].
"-2 " - Add -2 to the record, record is now \[5, -2\].
"4 " - Add 4 to the record, record is now \[5, -2, 4\].
"C " - Invalidate and remove the previous score, record is now \[5, -2\].
"D " - Add 2 \* -2 = -4 to the record, record is now \[5, -2, -4\].
"9 " - Add 9 to the record, record is now \[5, -2, -4, 9\].
"+ " - Add -4 + 9 = 5 to the record, record is now \[5, -2, -4, 9, 5\].
"+ " - Add 9 + 5 = 14 to the record, record is now \[5, -2, -4, 9, 5, 14\].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
**Example 3:**
**Input:** ops = \[ "1 ", "C "\]
**Output:** 0
**Explanation:**
"1 " - Add 1 to the record, record is now \[1\].
"C " - Invalidate and remove the previous score, record is now \[\].
Since the record is empty, the total sum is 0.
**Constraints:**
* `1 <= operations.length <= 1000`
* `operations[i]` is `"C "`, `"D "`, `"+ "`, or a string representing an integer in the range `[-3 * 104, 3 * 104]`.
* For operation `"+ "`, there will always be at least two previous scores on the record.
* For operations `"C "` and `"D "`, there will always be at least one previous score on the record.
| null |
Array,Stack,Simulation
|
Easy
|
1720
|
225 |
hey everyone it is this side hope you are doing good so let's start with the question so the question is implement stack using queue okay so basically you have given a stack obviously you have to implement the stack implementation using the queue so as you know stack is a la last in first out stack so it's a lifo structure follow so what you have to do you have to instead of using stack you have to use two queues okay the implemented stack should support all the functionality of a normal stack like push top pop and empty so push basically means you have to insert the element in the stack pop basically means remove the top element from the stack and top will this stop will return the top element from the stack it's not removing just giving the peak element of that empty basically returns true or false whether the stack is empty or not okay you must okay so let's see how we can approach this question okay so let's understand with an example let's assume we have a stack okay so first step is to create a stack we will create a stack then we have to push the element so let's say we push this element in a stack okay so we push this one now after this we again push the element so we'll push the second now what we have to return top element okay so if you can see top uh it is 2 so we just give the output as 2 after this we have operation of pop so we have to remove this and print it so we'll print 2 also then there's a function for empty so we'll check whether stack is empty or not you can see stack is not empty so we just return false for this case okay so now what you have to do instead of stack you have to use two queues basically okay so this is one queue this is second queue q1 q2 as you know stack follow lifo structure basically whoever comes last will be the first will remove from it okay and q is just opposite of that q is people so whoever come fi where come first he will be the person who will come out of that queue okay so if i give you an example so you can assume a banking line and the first person whoever come to the particular line he will be the first who will uh get out of that line okay so let's see how we can do the same problem with the queue okay so let's assume what we will do we'll use 2q so we will take q1 as this and q2 as empty okay both are empty we initialize it okay so we have to uh let's take an example and then i will give you that example so first we will do we will push the element okay so we will push the one so let's say we will push in the q2 okay we push it and now after this what we have to do every time whenever we push it we will do something in pop we just remove uh give the top element of q or remove the top element from the q one but whenever we push in it we will do our order of n operation basically or you can say order of q two dot length operation at the time of push so what we will do we will take this q uh like we will pop the element from the q one and push it to the q two every time okay so it's like q one dot length so yeah now you can see q1 is empty so there is no element so we don't have to push anything inside this after this what you will do you will interchange them okay so q2 q1 become q2 and q2 become q1 okay so now again we have a call for push so now the second item is second okay so we have to push into the basically q2 so we'll push into q2 so now this is become q2 now you push into the q2 now what you have to do you have to remove every element from q1 and push it to the q2 only okay so we will pop this element and we will push it so this will be our top element this will always come first then this okay after this uh what we will do we will again interchange them so q2 will become q1 and this will become q2 okay so you got the idea why we changes because this will be always our top okay and we will always get a recent element at this position okay so let's say this is 2 and we have a q1 as top as 21 okay now we have a top element so we'll just directly give the top element from it now we have a pop element we will pop it from here okay so we only have one left now after this empty we will check the q one size and cuban size is also not empty so let's assume there are further conditions so we need to pop push uh three we need to push seven okay these we need to push okay so first step what we will do we will push it into the q2 okay so right now q2 is empty so we will push it and what we will do we will insert every element oh sorry the element is three so we will insert three this is three so now after this we will pop all the q1 so q1 will be popped and we will insert it here so why we are popping it you can see like the recent element is always come first but that's why we are removing every element from one queue and insert it into the other queue so after this will again interchange so this will come q2 is generally every time it will be empty only in q1 okay so what we will do after this again seven will come so we'll insert into q2 and we will basically pop all the element from q1 so this is having seven then three then having a one so as you can see this is following a stack if i have a stack also my seven will be before then three will be then the one only so by this again we interchange them and q1 and this is q2 so by this we can solve the problem so it's pretty implementation question so you can do like i have taken order of an operation on push operation but you can and my pop is order of one and my top and empty is also out of one what you can do is instead of doing push of order n you can do pop of order of n and your push can be in order one either one of them you can do it okay so let's write the code with this so what we need a queue so queue of integer q1 q2 okay we'll initialize them in the constructor link list okay in java we don't have a direct implementation of queue so that's why we use the interface implementation class of linked list then we use q2 okay link list so let's do first pop okay so what we will do we just have to return q1 dot remove okay in top what we have to do we just have to return top element so q1 dot peak basically means top element in empty uh if q1 dot size is equal to zero so we just give them okay so first step is to uh insert new input basically new element in q2 okay then you have to what you have to do you have to take all the element from q1 and insert into q2 after this you just have to swap q1 q2 okay so first step is pretty simple we'll q2 dot add x okay after this what we have to do we have to insert all element from q1 so what we will do while our q1 is not empty we'll insert in the q2 so q2 dot add q1 dot remove okay after doing like after taking all the element from q1 to q2 you just have to swap the name basically we are making q1 as a priority you can say it is more uh that's why we are just popping the q one only and taking the top so it is a main cue you can say so what we'll do list basically linked list of integer temp basically swap we are just swapping it so q1 equal to q2 and q2 equal to temp i think we have done with a good so let's run it okay so there is some mistake okay sorry it will be our type q only why i have taken in teacher yeah let's run it so this is accepted let's submit it yeah our code is submitted hope you like it thank you for watching video and do join the telegram group if you're in doubt in any concern thank you
|
Implement Stack using Queues
|
implement-stack-using-queues
|
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
* `void push(int x)` Pushes element x to the top of the stack.
* `int pop()` Removes the element on the top of the stack and returns it.
* `int top()` Returns the element on the top of the stack.
* `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
* Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
**Example 1:**
**Input**
\[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]
**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
* All the calls to `pop` and `top` are valid.
**Follow-up:** Can you implement the stack using only one queue?
| null |
Stack,Design,Queue
|
Easy
|
232
|
258 |
Premature Ejaculation Sir Azamgarh will put the question, it was a game like Welcome game, meaning that if you get scared after seeing this question, then you will not have any question. You have subscribed to the fun, its questions were about thought process, it will take a lot of time, complexity will be very high and there will be problem in it. Have put it and there is one small thing in it which I would like to tell in the question and if you do not put the second thing then you will be taken away in it. The meaning of taking the Right IS people was that now the concern is about every video of every question. Is it equal to a question? If the video can be consistent for the people who are watching, then for them the question of which genre do you ask first? People who watch new videos immediately do that while reading the question first. Something different, 10 minutes, 15 minutes, 20 minutes, in this you give the last time and after that, if you are able to do it, well end, you can do all the videos and service tax and how could it have happened that it has not been done, otherwise still watch the edition. Can at this time let's see the question understand what the question is saying and absorbed in they must have tried and the question what the question was saying then very simple step given to us eighth and if is typical given that it means that when we What we have to do is first reduce this number and reduce the number until this number comes into a single unit like if we set three plus the dead skin label of the right face then now the number is 3111. Gone but what will we do with Rahul Dravid again What has OnePlus One become now Will spread it again oneplus 5 subscribe ki sex cut off so if you do 100 it means ke oneplus sure give you number start giving till then you should subscribe the channel soon 178 286 so this if we know this number is here So 16 number 10 if this number if we in this if we then it is very easy and for us and 5216 acid today we can perform what we can do, we can calculate it, now I have to add everything with this digit. - Waterfront Bus Where do we students - Waterfront Bus Where do we students - Waterfront Bus Where do we students study that they do not get digit from this number, tracks and this hands of experience should be there by coding you that you will be but the problem is Amla number is given to you, how can you convert it into digit, understand this completely. After the game, the question is based on a rope game, that is why 123 was changed to 1234, so if we turn on the mode by 123, then divide the chords by 123, melt 120 letters, these are maximum 11 numbers, then what do we do? Let's update the number 123, whose number is it, tension will be placed on it 123 510 means divide the 12th forum tan 123 a little above it sky system is collapsed tube will be our number again we will apply it and repeat in it If this tour ladlo tank work comes then give three grade two marks and will update the number again on this. Well mom brother 10:30 Well mom brother 10:30 Well mom brother 10:30 Swarajya Bhawan will do this thing again one model o 10th instrument very good One has got take off but how will we update the number will become 1 white Aishwarya's personal phone take off and if we do 108 then this is zero two what is the rose something what is zero point will make take this is what will come 0.1 approx will make take this is what will come 0.1 approx will make take this is what will come 0.1 approx interior mein ka Europe and for how long will we keep doing this until we get zero in the last and till then we will get all the single digits one by one, ok 321 so this logic if this number if 10 is not there then Nuvve is running like 123 Called number 123 Edison and passed 123 in it. Now inside this we check what is there and what is not. We have stored what in 123 model means make third front and updated the PAN. 12332 subscribe Chanakya is equal to 200. Otherwise Times will come with 12th model Paper Tenth means that there is no problem to record and instead of Tubelight it means that we will print this WhatsApp to take from its Kia K10 is not equal again Times is equal to One Model 800 Alto 151 Friends Karna Vikas Okay, it will be done on that N equal to one white means that 108 illegal gravel will be done then we will come out of it and this function executive 321 mix single number will be found it means that this function you have understood that. How is it working, how can we find the digit of a particular number, we have understood the rate, now our job is what can we do, how can we take advantage of that digit, what benefit can we get from it, we will give it a big number, 6786, we will What did the number do and look at the number to see what it stands for, meaning the big Hindu society, if it should come from zero to nine, not by breaking the number in the middle, converting the number, changing the number, if we do the number eight, then first of all we are the people. Know this means scalp, will give it a number, let's use the number, reserve the number, if greater than know it means that current means [ if greater than know it means that current means that that that they will update the number and pass this number If we give, then what sin have we committed and we will set it again, it will continue as long as we give numbers, if you subscribe to this channel, now we need to play, work, boil oil, numbers are not equal. If life is till number zero, then what do we do? These are the symbols that make a single digit. This is a single digit. This digit is placed above it. This digit will be more understandable. What does this digit mean? End model to airplane mode 9 inches and what to do with this digit. Do n't know and after updating this test and then update the number so that there is no problem in name bike tension or name will come but brother you will have to use this digit and course and you tell me how the number is doing exactly by adding every edit. So what we do is create an intermediate 042, keep updating the time, track the digit, no problem and what we do in the last one, we return everything, what we did, what is each two digit doing, the pair on the number will be repeated. Will take it, he is doing it and after adding it in the last, let us make it simple and subscribe, if you like, do n't forget to subscribe the number, do battery saver code, watch this video from office and you will understand how much your thought process is after watching the match video. After this, it depends on how much you give it, so if you like the video then please like, share and support my channel by subscribing to it. 1958 scrubber users are going to use it and if you can support people then thank you more and if If you have n't done so till now, then please remind me that there are job gates and there is a post next post, so this will be helpful for you, till then bye-bye [ will be helpful for you, till then bye-bye [ will be helpful for you, till then bye-bye hua tha mez
|
Add Digits
|
add-digits
|
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
|
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
|
Math,Simulation,Number Theory
|
Easy
|
202,1082,2076,2264
|
347 |
welcome back to code Meets World today we're looking at leap code number 347 which is top K frequent elements in this problem we're given an integer array called nums and an integer K and we need to return the K most frequent elements and we can return this in any order so looking at the examples in this array with k equals 2 we need to return the two most frequently occurring elements in the array so we can see that's element one which occurs three times an element two which occurs twice so that's what we output is the solution and down here K is just one and there's only one value in the array so we just output that so at first glance this problem looks pretty approachable but I think there are two distinct things that we need to do here the first of which is go through the entire input array and count the occurrences of every different value and then second we need to go through and pull out the K most frequently occurring terms so basically count everything first so I'll make that step one Step One is count and then step two is find top k so if they want just the most frequently occurring word we'll return that if they want the 10 most frequently occurring we'll return that so I'm going to talk about these one at a time so first the count anytime that I need to do counts I'm always thinking about a dictionary so this case is going to be no difference I think so what we can do is we can Loop through the entire input and each time we get to a number we can just add that to the dictionary and then we increment the count each time we find something new so what we'll end up with at the end is each value that's in each distinct value that's in the array and then the count of how many times we see that so this is just showing that element one occurs three times elements two occurs twice and element three occurs just one time so I think that's the first step just iterate through the whole array and build these counts now I think finding the top K elements is a bit tricky because if the task was just to find the top one the top two the top three if it stayed the same every time we could simply have for example Max One and Max 2 say we need to find the top two things and then we could just insert the first two elements here and then we could just go through and compare to those values and just update them over time but we can't do that here and that's because there are the number of values we need to return is a variable we don't know what it's going to be at the start of the problem so if you watched some of my previous videos which I'll link at the top of the screen right now or you're familiar with heaps I think that's actually going to be the secret to doing this efficiently if you haven't seen or don't remember what heaps are that's just basically a tree data structure where the smallest value is at the top the root of the tree and then all values below the root uh increase in value so for instance we could have a one at the top a two here a seven here we could have a three here and a four here we could have a ten and a 50. the only requirement is that the children of a root have to be a larger than it so this is just one example of that but what's really cool about heaps is that when you add something new or remove something you the Heap automatically re-updates itself to automatically re-updates itself to automatically re-updates itself to maintain that heat property so for instance if I added a 12 to this Heap it would figure out that the best place for it to go um would be perhaps over here and it would just do that automatically but if I inserted the value that needed to go up here for instance the Heap would update itself to account for that and when we remove something we're always removing from the root and then the rest of the Heap will update Itself by moving the two up to the top um so that the Heap maintains its property so why am I telling you all of this well I think what we can do is create a heap that is size k and then as we so basically we have this dictionary first then we create a heap of size k and the reason that size K is that we'll start by adding K elements to it so for example the first two and then as we consider more values from this dictionary we can see hey is the value that I'm considering now a larger than the value at the top of the Heap and if that's the case we can remove this value and add this value so let me show you an example of what I mean by that using this dictionary here I'm not going to do it in this order or it won't work as well so we don't know what order we're going to get the keys when we're iterating through a dictionary so let's say we're going to start at the bottom and move towards the top how we can do this is say okay we're going to create a heap and we'll start by placing this bottom value in it and a quick aside this Heap here I just put integers in but there's a really cool trick that we can use if we want to store more than one value in the Heap so for instance here we want to store and keep track of the counts but remember at the end of this problem we need to return the actual number not the count so we need access to both of these values and we can actually store both of those in Heap by using a tuple is just a list with for example two elements in it and if we insert a tuple into a heap it will use the first value to keepify the all the tuples so it'll look at the first value and use that and keep the smallest one at the top and so this is perfect for our use case because it'll keep the smallest count at the Top If we put count here and if we put the actual number here in y we'll have all of our values in the Heap which is perfect so back to what I was saying we'll start by putting this three one into the Heap so then I would insert again we'll put the count first so the count is one and the value is three we'll put that first next we'll put two our Heap is still too small because K is 2 and we want our Heap to be as large as K so we just add 2 in the same way and the value 2 is larger so it would go as a child of the Heap and this would happen automatically when we add it now when we go to add the last value we notice that the count is three and because the Heap is already of size K we need to check okay is this count larger than the count of the topmost value in the Heap which is the smallest and it is 3 is larger than one so what we need to do is remove the root so we're just left with 2. and then we add in the value that we just saw which is 1 3 and because 3 is larger than 2 in terms of the counts it would be a child and we would get this and now we're at the end of the dictionary so we would just be able to look at our Heap which is this and we could just extract uh not the counts but we could extract the two numbers that are associated with everything in the Heap and that would give us our solution of two and one the first step is like we talked about we're going to calculate this count dictionary so I'll call it counts I'll set that'd be equal to an empty dictionary and then I can iterate over each num in nums and I can check first of all if num is in counts if it's already there then we can say counts numb plus equals one so if we've already seen the value we'll just increment its count by one uh one if we haven't seen it before so and else num is not in counts we need to add it so we can say it counts num and we can just set that equal to one because it's the first time that we're seeing it so that's how we can build a very simple dictionary that counts the occurrences of everything so what we'll be left with is counts will equal something that looks exactly like this so that's perfect step two is finding the top K values so like I mentioned we need to create a heap and another name for a heap is sometimes a priority queue you might hear that but I'm just going to call it Heap and I'll set it equal to an empty array and then I can call heapify which is a built-in python function built-in python function built-in python function and I can call that on Heap again um go watch my two videos about heaps if this is unfamiliar to you because I explained the syntax uh in that video so once we have those um we need to Loop over counts and we need to start adding things to the Heap so I can say and to Loop over a dictionary remember we can say four this would be num counts and not counts I'll just call it counts in counts dot items which will give us the key value pair of everything in our dictionary so for Num counts in counts dot items the first thing we want to ask ourselves is if bubble length of the Heap is a less than K because remember we want our Heap to be exactly size K because we're going to be returning the kale largest elements but based on count so the length of the Heap is less than K we simply just want to add whatever we have whatever we're on right now to the Heap just straight at it so to do that we can say Heap push again another built-in function keep again another built-in function keep again another built-in function keep push and you have to say the name of the Heap that you want to add it to in our case it's the Heap variable and then the value you want to add and now this is the important part remember that we talked about in this case we need to add these tuples because we want to keep track of both the actual counts which are going to get sorted and then we also want to keep track of the number itself that's associated with it so at the end we can return those so what I'm going to add is actually the Tuple of first the counts so we'll add counts and then second the none and like I mentioned count is what's going to be heapified and sorted from smallest to largest so it's important that count goes first here so that's our case if the length of the Heap is less than k if that's not true we need to check if we need to replace the root or not and the way we're going to do that is by checking if the new thing that we're adding is a larger than the root because if it's a larger that means we need to replace the root and add the larger because we want to keep track of the kale largest counts so to the to do that we can say LF and I have this wrong hello um we want to check if it counts count because that's the one that we're on right now LF count is greater than and to get the first value in the Heap so the root we can say Heap zero so this accesses the first value the root and then we want the count of it which is the first value in the Tuple so we can access that kind of like it's an array and just say zero so this is going to get the root of the Heap and the first value of that and we want to check if our current count so whatever we're whatever count we're seeing in the dictionary value that we've looped over if that's bigger then the roots value in the Heap that means we need to replace it and what we could do to do this is a heap pop and then a heat push so pop off the root and then push on the new value but there's actually a way to do these both at the same time which is a bit more efficient computationally and that's by saying Heap replace and we have to give it the name of the Heap and then we have to give it the value that we want to add on which again is another Tuple of counts and um Heap replace behind the scenes pops off the root of the Heap and then adds on this value so it does a pop and then a push automatically and it's just a little bit more efficient once we do that we have to do the part at the end where we iterate over everything in the Heap and grab these second values and put them all into an array and return that I'm actually going to use a list comprehension here for Simplicity if this doesn't make sense let me know in the comments and I can also write out the way you would do it with a normal Loop but we can just return a list where we take value one so the second value of the Tuple for Value in keep so this is basically doing a for Loop where we Loop over each value in the Heap and remember value is a tuple and we want to take the second value of the Tuple which is the number associated with the count so let's see if we have any mistakes here it looks like that works on our two test cases so we will go ahead and submit and that looks like it's working so this is um a fun problem where we have to use both a dictionary and in my case a heap there might be other ways that you can do it but I thought this was a cool way to utilize some tools that we've learned by solving earlier problems in the neat code set to solve this one and if we look at our run time okay it's about as good as we can get so even though it's 50 30 percentile this is about the fastest you can do it so thanks so much and I will see in the next video
|
Top K Frequent Elements
|
top-k-frequent-elements
|
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
| null |
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
|
Medium
|
192,215,451,659,692,1014,1919
|
772 |
and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 772 basic calculator 3. implement a basic calculator to evaluate a simple expression string the expression string contains only non-negative integers a plus operator a non-negative integers a plus operator a non-negative integers a plus operator a minus operator multiplication operator and a division operator and an open and closing parenthesis the integer division should truncate towards zero you may also assume that the given expression is always valid and all intermediate results will be in the range of minus 2 to 31 to 2 to the 31 minus 1. note you are not allowed to use any built-in function which evaluates built-in function which evaluates built-in function which evaluates strings as mathematical expressions such as eval so if you haven't already seen my video on basic calculator 1 and basic calculator 2 pause this video and go watch those two because we're going to be using a lot of the same concepts that we used in those videos to solve this question which is really just a combination of the two uh but supremely more annoying because now we have to deal with parentheses and multiplication and division which just makes everything so much more of a headache but go watch those videos come back to this one and we're going to solve it so let's look at an example this atrocious looking string and we're asked to evaluate it so as you can see the output should be 21 but how do we get that well we know that we need to respect the order of operations so that means that we have to evaluate everything in the parentheses first so 5 plus 5 times 2 so obviously the 5 times 2 occurs first because of order of operations so that's 10 plus 5. so that means that this entire thing is 15. here 6 gets divided by 2 so that's 3 plus 8 so that's 11. so now we have 2 times 15 time uh divided by 3 plus 11. so we can do these in any order it doesn't matter so we'll divide by 3 first so that would this will become 5. so we get 2 times 10. sorry 2 times 5 plus 11. so this is obviously going to be 10 plus 11 and we get 21. so that's in theory how we solve this but how do we actually put together an algorithm because it's a whole lot harder to do this in code than it is just looking at it so let's think about how we can break this down and actually write some sort of solution for it i normally go through an example and kind of walk through how we can build out our solution in the diagram with a bit of a drawing but i've done that and it's really messy and i'm not going to put it in the video so what i'm going to do instead is i'm going to actually write the code out and then perhaps at the end of writing the code we'll actually just walk through an example uh and then kind of just go through it as if it was a real problem we can look at what the variables are and that way it's probably going to be a whole lot cleaner than me trying to draw it out with my mouse it just got way too messy way too ugly and it's not going to help anyone so let's actually solve this remember that we need a few variables to keep track of our calculation so we're going to say that the current number that we're working with we're going to set that equal to zero because obviously we haven't processed anything and the current operation is going to be a plus and we're also going to have a stack here which is going to hold our elements and in this question we're not actually going to be computing the result on the fly as we go from left to right we're actually just going to put numbers into our stack which at the end can be summed it's a little bit different from basic calculator 1 and basic calculator 2 where we were doing them in place unfortunately with this problem you can't do that you have to use the extra space and the way that we're going to do it is we're going to make it so that at the end we can just sum all the elements in the stack and that will give us our final solution so we need a little bit of a helper function to help us with the math here so let's define it and this helper function is going to take an operation and it's going to take a num and we just need to basically put things into our stack based on whatever the operation is and whatever our number is so we're going to say if the operation is a plus then what we want to do is we want to say stack the append and we're going to put the number in there else if the operation is a minus we want to say stack append minus num if the operation is a multiplication then what we want to do is say stack the append we want to say stack.pop append we want to say stack.pop append we want to say stack.pop multiplied by the current number and we don't have to unwind you know the previous operation when we see a multiplication because again we're not doing on the fly we have it set up that we can actually just uh add all the elements together so because we're doing this we don't actually need to unwind the previous result we can just do whatever the top of the stack is times the current number when we see a multiplication otherwise if we have a division we're actually going to say stack the append and we're going to put the integer of whatever stack.pop integer of whatever stack.pop integer of whatever stack.pop divided by num and again we just do regular division and we cast it to an int because uh when you're doing integer division in python with negative numbers it doesn't round correctly or at least not in the way that you'd want it to so to avoid that we actually just use uh regular division and the integer cast so now we can actually process our string from left to right like we did with the other basic calculators so we're going to say 4i in range len s what we're going to do is we're going to say if s of i dot is digit so basically if it's a number we need to process it and remember that it's not always just going to be single digits we can have you know multi numbers like one two three so we need to process all the numbers so we're gonna say num whatever the current number is times 10 plus the integer of whatever our current value is so s of i um if we have a left parenthesis then what we want to do is if you remember in basic calculator 1 when we have a left parenthesis we want to keep track of whatever the current operation is so that way when we come out of the parentheses we can apply the result of inside the parentheses with the operator and then the value before it so we actually need to store that in the actual um the stack so we're going to say stack.append whatever the current stack.append whatever the current stack.append whatever the current operator is and now we need to actually reset our number to be zero and we want to reset our operation to be a plus because remember it's as if we're starting fresh when we enter a parenthesis cool now if s of i is actually in um you know a plus if it's a minus if it's a multiplication oops multiplication if it's division or if it's a right parenthesis then we need to handle um those operations so what we want to do is we want to pass into helper our operation and the number and this is going to take care of handling the actual math for us and notice that we can actually pass in uh into operation uh a right parenthesis but here you'll see that we actually don't have a block to handle that so it actually nothing ends up happening um so we don't have to worry about passing in you know that left parenthesis the right parentheses because nothing's actually going to happen but that is a value that helper can take just nothing's going to happen so now we actually need to handle the case if it's a right parenthesis so we're going to say if s of i equals to a right parenthesis then remember that we just need to you know sum up all the elements inside of our right parenthesis and we can sum them because that's how we've been putting them into the stack we put them in a way such that we can actually just sum the result at the end and it's going to be no exception when we're in a parenthesis so what we want to do is you know set our num to be zero because that's going to be the value of the number uh inside of our parentheses and now we need to process it so how do we know when to stop processing well if you remember when we saw left parenthesis we actually put the operation uh into the stack as you can see and obviously this operation is going to be a string value whereas all the other values are going to be our numbers here and they're actually going to be integers so we want to process our stack until we hit the point where we see a string character and we know that we need to stop at that point we can apply whatever that previous character is which is going to be the top of the stack because that's where we end our iteration we can apply the value from inside the parentheses with the operation that was just before it to the value before that and that will handle the actual parentheses so we want to say while is instance so while the value at the top of the stack is actually an integer then we want to process those numbers we want to say num is going to be plus equals to stack dot pop and we're going to add all those numbers together while we're in uh while we have numbers to add right and obviously this is going to end when we hit this operation so let's now get it out of the stack so we're going to say op is going to be stack.pop say op is going to be stack.pop say op is going to be stack.pop and now we want to actually apply our helper function to that operation and the number to basically add that to our stack in the way that we want it to cool so now that we've done this we need to reset our number back down to zero because now we've processed the right parenthesis and we can continue on as if we're starting fresh and remember that the operation is just going to be whatever s of i is because s of i is one of the operations and we need to keep track of that as we go along so now what we need to do is before we can actually return our result we actually need to process whatever the last operation was because remember that we're going to end either on a number or we're going to end on a right parenthesis in which case we actually need to process those final numbers that we had because we won't have actually processed them if we just returned at this point so we're going to say helper of op and num is going to be the last thing we need to do and then remember we can just return the sum of our stack because we've said it we've been setting it up such that you can just sum it at the end instead of calculating it on the fly which doesn't work with this problem so let me just make sure i haven't made any stakes here and we can submit this and it runs cool and it does pretty well 96 of all pythons missions 94 on the memory so what is the time and space complexity of this algorithm well like the other basic calculators we do this in one pass from left to right so this is going to be big o of n where n represents the number of characters in our string and then space wise oops space wise um this is going to be big o of n again we have this stack here which is going to be holding our results in the worst case our basic calculator is not going to have any sort of parentheses it's literally going to be like 9 plus 8 plus 7 plus six oops plus five double dot it's just gonna be pluses uh and then we just have to store all these numbers into our stack and that however i mean however many numbers we store is gonna be dependent on you know the length of our string so we'll just say it's a big o of n solutions so that is how you solve this problem it's quite messy i would recommend working through an example uh one of the ones that lead code gives you maybe this more complicated one to see how it works if this didn't make sense i think it's pretty intuitive on how you want to do it is a little bit confusing if you haven't done basic calculator one and two i would highly recommend you go back and do those because it is um very beneficial for you otherwise thank you so much for watching this video was an absolute pain to make it took me so many takes this question is really annoying to make a video on uh it's i wish i could just write the code and not have to explain anything because yeah i just have a headache now anyway thank you so much for watching if you enjoyed the video please leave a like and a comment it really helps with the youtube algorithm if you want to see me suffer through more of these hard google questions then please subscribe to the channel i have tons of videos for you and tons more coming out just subscribe to the channel so you don't miss the uploads and otherwise thank you so much for watching hopefully this video didn't give you a headache as well and have a great rest of your day
|
Basic Calculator III
|
construct-quad-tree
|
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, `'+'`, `'-'`, `'*'`, `'/'` operators, and open `'('` and closing parentheses `')'`. The integer division should **truncate toward zero**.
You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`.
**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
**Example 1:**
**Input:** s = "1+1 "
**Output:** 2
**Example 2:**
**Input:** s = "6-4/2 "
**Output:** 4
**Example 3:**
**Input:** s = "2\*(5+5\*2)/3+(6/2+8) "
**Output:** 21
**Constraints:**
* `1 <= s <= 104`
* `s` consists of digits, `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
* `s` is a **valid** expression.
| null |
Array,Divide and Conquer,Tree,Matrix
|
Medium
| null |
1,716 |
hey everybody this is glav this is day six of the Leo day challenge hit the like button hit the Subscribe and join me on Discord let me know what you think about today's PR uh today I have no intro just because uh I'm actually doing in the morning uh and I didn't find for it but uh but the timing actually worked out today so I'm going to do it a little bit earlier um so yeah let's do it today is SP and I'm still in kenting here in Taiwan it's beautiful here as you saw from yesterday Central so check out yesterday's intro if you missed that one but uh yeah today's problem is 1716 calculate money in lead Cod bank okay hery wants to save money for his car what's hery is that a name okay uh his he put money in the Le every day one down the first day Tuesday he puts one down one the previous Monday okay so basically uh I mean let's see what's n is a thousand okay N is a th means that you can do it but that's a little bit silly um I'm trying to think whether there's a smarter way to do it I mean obviously we can like for Loops right we're all smart people here um okay so how many four weeks are there I mean I'm going to write it out so that it's less confusing because you could probably do it one lineer right so four weeks is you go to that right and that is of course um so the first week it's going to be 1 plus 2 plus 3+ 4+ 5 plus 6+ 7 right so plus 2 plus 3+ 4+ 5 plus 6+ 7 right so plus 2 plus 3+ 4+ 5 plus 6+ 7 right so uh what is that I'm trying to do it in my head but I am being dumb uh what is it 20 uh 28 uh 10 15 + 13 28 yeah 28 uh 10 15 + 13 28 yeah 28 uh 10 15 + 13 28 yeah 28 right um but that's the first week second week is bigger by seven so then now so that means that first week is going to be 28 and this is 28 is just you go to uh Magic constant here um first week is you go to 28 1 plus right and then now the second week is going to be seven more than that and then the third week is going to be seven more than that right so now you have this progression of uh 28 so now it's first week times it's full weeks R right full weeks times first week uh that's fine but then now you now is this plus some progression of um of 7 times zero for the first week plus 1 plus 2 plus 3 plus four dot right uh so and this is going to be the number of weeks so it's going to be four weeks times 4 weeks Min well this is actually technically minus one times 4 weeks minus one + one minus one times 4 weeks minus one + one minus one times 4 weeks minus one + one that's how you get the four weeks and then div by two right and this is just a really standard formula hopefully just will make sense and then yeah so that's basically all the four weeks uh time right but now we have to get the partial weeks so uh what is it four total maybe how for that right and then now the partial weeks now um H that's actually a little bit tricky right so well so uh how naming things is hard as well partial weak is equal to and mod 7 right that's the number of days that you have left over um to do but that is also um dictated by so the first week it starts at one the second week you start at two right so that means that your four weeks plus one so okay so yeah have partial week times partial week + one over two right um and then you times that by four weeks because you start at that multiple together right no you don't times it by four weeks that's something wrong along the way no you start at this well there have ways to do it so you have this number and it this gives you uh you know 1 plus 2 plus three so then now you times it by or you add it by full weeks times partial week right because full week is also um the first number the offset of the first number I think that part makes it confusing so yeah but then partial I need to add some variable names to make this less confusing so but let me see if this is correct real quick it looks okay uh I mean if it's okay for 20 play is right but this is a mess to read so let's uh and let me submit right now because in the past I have done this and then I forget to submit and then the next day I'm like oh no I have to you know but uh okay looks good but uh yeah uh what did I say so okay so week offset is equal to four weeks which is what um okay let's comment this right how come my stuff was one thing uh number of four weeks right number of money on the first week uh maybe even one full week whatever the first number um first number of the last week right so then now the full total it's just going to be this part is straightforward and this is uh technically I think this should be weak offset even though I know that did the same where well obviously I mean we got it right but uh yeah then partial weak and then now this is weak offset yeah now okay right make sure I guess that was the only thing that we needed to do but yeah um that's pretty much my logic obviously you can do it with a full loop and you could also do that in like 5 seconds or something maybe I did the first time because I got lazy I mean I'm very lazy generally so yeah you can see it that way um but yeah this is obviously constant time constant space and that's what I have for this one uh you can also say linear time linear space depend how you want to say it uh the reason why you could say that is because um the space and return value is linear in the size of the input is not n the size of the input is the number of bits representing the number n which in this case is Log and confusingly uh and because the number of bits on the input is the same of the number of bits on the output and space uh and time uh well Tech I guess technically ad and stuff I don't know how I guess ad isn't technically necessarily linear but I guess in general it is uh multiplication I guess it's maybe not that gets into the reads but uh but yeah uh that's all I have for this one let me know what you think stay good stay healthy to your mental health I'll see y'all later and take care bye
|
Calculate Money in Leetcode Bank
|
maximum-non-negative-product-in-a-matrix
|
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000`
|
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
1,383 |
hello everyone welcome to codex camp we are at fifth day of june record challenge and the problem we are going to cover in this video is maximum performance of a team the input given here is again which represent the number of employees and we have given two integer arrays one is speed of employees another one is efficiency of employees and we have to select exactly k employees for the team and we have to return the maximum performance of the team here the performance is defined that it is the sum of speed of the employees selected into the minimum efficiency among their engineers so let's understand this problem with an example so here is a given input from number of six employees we need to choose exactly two employees where we have a team with maximum performance so here the performance has been calculated by sum of selected employees speeds plus minimum efficiency out of all the employees we have selected so now we are trying to select the employee number two and employee number five for our team so in that case the performance is going to be calculated as 10 plus five which is nothing but the speeds of the selected employees into minimum of both of their efficiencies so here the efficiencies are four and 7 so in that case minimum is going to be 4 then we are going to do this with 15 into 4 which is nothing but 60 that is going to be our output so how are we going to approach this so the first intuitive solution was if we are trying to maximize the performance then the values of speed and efficiencies must be maximum but here they said that we are going to select the minimum efficiency out of all in the given efficiencies or in the selected employees so if we are selecting k employees then in that case the efficiency to be considered is going to be the lowest out of all the selected employees so the idea is to select the less efficient employee first so if we have any employee with lower efficiency then the rest of the employees that is k minus 1 employees must be having the higher efficiency than this efficiency so we are going to sort the given arrays based on the higher efficiencies to lower so that we will select our k minus one employees from the highest ground and the kth employee is going to be the going to having the lowest efficiency at the same time we are going to maintain the highest speed group that is how much every employee we select we are trying to maximize the speed so that we will get the maximum performance so this is the overall idea so let's see how we're going to implement this so we are going to sort the given arrays based on the efficiency from highest to lowest so this is going to help us select the higher efficient k minus one employee and one lower efficient employees so we are going to try out our performance with all possible efficiencies and maintaining the higher speed group to pick the employees based on higher efficiencies this is going to help us so as we i trade through the loop and consider each employee at once and every employee come in is going to having the lowest than the before employees if suppose we are exactly at iteration number three then in that case the current employee we are iterating is going to be the lowest out of all the ones we picked before so this is the first step so once we sorted them based on the efficiencies we are going to maintain a minimum heap which is going to hold of top k employees with higher speeds so we are going to maintain this heap of size k to push all the possible speeds into it and which is going to maintain the maximum speeds of employees so anyway the efficiencies are already sorted so they are going to be already maximum so whichever efficiency comes in will be having the maximum efficiencies but here we are going to maintain the heap to mean to have the top k speeds so let's understand we are going to push the first employee into it and the speed is going to be one and the next employee is going to be 5 since the k is equal to 2 the size of our heap is going to be 2 as well and the third employee is 2 so in that case when 2 enters we are going to throw out or lay off an employee with lesser speed so in that case we are going to pop it but before that we are going to maintain a variable result which is going to calculate the result considering the top two or top k employees speeds so first it was one plus five into the efficiency of the current employee was seven which is the least out of nine out of seven so this is going to be the result and that is going to be 6 into 7 42 so now comes our third employee whose speed is 2 so we are going to enter that speed into our heap should have only k engineers so in that case we are going to lay off an engineer with lesser speed so in that case the lesser speed is one so we are going to push that away from our heap so now we have the current employees of feed two and five so it's time to calculate our result is going to be two plus five into 5 because the current employees efficiency is the lowest of all so this is going to be 10 into 5 which is 50 which is actually higher than the previous performance so we are going to maintain our result at this position or at 50 right now so comes the third employee whose speed is going to be 10 so now when 10 enters again the next employee with lesser speed is going to be go out of the t then that case 10 enters the loop or heap and then 2 gets away from the heap so now the current employees are going to be 10 and 5 having the lesser efficiency of 4 so it is summing up to 60 this is so far maximum so we are maintaining the result to 60 now so next comes our next employee number four whose speed is three so if we put three into our heap that is actually the lesser speed compared to the other two employees so in that case we are going to push three away so hope you are understanding this concept by now we are going to maintain a higher speed group along with higher efficiencies anywhere the next employee is going to be having the lesser efficiency so this heap is helping us to maintain employees with higher speed as well as higher efficiency so that we will get higher or maximum result so finally comes our next employee whose speed is eight so if we are trying to push eight into the heap then five gonna go out as that is the lesser speed so now the employee speeds is going to be ten and eight so let's calculate our result so if we are calculating ten plus 8 into the lesser efficiency that is 2 it is overall going to be 36 which is actually the lesser performance compared to 60 so we are going to stick with 60 and not going to consider 36 for a result so we reached the end of iteration we don't have any other employees left to form our team so we finally formed a team of two employees with speed 10 and 8 and our result is going to be 60 which is the maximum performance we could achieve with the number of employees given so hope you're understanding this solution this is gonna take big o of n login time as we are going to sort the given array once and we are going to push and pull the values to the heap and that's overall going to take 2 n log n time and ignoring the constants the time complexity is big o of the n log n hope you're understanding the solution let's go to the code now so first let us have a two dimensional integer array to hold both speeds and efficiencies together so that when we sort one the other also gets sorted accordingly so once we have our array ready we are going to sort this array based on the efficiency that is in decreasing order so here we have in an engineer zeroth index as efficiency and first index is speed so based on the efficiencies we are sorting it here on the decreasing order so now let us declare our priority queue and the size of our priority queue is going to be k and we said the comparator that if we insert the speed it should be based on the increasing order and whenever we remove a speed it should remove the least speed from the heap so let me declare my result and this total speed variables in long because they have said that in problem statement it will be higher and we have to return a 10 power 9 plus 7 modulo so here we are going to push all our speeds into our heap so our speed is at index 1 in our engineer array so before adding the speed we are going to check whether our cue size is of k if a new element enters and already the skew is full then in that case we are going to pull the least speed and then add the new speed so we are checking if our pq dot size is already k then in that case we are going to push away the least element from the queue so we are maintaining a total speed variable in order to hold the total speed right now at the heap so from that we are going to subtract the least speed now our total speed will become which is nothing but speed so far plus the current speed of the engineer so now calculate result for every possible speed so yes our result will be having the maximum speed maximum performance so far that is what we are going to return but here they have asked us to return this in modulo so let me declare a modulo variable and it should be in paint so yes this is it let's run and try yes let's submit yes a solution is accepted and runs in 39 milliseconds thanks for watching the video hope you are understanding this concept if you like the video hit like subscribe and let me know in comments thank you
|
Maximum Performance of a Team
|
number-of-single-divisor-triplets
|
You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108`
|
The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values.
|
Math
|
Medium
|
2301
|
341 |
hey guys this video is a little bit special and because i came across this question today in my uh interview with google uh so let's walk through it and this is a big call number 341 flatten nasty this iterator so uh let's dive in uh to the example so you can see the element in the list it can be a list or it can be a number or it can be well this one is a list inside another list so it's a nested is this that's why it's called nested this so we don't know how many layers of this that it's gonna be um and then what we need to do is to output a flattened least that's why it's called flatten so immediately you can see that we can use a recursion to solve this problem right because we can peel off each layer within the list and then we can um solve um we can flatten the list by doing that and this question was asked by facebook amazon i don't see the name of google in here but actually i was asked by this question today um with google anyway uh let's walk through it so um one way to solve this is to flatten the list in the init function so this is the object design question and we have to write three functions once in it which initialized the object the next one is the next which will return the next integer in the nested list and has next is a return of boolean that if there is something in the next uh sp position and then we return that true otherwise we determine the false so um let's look at the codes together so the init how can we flatten it as i said before we will use a recursion method and i have a recursion function name of flattener and then we will input a given list and for all the elements in a given list so the element can be either a integer or it's a list right so in this case this is a list and this is the integer and this is a list and in this case this is integer this is a list and we find this list and this is integer and this another list right so the element can be either an integer or a list in for all the elements in the given list if the element that we're looking at is a integer and then we up extract the integer from that element and then append to the flattened list which is a becomes a property of this object otherwise we push back into the flattener and then do that recursively and how we do that you just extract the list by using the get list function which is a um a default function that has been written so we don't have to worry about this function so we uh it has a get integer also get list also is integer so this is all the default functions that we don't have to worry about okay and then after that we uh push it back to the flattener and then deal with it again using the recursive method and um to trigger running at the beginning so we push in the uh the input argument nested list to the flattener and also we keep track of the position because this is sort of look like a length list but it's not quite because we know uh there's a position that's pointing to our spot so the initial position is a zero and uh this is how we initialize the position and i was paying a little bit attention to this uh testing method so the code will be tested using the following pseudocode so we have given a result and uh while uh the iterator uh has something in the next position and then we just append it to the result and then we return to the list at the end okay and the next one the next function what we need to do is to uh return the number at the position right so basically we first we save the number by looking at the position of uh the flattened list that we dealt with previously and then we update the position because we have look we have already looked at that the guy that guy and then we push the position to the next spot and then we return the saved uh item to be returned and also the has next function and then we check uh if the position is it less than or equal to uh the length minus one because it's the index that we are talking about and why is so why is there has next it's not uh position plus one is y is self.position why it's not self top self.position why it's not self top self.position why it's not self top position plus one is because already we already push it the position to the next spot right after we call this function right every time we call this function we push this guy to the next part and that's why we just need to check that otherwise we if we plus one again we'll push right two spots forward and this is not what we want and let's run that and run it again so um as you can see it's pretty efficient uh the number changes and for uh time complexity and for the time complexity is b over n plus l so n is the total number of integers within the nested list and l being the total number list and d is the maximum nested depth and maximum number of lists inside each other so there's a nodes in here i'm not sure i understand so the maximum depth of the nesting uh does not impact the time complexity uh yeah i'm not sure understand this because let's say if the if there is only one number in the list and there are 100 lists outside and with that not impacting the speed because i would have to uh in that case i would have to call uh this flattener function 100 times right because you keep calling this guy over 100 times so i'm not actually understand this the next function is a bigger one doesn't make sense because just a lookup and also it has next and speaker one and that makes sense as well it's just one comparison and for uh the space complexity is a big o of n plus d so the d comes from the number of stack the call stack and that makes sense and also obvious is that this is obvious auxiliary space of the integer this is the length of the big of n and that makes sense um and yeah that's so much for my solution i hope this is helpful if it does please like this video and subscribe to the channel that will be a huge support and thank you so much for watching i will see the next video thank you daniel bye
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
1,220 |
hi everyone with Calvin here so let's discuss about weekly contest 157 for question count for one permutation so we are given M and it's the length of the string that we want to form and this thing can be form only by our letter and there are five rules here which saying about if our last character is a and the next character we can type is only E and if the last character is d we can only type either a or I if it's an AI we can type any character other than I and if it's an O we can type an i or you and a feature you and we can follow it on the by na and after the and we form the correct at the length of n for the string so the question is how many unique string we can form and the number can be very large so they asked us to model it with this number so the length of this string itself is twenty thousand so yeah so take a look on the first example if the N is 1 so yeah we just type out the foil itself since the length is only one and when there Lang is 2 so we can see the rules if first we type an A so the next character we can only type an E and when we type in e first the next character can be an A or I write a or I so if the first character is AI we can type all for our character except I so there are four combination of it and if it's an O we can follow it by either an i or you and if it's in new we can only follow it by an a so in total there are ten possible string can be formed with the length of two and when the line is five they are telling us the answer is 68 so how are we going to solve this question so yeah this question is DP question so yeah we know the case that if the line is one and with certain character there's the answer is 1 so for example n of 1 it with and with character a the answer is one so yeah and if we see the solve so there are the rules specific mentioned in the question so if the character is a what is the next character possible so we try to do a recursion here so yeah when the n is equals to one we return one because that is the base case right so because this recursion will have a lot of repetition of the end and see so we catch the NNC for the DP so with the certain length left and we want a certain character we put how many possible combination are there on the first time visit so on the next visit we just check if our gets contained at N and C we return immediately without performing the recursion again so yeah at the end so we solve all the length of n and with those five fouls and then add it up and then that will be the our answer so yeah that's it thank you for watching see you on the next weekly contest
|
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
|
1,727 |
Hello everyone Welcome to my channel here I solve problems Lead code today task number 1727 is the largest under Matrix with permutations we are given a binary Matrix of size M by N and we are also allowed to rearrange the columns of the matrix in any order we need to return the area of the largest under matrices return the area of the largest under matrices where Each element of this we will store in the form of a list the number of units that are in each of the columns continuously, that is, what it will be, that is, for example, we go through the first line in the first two columns we have zeros, so for these columns in this variable that stores the number of units in the column continuous columns display, we store zeros in the third column of one, so we write one after we have processed the first line, we move to the second line in it, we get units in all elements and we check the previous value, if it is sequentially also one, then we increase it, but since the previous ones were zeros, then we simply write units in both cases in the third column. The previous value was one, so we increase it, that is, in fact. In this list we store How many continuous units there were from top to bottom. Moreover, if, for example, in the third line in the second column we met zero, then we replace the previous value with zero because that in this case it does n’t matter anymore And in this way we will n’t matter anymore And in this way we will n’t matter anymore And in this way we will calculate the number of continuous units in each column and at each step, that is, after we have processed the next row, we will rearrange these Columns with units in ascending order, so we will have something like a ladder of the number of units That is, what it will look like is we write here for the first row we have 0 and one in this case we have only one element which we will Write in the result as one That is, we already have one final Matrix with the result one That is, the result for the first line is one; we is, the result for the first line is one; we is, the result for the first line is one; we process the second line; in the second process the second line; in the second process the second line; in the second line, we have the number of continuous units, that is, 1, and for the third column, in the case of the second, the following logic is obtained. That is, if we look at the first element, we see that we have one unit to the top, that is, this is the width of our rectangle, since the columns are sorted. That is, this is one. That is, the next column is at least no less than the previous one, and accordingly we can calculate the area of the rectangle can calculate the area of the rectangle can calculate the area of the rectangle under it, that is, accordingly, in this case, we have a rectangle with a height of one and a width of T accordingly, the result is 3 in the third line, we have one so not ond because we have the Second unit in a row for the second column, we have one for the third T since we will be this is a re-sorting that we can have a re-sorting that we can have a re-sorting that we can have a rectangle with a height of 2 and, accordingly, a width of also 2, its fruit is obtained 4 Nago says that the maximum area can be four Let's try to do this in the code, first, define a variable with the default result will be zero, immediately return it, we also need a variable in which we will store the maximum number of units in the columns, let's say we call Max on the default is equal by default, this is a list consisting of zeros. That is, this is zero multiplied by the length, that is, by the number of columns, this is the length of the matrix variable with an index, but now we need to go row by row and fill the variable ma and update the result value accordingly, let's do this, then we go through each row further inside lines we go through the elements and we need to have an index since we will update the results in the Max variable and we need the value itself so we use the enumerate function from R we update the current value Max Ma IT is equal to zero if the current value is zero otherwise we increase the previous value by one Thus we have updated all the values of the Max on variable for the current values of the Max on variable for the current values of the Max on variable for the current row, now we need to sort these values, while we must preserve the original Max on values, that is, we cannot sort in place, for this we will create a sorted on variable and the sorted unit will call the sorted function, pass the Max variable to us now we need to go through the values of the variable sorted and calculate the value of the result if it is greater than the previous one then update it that is, for and H we also use the variable sorted and update the value of the result this is the maximum value from the previous value of the result and here we need to get the area of our get the area of our get the area of our rectangle the height of the rectangle Rav H at the angle is calculated as follows: angle is calculated as follows: angle is calculated as follows: this is the size of the current line, that is, L R minus the current index. That is, for example, for the second column, the index is 1 and, accordingly, the width will be 3 D. In principle, as it actually is, so here we write mi min I, in theory, this the whole solution Let's try to run the tests some error so let's run it again so another signet Ma tests passed let's try to send the decision has been made it's quite effective that's all for today Thank you all for your attention bye
|
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
|
5 |
foreign called longest palindrome accept string it is a medium let's get started given a string s return the longest palindromic substring in X so just to recap what a palindrome is it reads the same forward and backwards so a common one is a race car reading this backwards we have r-a-c-e r-a-c-e r-a-c-e c-a-r so it's race car forward and c-a-r so it's race car forward and c-a-r so it's race car forward and backwards and it's mirrored across this e right so we see that C's are the same A's are the same r's are the same even if this e wasn't here and our input string was rack car this would still be a palindrome because it's still mirrored just between two characters instead of being a character that's mirrored on so let's take a look at example one and again we want to find the longest palindromic substring we can in our input s so we have the input b a d here we have a palindrome of b a b and a b a both are length three so either one of these would have been a valid output example two we have CBB D here the longest palindrome we can make is just BB and so we output that and it has a length of two so before getting started let's look at a couple of examples so say I have the following two input strings here my first input string that I am testing with is W A B A the longest palindrome exception I can make here is a b a and I'm splitting that on the B that is where I'm mirroring this so what I want to do is check if the character to the left of me and the right of me are equal to each other they are so that means I have a longer palindrome than when I was just on my character now I want to see if I can continue pushing out however I see that I am out of bounds here so the longest palindromic substring I can make here is just the length of theory a b a now if I had a second input string as an example here W A B A the longest palindrome exception I can make is a b a length of four and here I'm splitting between the two characters between these two beats and what I want to do is make essentially the same check as before except between the two characters or my two characters equal and we see that they are well now I want to continue pushing left and right to see how far I can go to see what the biggest palindrome except sharing I can make is so if I move say I had a left pointer here my left pointer down one more to a and my right pointer down one more it's a as well I see that these two are equal and I want to see if I can continue pushing out I see that I am out of bounds here but say I wasn't say I had a c here well now I would make a check whether these two are equal I see they are not and I would know the longest calendar I'm substring at this point would be these four characters so that is what I want to do given any input string S I want to go ahead and make two types of chips either at a character I want to split my palindrome and see what the biggest palindrome I can make is or between two characters so how many checks would that be right say I had n characters in my input string s so that would be n checks for every single character Plus n minus one because now I also want to check between every single character so in here if I had four characters I want to see what the longest condom exception I can make is at every single character plus between so I have four here as well as between w a between a b and between b a so that's an additional three and what this means is that as I iterate through S I'm going to be having two checks and whatever the length I return here I'm going to compare with the longest palindromic substring blend I already have if it is greater than that then I just overwrite it with this new one so just to make this a little bit clearer say I had b a d this first example right here what I'm going to do is I'm going to check at index 0 first so I index 0 what is the greatest palindrome substring that I can make well that would be just the character B and length of one because I can't go further I am out of bounds well now what's the next thing that I want to check now I want to check between A and B so between 0 and 1 what is the longest palindromic substring IQ mean well I see that these aren't even equals so that's just going to be zero I don't even need to make any check here now say I moved down to index one what is the longest palindrome exception I can make here I see that my left and right characters are equal and I want to see if the left of that and the right of that are equal well I am out of bounds they cannot be equal so the longest condom except stream here is eav length of three and I'm just going to iterate through doing this for every single character so now when I'm between one and two I make the same checks again right I see that A and B are not equal there's no point checking let's just move on so I have B and left and right are equal so I have a now I want to continue pushing down I see now I'm on B and D they aren't equal so the longest palindrome reception I can make here is a the a length of three and as I continue pushing down now I'm between two and three we see there's no point in checking we will output zero and finally at character three again this is a and I have e and B next to it so the longest substring here is just a with the length of one and when I check three and four I see that there's no point checking because this is between AMD so I will just output zero now I don't actually need to go to my very last character because I know it's just going to be a character of length one which we've already seen before we would have had at least a minimum character of one in our previous letters this way I don't need to check the character I'm on or the character time on plus one because we know we're going to be going out of bounds anyway so essentially what we need to do is start from zero up until the very last index in our string and what we're going to do is check with the character we're on as well as between the character we're on and the next one so let's go ahead and code all of this up and run through some super quick examples so to code all of this up the first thing I'm going to do is make a helper function to figure out whether or not I am a palindrome and how long of a palindrome I can make so my helper function is going to be is how it's going to take a new string a left and right pointer now what I'm going to do is check while I am still in Bound so while my left pointer is greater than zero and my right is less than the length of my string minus one so I'm not at the very edges of my string I'm not at index 0 or the last one what do I want to see if the characters that I want to move to next are equal to each other so if so and I'm going to add this straight into the wild condition so while we're in bounds and the next characters are equal to each other so string of left minus one equals string of right plus one I am going to move my pointers down so left minus equals one and right plus equals one and I will keep going into this Loop up until any of these are not true so as soon as we end we know our left and right pointers point to the last valid string the last valid substring of our longest palindrome and all I want to do is return those indices so I'm going to return left right and what that length is so right minus left plus one say I stop at index um three and one so from one two three I know I have the longest palindrome so what does that equal for length right three minus one so that's going to be 3 minus 1 which is two plus one because when we subtract it's not inclusive to get that length of three so once we have our helper function now we want to go ahead and iterate through our input string X so for index in range length of s minus one we don't want to go up until the end we want to make two checks first if the middle is a character so what I'm going to do here is store my output L1 R1 and max length one from self dot ease pal and I'm going to be passing in my string s and left and right here is just going to be the index that I am on so I'm passing an index and index I'm passing in my index and then I'm going to see if the left of me is equal to the right of me if they are I'm going to keep moving down now if max length 1 is greater than whatever max length I have stored so far now I'm going to rewrite max length as well as my left and right indices so Left Right equals L1 R1 and of course I want to go ahead and initialize all of these so max length is going to be zero as or my left and right indices so Left Right are also going to be zeros and they simply just tell us what index we want to store because we want to return the actual substring right so we want to know what index we want to sort from what to what that's why we are sorting these markers and now the second check I want to make is if my middle is between two characters so if the middle between two characters so if string of index is equal to string of index plus one now I want to see what my longest palindromic substring is so L2 R2 Max Len 2 is equal to solve e is pal with s index and index plus one and we want to make the same checks here that we did right here so I'm just going to copy and paste that if maximum two is greater than Maxim then I'm updating excellent and updating the pointers that I have as well in the end all I want to do is return my string at those saved indices left and right so left and right plus one just because this is not inclusive so let's go ahead and run this code one time error expected an indent block after if statement I mean these need to be indented so let me go ahead and do that so now if we go ahead and run this code it is accepted and we can go ahead and submit and it is accepted as well so before leaving let's just super quickly run through a short example here just to see what our code does line by line so if we have our input string s being this we are setting Max when left and right all to zero now for index in our range up until the last character so right now we are going to be moving through 0 to 0 1 2 3 0 to 2. so we're going to start with index being zero and L1 R1 max length 1 are going to be equivalent to the output of our helper function so L1 R1 and Max when one are equal to the helper with this and we're going to be pulling in our string S 0 and 0. so when we call this width 0 we want to make a check is left greater than zero it is not so we are immediately out of our while loop and we return left to right and the length right here so right minus left plus one so we've turned zero plus one and one so we return 0 and 1. so here our left index is zero right is zero and our length is one now we make a check is our max length greater than our current max length it is so we are going to go ahead and update this so this is one and we're going to update these pointers as well so this is zero and this is zero now the second check we want to make is if the index were on and the index above us so zero and one are equivalent so a c equal to B they are not so we are out of this if conditioned back into this for Loop and now our index is one now here we want to make the same checks here and I'm going to be calling this again passing in CBD index one and index one here my string is CBD left is one right is one now y left greater than zero and right less than length of string minus one so length of string is four minus one is three so one is less than three and the next characters are equal so is zero and two the values at those indices are they equal so 0 is C two is B they're not equal so we just return left to right minus left plus one so here we are returning one and we are returning one we are in this if check and we see that max length is not greater than the one that we already have so no need to make any updates here and we are in this second call right here is the index we are on and the one Afters are those values equal we see that they are one and two are equal so now we make the following call and here we are passing in CBD we're passing in one and we're passing in one plus one which is two so the string is CBD left is one right is two now in this helper while left greater than zero which it is write less than length of string minus one which it is as well and the next two characters are equal so is zero the right should be 2 here so it is the value at character 0 and 3 the same and we see that it is not the case so we never actually increase our pointers and so we just return left right minus left plus one so here we return one write these two and the length of that so right minus left plus one which is two and we see that this max length is greater than the one we currently have so we can go ahead and make our update so update this if you want and this to be two we are back in this for Loop and it is our last time in this for Loop we are on index two and we make this call we know what this will return because that index to the one to the left and right of us are not equal so we'll never actually go in this while loop and we would end up returning left which is to write which means two and the max length which would be one since we never actually moved our pointers and we know we wouldn't have to actually make any updates here since max length is one and we would go into this if condition so is the value at 2 equivalent to the value at 3. it is not the case and so we exit out of this if and in the end all we have to do is return string of range going from one two three so we are going to be returning from one to three it's not inclusive so we are returning the two fees which is exactly what we expect and super quickly for space and time for space we're not really making use of any extra space except for the variables we're storing so that is constant of one and for time say our entire string was just all eight right everywhere we go is just a palindrome so potentially we would be making a check for palindrome at every single point going as far as we can so at any point we are going to be iterating through our entire string because we can just keep incrementing our pointers so that would essentially be for every n and we know in this case you're actually going to be having 2N but since this is still an order of n we can reduce the sound to be linear and what I mean by that right we know the total number of checks we're going to be making is n plus n minus one and for each of these we are going to be iterating through every single character so this times n if every single character is the same we can just keep moving our pointers every single time now this is equivalent to 2N minus 1 and any time we have just numbers we sort of don't really care about them we can reduce the sound to be something of order n so we're going to be making order and checks and for every check we are going to go through every single character so this is going to be N squared for time so constant space N squared for time and that is how we find the longest palindromic substring if you have any questions at all let me know down below otherwise I will see you next time
|
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
|
1,832 |
hello everyone welcome to harsha lectures in this lecture i am going to explain you about check if the sentence is pangram or not okay so here pancream means user will give one sentence so in that sentence we need to check all alphabetical name all alphabetical letters are there or not so here a pancream is a sentence where every letter of the english alphabet appears at least once given a string sentence contains only lowercase english letters written true if sentence is a pangram or false otherwise so here in this example one they given sentence equal to the quick brown fur jumps over the lazy dog so this is a pangram how can we call this is a pan graph because this string contains all 26 alpha alphabetical letters so that's why we need to check the given input is pangram or not if it is pangram we need to return true statement if it is false we need to return false so here the logic for this is first we need to create here string s equal to sentence okay and then here what i'm mentioning is for character c equal to i am giving a and c is less than or equal to i'm mentioning here j and pre-increment c in this for loop pre-increment c in this for loop pre-increment c in this for loop i am mentioning if s dot not contains string dot value of c okay then written false else written true so here what i did in this first created one as string in that i just allocated this sentence into this and then here i took one loop for character c equal to a to jet i kept one range in this by doing iterative we can find that if s dot if the sentence having some input right if that is not if all elements are not in this value of c means we need to compare if the elements which are if the string which are present in this yes if it is not condensed uh when we are comparing with value of c then it will give a false statement as it will return true statement so by implementing this logic we can able to find whether the given input is pangram or not it this will help to check whether all alphabetical uh letters are there in that input or not if it is not there then it will return false so this is the logic behind it now i will run this code will check what will happen yeah it is accepted now i will submit this code will check so here success so this is the logic behind it if you have any queries you can mention your doubts in commentary session and please do like and subscribe for more videos don't forget to click on bell icon thank you
|
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 |
860 |
what's up guys Nick white here and I am very tired I'm doing so many problems but it's gonna be worth it maybe I don't know maybe won't be worth it I don't know why I committed to doing all these problems but this one's easy so that's a little piece of you know whatever it's goodness so this lemonade change also check the description for information bringing me problems on patreon the same description every freaking time discord whatever I've got lemonade change 336 likes that doesn't matter okay let's get real here lemonade change you're running a lemonade stand the lemonade cost five bucks customers are in the a line and they buy from you one at a time each customer will buy one lemonade only and they'll pay with either $5 $10 or $20 they'll pay with either $5 $10 or $20 they'll pay with either $5 $10 or $20 bill you must provide the correct change to each customer so that the net transaction the customer pays is five bucks you start with zero bucks at first or return true if and only if you provide every customer with correct change okay so we looked at this array and we keep track of the money and then we have to provide the correct change and if we can't we do false if we can we do true and we start with nothing okay so we're gonna keep track of fives in $10 bills because those are the only $10 bills because those are the only $10 bills because those are the only ones that matter we're not dealing with ones or anything so yeah into five this is equal to zero into tens is equal to zero and then we move through the bit it's super easy honestly this problem probably the easiest what one of the easiest on the site if the bill is equal to a five-dollar bill 5s we added a $5 to a five-dollar bill 5s we added a $5 to a five-dollar bill 5s we added a $5 bill to what we have okay else if they're paying with a $10 bill else if they're paying with a $10 bill else if they're paying with a $10 bill we add a $10 bill and we can remove a we add a $10 bill and we can remove a we add a $10 bill and we can remove a five though because that means that we have to give them change right because the lemonades five books so they pay with time we gotta get them five else if this means they're paying with a $10 this means they're paying with a $10 this means they're paying with a $10 bill so else if they're paying with the $10 bill and ten if 10 is greater than $10 bill and ten if 10 is greater than $10 bill and ten if 10 is greater than zero I mean a 20 they're paying with the 20 if we have a if our tend out if we have more than 110 then we can give them a 10 and we can give them a 5 else then we have to give them 3 fives right because they we don't have a 10 to give them we have no tens so we have to give them 5 so yeah that's it and then we just have to check okay if fives is less than 0 return false at each iteration because that means that we they give us a $10 bill and we don't have a 5 to give a $10 bill and we don't have a 5 to give a $10 bill and we don't have a 5 to give them we're screwed we can't give them a change automatically so that would be you know it'll just go negative at some point if we can't give them the change if they give us a 20 and we don't have a 5 then what are we gonna do we're screwed we have to give them a 5 in the 10 there's no other way so we're screwed if it goes negative and in the case they give us a 20 and we don't have a 10 then we have to give them 3 we get a negative 3 we're screwed so you basically just screwed if it goes negative if you make it through the whole thing you're good easy that's it boom done 7 months ago weird tens sorry tens come on alright thank you guys for watching that was a super easy one all right thanks like the video maybe alright or you don't even have to all right bye
|
Lemonade Change
|
design-circular-queue
|
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net transaction is that the customer pays `$5`.
Note that you do not have any change in hand at first.
Given an integer array `bills` where `bills[i]` is the bill the `ith` customer pays, return `true` _if you can provide every customer with the correct change, or_ `false` _otherwise_.
**Example 1:**
**Input:** bills = \[5,5,5,10,20\]
**Output:** true
**Explanation:**
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
**Example 2:**
**Input:** bills = \[5,5,10,10,20\]
**Output:** false
**Explanation:**
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give the change of $15 back because we only have two $10 bills.
Since not every customer received the correct change, the answer is false.
**Constraints:**
* `1 <= bills.length <= 105`
* `bills[i]` is either `5`, `10`, or `20`.
| null |
Array,Linked List,Design,Queue
|
Medium
|
859,1767
|
128 |
hey guys Greg here and let's solve longest consecutive sequence so we're given an unsorted array of integers nums and we need to return the length of the longest consecutive elements sequence this is such a confusingly written problem and it's much better with the example so if you look right here we have 100 4 200 1 3 and 2 what you'd think they mean by longest consecutive sequence is like if you had 1 then two then three in the array in order but the order doesn't matter here in this array there actually exists the consecutive elements of 1 2 3 and four remember order does not matter and therefore that is the longest consecutive sequence and we just want its length and so we would return four and in this example they go crazy to the extreme here you can even have duplicates as well and so we have 0 1 2 3 4 5 6 7 8 they all exist in there and so the longest consecutive sequence is 0 to 8 which is going to be nine numbers now the Brute Force solution would definitely just to be sort this thing and from there it's really not that bad in N log n time you could sort this array and you would make it okay we have 1 2 3 and four and at the end our useless 100 and 200 and then we'd say whoo all of the sequence stuff is actually in order here and we're not going to write the code but you could imagine that kind of checking off by one every single time through the array and order is really not too bad we could definitely return our answer of four there however they even said in the problem that they want you to do better than that so we're going to try and come up with the O of n solution now whenever you're not sure with some tricky array problem like this you might have a feeling that some sort of a set or hash map might be useful and it turns out that a set of the numbers or a hash set is going to be very useful and so if you basically just store all of this stuff in a set we put all of the numbers into the set so that you can immediately do an O of one lookup to see if we have one of these numbers so why would that be useful well that would mean if we saw this number here well how would we have a sequence from this well you could have basically two different directions you could have well 99 if 99 was in the set then you'd have 99 then 100 and so that's a sequence bigger than one or you could have 100 and 101 if this was in the set well then you could have again a sequence of two and you could kind of keep checking that you could say well if we have 101 do we have 102 do we have 103 or if you could go the other direction we could do something like okay we have 99 in the set well do we have 98 in the set well do we have 97 and you could keep doing that check however theoretically how long could this thing run well if all of those numbers actually were in the set like let's just change this to for now 1 2 3 and four well if we have these numbers if we checked for one well we could say do we have zero no but do we have two yes do we have three yes do we have four yes so we could say that we have from this element right here we found a sequence of length four however that would happen again over here we would have at two here we'd say okay do we have one actually yes we do and so we have one do we have zero no we don't do we have three yes do we have four yes and so that's running again and so he basically again outputs we have four same thing with three do we have two yes do we have 1 yes do we have zero no do we have four yes do we have five no and so again he outputs hey we have a four sequence and so four would do exactly the same thing this is basically an O of n s algorithm because for each every single item in the array you are going to basically check potentially all of the other stuff in the array as well however there's a clever way to optimize this what if you only ran that check if the previous number is not in the set okay why would you do that well if we run this if zero is not in the set and Zer is not in the set so we would run it for one well that basically means that one starts a sequence if you check if 1 minus one so it's 1 minus one in the set s that means that this thing is the start of a sequence and so on its own it's just a sequence of size one does it get bigger than that well we'll go in the forward Direction only and we'll say yes we actually have two and we have three and we have four we don't have five so from this element we did actually see a sequence of length four but now let's do the same thing over here we say hey for two we'll try to do that check but we want to run first we only want to do this if 2 - 1 is not in the set and it this if 2 - 1 is not in the set and it this if 2 - 1 is not in the set and it turns out that 1 is in the set okay what does that mean well that means that one or maybe something else was starting the sequence so we've already kind of ran this Loop thing of checking all the other numbers or we're going to later and so we're not worried about that check right there that stops this from being an oven squared algorithm and it makes it just o of n we only do it for if you're starting a sequence he's going to go up but here we'll go through the numbers but he's not going to check anything neither are these guys so to do it for our original problem here we would put all the stuff in the set and we'd say hey is 99 in the set no it's not okay so let's try running this is 101 in the set no it's not and so this just outputed a sequence length of one we'll check for four does four start a sequence is three in the set yes it actually is okay so four is not starting a sequence we don't want to work with it we want to worry about that later 200 it does start a sequence but it's just going to be a sequence of length one for one this is where we actually run that check and so 0 or 1 - one is not in the check and so 0 or 1 - one is not in the check and so 0 or 1 - one is not in the set so it does start a sequence so we'd get two and we get three and we get four we wouldn't get five so he outputs a sequence of four and for these guys three and two they do not start a sequence so we're not going to run that this leads to an O of n algorithm it's really clever and pretty awesome okay so we're just going to start this off by putting all of the numbers into a hash set and we can do that with s is the set of nums we'll get our current longest sequence that we've seen or we haven't seen anything so it's going to be zero and we'll say hey for each num in the nums if num minus one is not in the set it starts a sequence so we want to start going up so the next number that we're looking for is well the number Plus plus one okay if we had next num well then the sequence would be length two and we could keep bumping this up so next num is num plus one and the current length of our sequence is just one now while the next num is in the set s well the length that we've seen is one more so our sequence is one more and we need to bump up that next number to keep this check going okay so after we eventually break out of this Loop finally at some point our next number was not in the set so our sequence concludes so we'll set longest to be the max of what it was already and the current length that we're looking at we'll only set longest to be the current length if that length is actually bigger than what it's seen already and at the end of this we can simply return our longest and if we run that then that's going to work just fine okay so the time complexity of this algorithm this is going to be a big O of end solution because you're going to go through the numbers and again you only do this sort of nested Loop thing if the number minus one is not in the set and so that's not going to be n^ S that's so that's not going to be n^ S that's so that's not going to be n^ S that's going to be o of N and the space complexity that comes from using our set and so we are basically storing the end things as well I hope this was helpful guys drop a like if it was and have a great day
|
Longest Consecutive Sequence
|
longest-consecutive-sequence
|
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
**Example 2:**
**Input:** nums = \[0,3,7,2,5,8,4,6,0,1\]
**Output:** 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Union Find
|
Medium
|
298,2278
|
1,991 |
all right so let's talk about the fun and middle index in Array so uh what it means is pretty straightforward so just find the leftmost middle index and the middle index is an index where num zero plus nums one plus all the way to in Middle East minus one equal to the middle index plus one and plus all the way until nums or length minus one and find out the leftmost index uh so this is the idea so what you need to do is write uh you want to find out the total sum right so total sum representative one sound of all sum old all of the inner array right and you also know like if you notice you are not including the middle index in a comparison right so you want to uh just clue right so look at this the example one two three negative one is four right and then the output will be index three zero one two three which is number eight but they'll get a explanation the sound of a number before index 3 is 2 plus 3 plus negative one and then the sum of numbers after industry is four right which they are in the same so you will notice left sum plus right sum will be equal to the total sum minus the middle index but in the meanwhile left sound equal to the right sum which is also equal to two times left sum equal to sum minus middle uh middle Index right all right so uh I give you the idea so let's stop holding so what we need to do is using the sum so how do we uh write down the equation code so just using a regular string the numbers of rate of sum right and then what I need to also have is the left sum I was starting from zero and then keep adding uh for every single each iteration in the for Loop so go in I to zero I listen number length and then I plus foreign definitely find out the sum minus the current index or the middle value is equal to two times left sum so just look at the formula uh like 30 seconds ago right and then what you need to return is the current is because you are not including the millions right you're not including the middle value the middle index no I'm sorry and then I need to keep adding my left sum right number five and then if everything uh has done already and you still cannot find you want to return negative one so this is pretty much a solution so let me run it submit okay so um again the time in space this is all of N and represent end of number three and then this represents all of n right all the time right all the simple time space is constant right so uh let me have a breakpoint over here something like this right and then pause the video at any second if you are confused all right so my sum is 16 right and I will keep the subscribers in Traverse into everything look at this I'll update my sum and I put the two right and then exit all right so uh I mean I need to pause return I over here so you'll get three uh let's do it again sum is 16. first iteration second direction right I put one second division third and fourth time you return I when I go to three so this is a solution so it's still confusing just leave a comment below and then subscribe if you want it all right peace out bye
|
Find the Middle Index in Array
|
league-statistics
|
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).
A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.
If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.
Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.
**Example 1:**
**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
**Example 2:**
**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
**Example 3:**
**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.
**Constraints:**
* `1 <= nums.length <= 100`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/)
| null |
Database
|
Medium
| null |
11 |
hello so today while doing this problem called container with Moore's water and problem says we get an array of integers such that each represents a point coordinates that are by I the index and a I so the I if the index in the array is the x-coordinate and a I the value in is the x-coordinate and a I the value in is the x-coordinate and a I the value in the array is the y-coordinate so you can the array is the y-coordinate so you can the array is the y-coordinate so you can see here for the red the first red one the eye coordinate is since it's the second element in the array it's 1 and then that's the x coordinate and then the y coordinate which is AI is the value 8 and so that's the y coordinate and we have n vertical lines which corresponds basically to these end points from isay row to III so I 0 is the one at the bottom which is the start of the of this bar here and we're gonna find two lines of these such that together with the x axis the one-bite parallel with the x axis one-bite parallel with the x axis one-bite parallel with the x axis they form the container that contains most water so you can see in this example here the one that contains most water is the one color the blue here and so that's this example in the area of that one is 49 so how can we solve this problem let's take a look okay so let's see how can we solve this problem so the first thing let's just look at the example that the problem gave us here which was which was this one with one eight six two five four eight three seven right and so the indices here are zero one two three four five six seven eight right so let's just draw the draw this out and so what we had is we the values here go up until eight so let's just take one two three four five six seven eight okay so after that let's just throw these up so we have the first one goes up into one the second one goes all the way up until eight one after that goes over to six and then we have two and then five eight and then three and then so how can we solve this problem so all we want is the container with most water so the first thing we can do in this kind of problem when we don't know where to what to start with we can just start first and try a brute force solution so what would a brute force solution in this case mean well we can just examine all the intervals right and then count what are we interested in here first we want the container which was more sweater let's just analyze that first a little bit and then we can know how can we approach our brute force right so we want container with most water so essentially if we had a container between let's say this one in this one it would be something like this right then what is this section here that's just the area of what's in between right so essentially what we are looking for is an area right and so what are what defines an area basically it's the width multiplied by the hate right so in our case for two hate and what is the width and what is the head so the width is just the basically if we have index so here with the indexes we have our zero one two three four five six seven eight the same as the one about there so the width here of this area here is just this right so it's just 8 minus 6 right and so the width is just the last called the last let's call the mass index J Alice for this one a so the width is just j- i right and then so the width is just j- i right and then so the width is just j- i right and then the hate what is the head so the head is limited by the smaller one because if you the bigger one you can't put water here because there is no nothing to hold it on this side right and so the head is just the men of the two sides right and since we said I and J this one is array of J and this one is array of I right so it's just the min of array I and Ray J or in the problem they called hates the array the contacts so let's just match that so we don't get confused later so it's hate it's fear and same thing men of hate and hate okay so now we know what the area is and so now we can think about a brute force solution to this so the brute force solution that we can do is just go through all intervals and compute to the area between each fair using the formula that was just I'm said and get take the max right so that's very simple solution right this will probably get a tumbling to exceed it but let's just do it and then from there we can take a look at what we can improve so what would a brute force solution look like so we said we are just going to go through the intervals and then we go through the intervals and from there we are going to calculate the area and pick the max right so we need the max area something about the max area so let's call that max equal to zero and then we're going to go through every pair of intervals and so that means going through length let's call this haze so and with every other interval so I plus one length of tape and then we're just going to pick the max right so max area is going to become the max of max area and then what is the area that we just saw that to compute the area we need to minoc the head multiplied by the width which is J mind's eye and so that would mean multiplied by the width which is J minus I and the head which is that just the min of the value of the toe right so the men of the hates of J or I and hater right and so don't give us the max and then at the end you can just return that right so very brute force solution okay so that looks good I submit so you can see we've got a time limit exceeded and it pass it on good number of cases but naturally since it's brute force um we got time limit exceeded now let's see how we can solve this problem improve it a little bit so that we can get to us okay so how can we improve this solution so one insight is that since we know what the area depends on right we know that it depends on the width and the height right so how can we maximize our chances to get the max area right so let's just so it since it depends on the width bus just pick the max width possible so the max width path but it's just to go through the entire thing - just take the through the entire thing - just take the through the entire thing - just take the entire section right and so you can just take this entire section as a start so what that means just put our I here and our chain here this will maximize our width right and then from there take that take the max area of that and now how can we know how to link these two so we have two options we can either move this one on this one or both at the same time so basically the loss look at the area in this case words y as wide as possible right so the area in that case is something like this goes from here all the way to here why is that because of this smallest one we can't go here so it's useless that the hate of this one is really big right so to maximize our chances to get a bigger one we need another taller one that is taller than this one so that it can increase the hate a little bit because increasing the we can increase the width we have to go in advance and that will only decrease the width because we have to go in one step further and then if we go one step further the width will be minus one would be the old width minus one and if we move this one J it will be still out with minus one if we move both it would be odd with minus two so it's in our interest to minimize the to maximize the width and so to do that we need to move one of the pointers and now both at the same time so now we rolled out the moving both pointers at the same time and so now we know we have to move one of these pointers which one you have to choose so if we move this one here if we move this one so we can if you change first if you lose for Mojang which means the one with the Christ with the largest weight that means that so the width became smaller right but the head even if it's bigger than the one that we just have who are still below me to buy the smaller one right and if it's smaller than it will be smaller than this one so the head would be also smaller and so we'd have a smaller area so head would only be smaller will only be same or smaller so no matter what we do is if we move the larger one we won't have a smaller area right and so that's not optimal and so naturally there's only I left right so if we move the now if we move the eye which is the smaller hate right we still know that we the width will be smaller the width will become smaller because we subtracted one but hate it will either be bigger right it will either be bigger and in that case it's either bigger than the hate of cherry so in that case we are winning because the hit will become the head of Jay which means we will have a bigger area or it's even smaller but in that case again we will lose but there is a chance that we'll find a better areas the new one is bigger which is the case with this one so potentially here we might find a bigger head right and so this one we are sure we won't find a better max area but this one we might and so might find a better area and so it makes sense to me this one right and you can notice this argument that I just outlined here it doesn't matter if it's for the left one or the right one the same argument applies and so that means that in all cases we will take the smaller the one with the smaller rate and move that index and if it's if this one is the smaller mate remove that index so we would need to make it to subtract one from that index right so how can we cut that up so the code for that would be just something like so the pseudocode for that will be something similar to so we will need two pointers I'm going to call them left and right that would be easier those are usually the names that we give to two pointers that are on one on the far left and the other stars on the far right so we're going to have these two pointers and one of them is the length of 8-1 of them is the length of 8-1 of them is the length of 8-1 because it's on the far right and then we're just going to go until they meet because once they meet we are done we examined all the other areas that we need to examine and so you can notice here that okay so now we are going to go wild but have they haven't crossed each other if we are going to just apply this now if the weight of the left side is less or equal to them on the right side or less then they hit on the right side then at that point we are just going to advance because that's the smaller one which is what we said here always advancement the smaller one else which means the head of L is the one that is smaller in that case we need to advance you need to move the our index which means just doing minus one so that would be minus one and then here we will update max area so let's just call this update max area we should be the same thing we did with the brute force solution or the just compute than you earlier using this new hate and with and see if it's better and so that's pretty much the pseudocode solution for this and you can see while doing one book and advancing each time one step and so this one is of M such that n is the micro phase so it's a lot better than the brute force solution which considered every pair and was open squared so hopefully this one won't pass okay so let's see the code for this solution okay so let's see the lost code the better solution so this solution we said we need to have two pointers so it's the same LP pseudocode outline and we need the max area that we will keep computing like we did with the brute force solution and then while the two pointers haven't crossed each other we are going to determine the height which is just the minimum of the two so that would mean and the same way as the brute force and multiply that by the width which is our minds and then from there see if this gives us a better max area and so that would mean Oh actually sorry I need to do that at the end right so this is the head and that's my area this is basically the part where we update the myself and it would be the width multiplied by the eighth can just take this put it here return max area at the end and here we can just do what I just did in the pseudocode which is the other one is smaller is the one that we need to advance and so if this is smaller than its at are won't admit that's the smaller one which is in this case L and the left side to advance it we do plus one otherwise it's the right side very smaller and in that case we need to advance the right pointer by subtracting 1 and that's pretty much all that is to it and the solution is open and so let's just run it Scottie's fades okay it looks good the submit there is a slight issue with one yep so basically the problem is I didn't initialize with the I didn't realize the first max area because I updates right away and did it initialize the first one so let's just ensure light max area to the first left and right which is the far left and the far right so the case were the far left and the far right form the max area that wasn't computed so we need to do that before assignment here so this is just initialize it to this okay so looks good okay so this solution passes and yeah so that's the better solution than the brute force using the same calculation but just cleverly traversing so that we don't end up doing urban squared and using two pointers technique instead yeah so that's a professor russian thanks for watching
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
313 |
hey hello there today I'm looking at the questions 313 super ugly number we have to write a program to find the ANSF ugly super ugly number the definition for this super ugly number is that it is a positive number integer number whose all prime factors are in a given set of prime numbers we have and also that one is considered as the super ugly number no matter the set of prime numbers are what the prime numbers are so we are looking at the ends super ugly number that's in the increasing order we can see that by the example basically we are asking the twelve smallest super ugly number that we can generate with this set of prime numbers one is always going to be the first one in the increasing order and then the all the rest all the numbers there are basically some kind of multiply of the prime numbers we have in a set so if you look at the this actual sequence generated it's one two directly from the set four which is two x two seven directly from the set eight which is 2 to the third 13 from the set 14 as 2 multiplied by 7 16 is 2 to the fourth 19 from the set 26 2 x 13 28 2 multiplied by 2 by 7 + 32 which is the multiplied by 2 by 7 + 32 which is the multiplied by 2 by 7 + 32 which is the 12 smallest and smallest super ugly number in the sequence that's being sorted in the increasing order so obviously if we can actually generate the sequence or write a generator that can consistently give us the next smallest number in a lie we just ask that number generator for n times and that number is the one we want so then the question is how we actually going to generate those numbers in sequence note that all the numbers here are pretty much is some kind of a multiple of the numbers we have so if we grab a number like say for the multiple bit multiplier between the product between this four and those prime numbers are going to be somewhere later in the sequence the two x - 4 x to the eighth that's the two x - 4 x to the eighth that's the two x - 4 x to the eighth that's going to be here ladder in the same ladder position in the sequence 4 x 728 s here and 4 x 13 is even further dong in the inner line so what we can do is basically starting from 1 and have that number the smallest number we currently have in the sequence multiply that by the each individual prime numbers in the set and put those product into a set and we after that we are done with number one we move that into the sequence and we try to grab the next smallest a super ugly number from the bag of a super ugly number that we generated it's 2 so we multiply 2 by the individual prime numbers in the set and I put on all those product back into the bag of generator - the broccoli numbers bag of generator - the broccoli numbers bag of generator - the broccoli numbers and then grab the next smallest so what we can do is to use a priority queue to hold all those generate a super-clean number each iteration we're super-clean number each iteration we're super-clean number each iteration we're going to grab the next smallest to throw that into the sequence and have the number and multiplied by how many Prime's we have and put that back into the bag this is a bag we want to do some kind of deduplication the priority queue does not do it naturally so we might enable - we need to create a set to do enable - we need to create a set to do enable - we need to create a set to do the deduplication so the this will definitely work but it's not efficient because just think about that we actually CRO have the bag size to be growing quite dramatically somewhere down the line so the run time that's not going to be ideal we will look into the code and do some analysis and it's not gonna be strict because I'm still struggling time trying to figure out the exact mass so we're gonna look at some dues lose upper bond instead of the actual tight lower bond so tight bond so let's go this so pretty straightforward so we're gonna use a priority queue to use that to hold the set of generator to super ugly number and each generation we grab the smallest to put that into the sequence and then use that number to generate new additional super ugly number and so diving back into the bag of generator numbers so pretty much just to create a really naive super ugly number generator so we're gonna have this prime cube which initially is this number one by self and we use a set to do some kind of thick application in the beginning it's just number one so we have to generate n number so while here we're gonna grab the next smallest number from the priority queue so I will be using the heap queue from Python itself why he cute I'm not misspelling right hip hop PQ because by default it's actually the mean priority oh so if it's main priority queue that satisfy our requirements because we're gonna consecutively grabbing the next as small as the super ugly number that we generated so it's satisfy what we need for time in Prime's we're going to multiply the number with the prime and that's potentially the new number that we generated if it's already something we have think that means we have already pushed at this number on top right here already we don't want to do this duplication otherwise we will push this number onto the priority queue and also add the number into the set of numbers we generator so far so what we would do is to push this number onto the priority queue and also add this number to the product up to the set so after this for loop we are done with this number we officially move this into the sequence and decrement the number we have already generated here I'm not actually collecting this because all we need is the rare loss the number have been popped out from the priority queue so after this while loop we should just return this number yeah so there's a little bit open meditation if n is equal to 1 the number is what we want so let's actually do that so for that we don't this need this right yeah so we don't need this return so let's see if it works looks good let's see yeah it's a about mediocre you know somewhere middle in the runtime among all the submissions but it's actually quite slow if we analyze the code we definitely have a order of n here it's a while loop and this decremented by 1 every iteration a we got a pop here which is a log of the size of the priority queue size let's call this s the size of the priority queue is growing so that's a very it's a slightly complicated problem the prime the for loop here is potentially out of K but it's not necessarily K multiplied by the push here because the push is also law with respect to the size of the priority queue so but it's but since that we're doing some kinds of deduplication it's not necessarily K but it so let's just say that in the worst case is order of K so the whole thing is these three things multiplied by together so it's a it's going to be loose so it's n K multiplied by log of size of the priority queue and the size of the priority queue is actually some kind of function of values N and K but it should be less than linear so in the very worst cases be in x case so that's the rarely loose upper bound for the runtime complexity it's n K multiplied by log of n K so it's actually quite bad and if we look at what's kind of a redundancy here is that this thing grows unnecessarily let's say that we only want 12 we can potentially generate far more than that so you know it's the two multiplied together that could potentially be something like 48 so that's definitely far more than what we need here so let's say so obviously the thing that we want to do is still to follow this kind of track to generate the next smallest number using priority queue we need to do some optimization so here we actually create a lot of large number that's too far away down the line so the code is easy and we're lazy but work on the under the hole is quite busy so we're actually going to do the opposite we're gonna try to have the work to be a little bit the code to be a little bit more complex but have the actual work down there to be lazy what I mean is that I'm not going to generate all those combinations I'm only going to multiply this by make this number slightly larger in the sequence and put that out to the priority queue so let's look at this is the desire the sequence of numbers and the primes are here so every number has to be some multiplied by either two seven searching on 19 just think about how we actually gonna do this initially we only have one so let's just put a 1 here and we have 4 different branches to sort of so let's see that we have a 2 here some multiply some number multiplied by 2 and 7 and 13 and 19 so initially this sequence is only the number one we will multiply this by two that's actually the number we want to put back onto the priority queue then what's the next possible next the number we want to put on that propriety cure the number of the sequence of super ugly number that we generate it's gonna be two multiplied by two so we actually have this kind of a next relationship to is going to multiply by the next smallest in a sequence which is gonna be four and now four is the smallest that we put that back to the end of the priority queue the number you know the priority queue basically here is the generated a super ugly number and then we find a seven here we're looking for the next smallest it's just going to be seven plus seven move seven up and four seven we will the next smallest super ugly number we can generate by something multiplied by seven is this 2 multiplied by seven so then it will be the next super argument number that generated by multiplied some number multiplied by seven is going to be the 2 multiplied by seven it's going to be 14 and the next number is going to be so seven the next number is going to be 2 multiplied by four I'm just gonna promise I and I will do this a little bit more iteration to it will become super clear what's what I was what we are doing here this is eight that's the next the smallest super ugly number in a sequence and also the third number from this sequence kiri is one x - 2 x - 4 x - so after kiri is one x - 2 x - 4 x - so after kiri is one x - 2 x - 4 x - so after this it will be 13 it put certain moves starting into the sequence and then the next number that's going to be some number x 13 next - super ugly number in number x 13 next - super ugly number in number x 13 next - super ugly number in this line is going to be the next one to x searching which gonna be 26 so each individual line here is basically assorted linked lists and it's a sorted list and it's actually growing dynamically while this sequence of super ugly numbers actually is growing it's growing us when the same time this list is growing so all we need to do every time is actually just do a priority queue it's checking the forehead node inside the among these four lists so all we need to do is to keep a priority queue of size K so that's much better than this year because then we see that n multiplied by K is actually flying the thing that's really bad is this a log n K that's a multiple of that if this becomes much smaller than the whole thing is smaller because n a stuff length has to be there K the in multi by K term is definitely gonna be there the Lotter multiplier should be as small as possible and this latter time is tied up to the size of the priority looking at here we can basically this is like merge for K different sorted list and the next element we grab next the head node we grab from this for sorted list that you know advancing dynamically as the sequence the actual sequence girls is to use a priority queue to keep track of the for head node here so let's think about what this head node actually should contain the information that this head node should contain you will be let's see it's a two-dimensional saying let's see it's a two-dimensional saying let's see it's a two-dimensional saying right the actual number here the it should be a three-dimensional thing the should be a three-dimensional thing the should be a three-dimensional thing the actual number here the Colin it belongs to and this is the first column this is the second column this is a certain column and the multiplier the prime multiplied it has so it will be a number it's like eight here the index the Colin which is going to be three and the prime multiplier so that is two so every single number here every single node in inside this case ordered a list this is a Triplets of three things and we're just going to put this thing for full of this thing key off this thing on the priority queue each iteration we're going to pour the smallest node in terms of the first element out and use the second item the second value the colon increment by one to grab the next evaluating the line and multiplied by the prime it comes with two to put that back in there so the so as an example we currently have is 814 2006 and nineteen so the next smallest it's going to be this what we need to do is to increment this column number three to four so we'll graph seven and the multiply two by 7 to get the next element here next note here which is gonna be why it's so that's not shrinking it's gonna be to multiply by the force from the sequence it's gonna be 14 yeah so we were basically updating this node from this to this yeah so this is the update and we pop this out modify the second column multiply this to look up at the number four from the using this column number from the actual sequence multiply the ladder to get to the update the number and push this back to the priority queue so that would be a better solution the size of the pride queue is always kind of before so this kind of query would be log of K so much better than this never it's not growing with respect to any more it's fixed there is K so it's much better so let's code this up sorry it's not mean to happen so we could have the sequence of number that's generated so far it's gonna be a growing kind of array or a linked list and we have the this triplets as the elements on the priority queue so let's just call this the a curly number we generated which is initially going to be this only number one and we have a prior review which going to be the these three of the K different initial nodes and on the for each of those sorted list which is going to be the prime number itself and Colin 0 which is 1 and the prime itself so it's a p IP p 0 p well i is 1 in the beginning and then we're just going to do the similar thing decrement this am each time we'll put a new ugly number onto the priority queue sorry they generated a sequence of super ugly numbers and we assisted we already have a 1 here we can run this only n minus 1 times and actually here is the same thing right we could do this n minus 1 so that we don't need to do this test but anyway that code is already there with I'm not going to do some kind of modification to that we're going to grab the number from the smallest a number from the priority queue which is as ah sorry I think I'm forgetting something yes the thing that here is we can't have duplicates do we do anything about that not necessary because if no matter which one we grab it's just gonna advance that one more so the size of the priority will never really change yeah so we don't need to worry about that but that messed up the updates for this because for fourteen if it's already there in the list we don't want to decrement this end right yeah so we're gonna grouping the node of the same value extracting into the Sam do under the same iteration in the while loop so for that reason we're gonna first get the smallest number in the sequence and then just grab all of those notes with the smallest number in there so yeah it's gonna be a nested loop we get the top element and the first item in the triplets is going to be the ugly number so we try to pull the nodes from the priority queue until that the smallest is not equal to this number we coopera the triplets this time we actually pop out the triplets and then we want to increment at the second item - indicating we are now grabbing the - indicating we are now grabbing the - indicating we are now grabbing the update the next element from the sorted sequence of ugly numbers and multiply that by the prime factor and after use that to update the first the actual number that gives us the next number in the sorted list for the prime factor and after this we push this topple back into the priority queue that's equivalent to say we have we transferred from this to the next node in the sorted list and put that back into the prior to queue so at any given time we're only gonna have you know K different items on the priority queue so that's that and after this fun while loop will be decrement this end and in the end we're just going to return the very last ugly number we generated yeah so let's give this a try nope I got a I got an arrow what's the problem when I pull this number I should put it back to the ugly number otherwise the index access I will we're getting be out of fun so why I'm forgetting this okay the tricky part is that the prior to queue in Python it's a the container the under underlined container and the data structure is actually it's actually separated I always forgot about this so I should put this typo onto the container all right no still no geez less than is not supported between us and listened integer oh the wrong order so bad this time works okay yeah this is a much faster let's look after the run time I'm going to do some really loose analysis this is the order of N and we can potentially pop k that's in the worst case the number is 2 multiplied by 7 by 13 by 19 that every linked list here so the list or that they know that we are looking at would be exactly having that number so if that's the next number in the sequence that's the only time this while loop will run out of k times and each keep operation is going to be order of exactly log and low K because the size of the priority queue is always going to be kidding so this second solution the runtime is going to be loosely bonded by upper bounded by get rid off the end here yeah so that's pretty much what I want to talk about this question that's it for today
|
Super Ugly Number
|
super-ugly-number
|
A **super ugly number** is a positive integer whose prime factors are in the array `primes`.
Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_.
The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer.
**Example 1:**
**Input:** n = 12, primes = \[2,7,13,19\]
**Output:** 32
**Explanation:** \[1,2,4,7,8,13,14,16,19,26,28,32\] is the sequence of the first 12 super ugly numbers given primes = \[2,7,13,19\].
**Example 2:**
**Input:** n = 1, primes = \[2,3,5\]
**Output:** 1
**Explanation:** 1 has no prime factors, therefore all of its prime factors are in the array primes = \[2,3,5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= primes.length <= 100`
* `2 <= primes[i] <= 1000`
* `primes[i]` is **guaranteed** to be a prime number.
* All the values of `primes` are **unique** and sorted in **ascending order**.
| null |
Array,Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
|
Medium
|
264
|
1,720 |
we given an input array and a first value we want to decode it based on the following formula seen here with xor and first value you'll notice that we want the red values to be output and you should know that the inverse of xor is xor itself so we can change these formulas into these formulas giving our result here you'll notice that the result is really just the running exor of our input with the first value as its first value so we have our first value here next value will come from the input first value exord with the first resulting value and so on and so forth is getting passed down each time so we can Define our result and we can get each value in our input and then append our first variable we are going to use our first variable here to store the running exor so we would just do the running exor like so and then return our result plus the last value because we are going to have an extra value at the end in this case result 4 it's not going to be encapsulated in this for Loop because this is only of length n we need length n plus one we can do this in one line like so using the accumulate function but we are not summing we are doing an exor operation so we need to give it the xor function like so
|
Decode XORed Array
|
crawler-log-folder
|
There is a **hidden** integer array `arr` that consists of `n` non-negative integers.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`.
You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`.
Return _the original array_ `arr`. It can be proved that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[1,2,3\], first = 1
**Output:** \[1,0,2,1\]
**Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\]
**Example 2:**
**Input:** encoded = \[6,2,7,3\], first = 4
**Output:** \[4,2,0,7,4\]
**Constraints:**
* `2 <= n <= 104`
* `encoded.length == n - 1`
* `0 <= encoded[i] <= 105`
* `0 <= first <= 105`
|
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
|
Array,String,Stack
|
Easy
|
682,874
|
1,094 |
hey what's up guys this is sean here so uh today uh let's take a look at this uh lead called problem 1094 carpooling uh medium level problem i think it's not that hard but it's i think it's worth sharing with you guys a few uh ver a few solutions different solutions for this problem you know okay so you're driving on like a vehicle that start has a capacity empty seats has capacity empty seats initially available for passengers and the vehicles only drive east which means it's going from left to right okay and you're given like a list of trips so the trips has three elements the first one is the number of passengers okay that this trip will carry and the second one is start location the third one is the end location okay and then there's another like a capacity here okay so it asks you to check if you can finish the whole trips with the current capacity which means at any given time the car cannot take more than this capacity number of passengers if that happens we simply return false that's what ha exactly what happened in the example one here because you know at location one here right we pick we picked up two we pick up two passengers but at that location three here we picked anot another three here okay and the total is five which is like uh exceeds our capacity that's why we return false here and the second example is like it's five because i mean because the two plus three is five it's not exceeding the capacity okay same thing here right so that's the third example is because basically you know since we start at five here right and then at the location five here we have already uh drop off these two passengers okay so from here i think probably you guys already know that i mean this is kind of like the uh a sorting problem right because you know so the trip length is this okay so we have some constraints here so the first intuition will be like we should sort by the start time right by the start time and then the end time that way basically every time when we have a start time we can simply uh um remove right we can see we can certainly remove everything uh we can remove everything that's previously like uh ending time whose ending time is smaller than the current start time okay to do that we can simply use a priority queue okay so for the priority queue we can i mean we every time when we uh we see like a new trip here right we uh we first we try to uh we try to pop everything that's uh pop all the trips that finished view up before this new start time okay and then in the end we add this like new a new start time and meanwhile every for loop we just check if the total is like exceeding the capacity and if that's the case we simply just uh return the false otherwise in the end we return true okay so i mean that's the first approach right i mean that approach is not i think it's the unlock end right because at the beginning we need to sort we sort it and then every time when we have like uh and then later on we have a for loop which is the end and then uh every time we do a heap push and hip pop and for that is a lot it's a log n so in total it's unlocked n um you know what actually let me try to implement that real quick so actually today i'm gonna including this one i'm gonna try to show you guys three solutions here okay so we're gonna have like a so first i'm going to sort the current one okay the key is the lambda right since we're going to sort by the second by second and the third elements here i'm gonna do a like x one and then x two basically i'm creating a customized sorting key which is the a tuple with the second and the third element here okay and then and i have a priority queue here okay so basically this is what i mean basically for like number right and then i have like a total here okay so for number and start and end in the trips okay so at the beginning i will try to basically pop everything in the priority queue okay basically in the priority queue here i'm gonna store two values here so the first one is the it's the ending time and the second one is the number okay because i need to use the ending time to help me to pop everything okay in here so basically while the prior queue is not empty and the priority queue dot 0 is equal or smaller than the current start okay if that's the case i simply adjust do a pop okay we do a hip pop okay it'll hip pop a priority queue and then actually hip q dot hip pop okay and then i'm gonna need to remove this total numbers okay because after popping we have a end time and numbers here right and then we have this one that second one is the total numbers okay now uh the total number is equal now we add this one here now we will do a like keep hit push okay hit q dot he push the priority queue and here uh we're gonna have like the new end right the new end and the number okay so and also we need to add the current total with the uh within the card number here if the total is greater than the capacity okay then we simply return fast okay later on we return true here okay i think this should work oh sorry ah zero okay all right submit cool so this first one is looks it's it works right because i mean the time complexity so here's a uh the first here's the unlock and okay and here this is the end right and the heap pop and push here we're gonna do uh like end of the uh actually the worst case scenario for this one here it's gonna be a i mean yeah this is fine because here i mean the total number we're going to do the pu the pop will be n so basically here is here it's also log n here and here it's also log n so in total this part is also unlocked okay yeah we're not doing this like pop end times every time because the total times will be uh we'll be in so when it's gonna allocate it so when it comes to amortized uh complexity so this one is like oh one here this one is o1 so which means here is uh just a login okay cool so this one is pretty easy to understand right basically every time when we have a like we sort and then every time we have a new start we pop everything that ends before the start okay and meanwhile we're also maintaining like a total number total passengers okay cool so that's the first one and the second one so the second solution is that you know every time when you guys see this like uh you have like a few bunch of like a point here like timestamp or in this case it's like the look the location a bunch of low locations here and you either have like a start it's basically like a start point and end point okay and then basically at each of the location here right you have like at the start locations you basically you increase the passengers by two and when you're at this like uh the end location basically you decrease the passengers by two okay so for this kind of problems you know you can basically you can separate the start and end you separate them into two events okay and then in the end basically you just spread them into like into this like 1d up lines here with the start and end time and at the at start time you increase this number and at the end time you decrease and then in the end you simply scan those time those like the location from left to right and then every time when you see as long as by the time you see like the number that's greater than the capacities and then you return false okay so we're gonna have locations okay locations like this uh locations so the locations okay let me see here okay so this is what i mean here so basically for like again for the numbers start and end in the trips okay uh locations okay locations dot append so the start is the number okay and then locations dot append and is the negative number okay so how about the duplicate locations and i mean the duplicate locations doesn't really matter right because we are in the end it will be we'll be sorting by the times that by the locations anyway so we can simply like basically append those each event to this location and later on uh we just need to do a sort basically we just do a sorting sorts by the location right so and then like four uh location and then the numbers okay in the locations we need to have a lo a total okay again so total plus number okay and if the total is greater than the capacity and then we return fast okay else we return true okay so this should also work cool i mean so as you guys can see this thing is i think it's a little bit faster than the other ones because uh we don't need to do like the heat the heap thing so we just do a for loop here this is n right so this is an and here the sorting is unlocked and here it's just another end here okay i mean this is a better solution because you know so for this one i mean i think for you guys you just need to i mean have this kind of idea in mind that every time when you have like this start and end things you can and especially you know when it asks you to uh to calculate the total numbers the total like values like uh that happens after a few of events right in that case you just need to uh basically separate those events into a two events so that you can later on you can scan it from left to right because this is important you need to sort it okay so that's that and the third one can we further improve this one to uh to even faster solutions it depends okay so this is where we should we need to uh like improve so why is that i mean because you know the reason we're doing the sortings here is because you know the locations we don't know the locations right we don't know the range of the locations that's why we need to sort it because the locations could be from anywhere to anywhere but here there's like interesting like constraints here so the trip so the trips length is one uh sorry here number four here so the trips the location start and end they're within the range of 1000 so which means that i mean the total length of the location is from zero to one thousand okay then with this range right i think most some of you have already realized that we can use like this bucket thing bucket sorting thing right sorry basically we created like a bucket right for each of the locations in uh beforehand and then we do the same thing here okay basically we put each of the location into its bucket okay and then and since it's already sorted it's already like in the sorting sequence right from zero to one thousand we can just simply remove this part yeah cool so real quick i mean i think it's pretty similar with the above one basically we have locations right um at the beginning everything is one thousand i think one thousand one okay and then i just basically copy everything here i just copy it here but instead i'm removing this okay and here okay i can simply okay sorry so the look actually the key will be this the events here okay so that's that all right and the value of the other thing is this right n equals to minus n here okay so after that right after that we just need to scan from the left to the right because if there's nothing there it the value will be zero so it will not affect our total okay yeah so submit oops uh oh sorry uh increase okay because you know be at this one for this one here since we're appending so basically if the location is the same it doesn't really matter we're gonna have like two events of that and later on we'll be accumulating everything together but right now since we're using a bucket right so each of the bucket holds everything for this location so that's why we have to accumulate that okay and this should just work cool yeah i mean i think that's it for this problem i mean it's not a it's a pretty standard problem it's not that hard but i think it's worth sharing with you guys like the different like ideas or different intuitions just to come up with the solutions right i mean the first one i mean it's okay right the second one is you need a little bit of like an ex previous prior experience like how can you separate these events right into two separate events so that you can sort it and then you can just uh scan it and then the last one is even bit a little bit more trick uh a little bit uh trickier because it does it you need to realize that uh this constraints here which means that you can trade like uh some extra you can trade the uh the better performance with some extra like uh space here okay and the last one as you guys can see it's a lot it's a on solution right because here's just o n and here's also o n but with a little bit of extra a bit more space here and cool i think that's all i want to talk about for this problem thank you so much for watching the videos guys stay tuned bye
|
Car Pooling
|
matrix-cells-in-distance-order
|
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_.
**Example 1:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4
**Output:** false
**Example 2:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5
**Output:** true
**Constraints:**
* `1 <= trips.length <= 1000`
* `trips[i].length == 3`
* `1 <= numPassengersi <= 100`
* `0 <= fromi < toi <= 1000`
* `1 <= capacity <= 105`
| null |
Array,Math,Geometry,Sorting,Matrix
|
Easy
|
2304
|
455 |
Hello friends, in this problem we have been given some children and we have been given some cookies. We have to give at most one cookie to each child. Each child has a specific requirement that he wants a cookie of this particular size or that particular If he will not take a cookie of the same size or bigger or smaller, then we have been given what size cookie the children need and we have been given the sizes of the cookies that we have. This information is in two separate arrays in our M. What is the distribution of these cookies to children? Distributor in such a way that we can distribute these cookies to the maximum number of children. We can give at most one cookie to a child and what is our M. What is the maximum number of children to give cookies to. Like if we take this example. What size of cookies do we need? One, two and three. What size of cookies do we need? One and one, we have cookies of this size. If we see, we can only give the cookie to this child. We can give this cookie to this child. After that we will have the requirement of T and T, but what size of cookie will we be left with? One size cookie will be left. We cannot give this to anyone, so how many children can we give cookies to one child? This will be our answer. Similarly, if we see this example, one and two, what is our requirement, one and two, we have two children, one child has the requirement of one size of cookie, the other has the requirement of two size of cookie and what size of cookies do we have, one, two and three. If we have cookies of these sizes, what can we do? Give this one cookie to the children. Give the two cookie to the children. We have one cookie left, but you have no children left to whom we can give the cookies, then to how many children the cookie distributor? Now if we see that if we have to give a cookie to any child, then which cookie would we prefer to give, i.e. the one which is of equal size or i.e. the one which is of equal size or i.e. the one which is of equal size or which is of the immediately next greater size, like if Suppose we had 1 2 3 This requirement was there and we also had cookies of the same size 1 2 3 So what would we do in that case We would give one to one Two would give two Three would be given to three If we would have given three to one We would have If we assign a cookie of size three to one, then what requirement are we left with one and three? And what size cookie are we left with one and two? So we would have assigned this two to two, but now we will assign this three size one to any one. Why couldn't we sign the cookie? Because its demand is high and we have small size cookie. If we have to sign the cookie to most of the children then what will we have to do. Whatever is their demand, either we fulfill that demand exactly or exceed it. Just Near Greater Whatever is the next greater cookie, let us try to fulfill it, only then we will get the cookie distributor to more and more children because what will happen to us with this, we will be left with big size cookies and if we do that to any of our children. If the demand is high then we can fulfill it. What can we do for this? If we have to give a cookie to a child which is equal or more than the same, whatever nearest greater one we can give, what will we need for that? Which is the next greater element than that, if we need it, then how can we find out that thing easily? If we are given these two arrays in sorted order, then what will happen in that case, we will know what size should be the smallest cookie. What do we need and with which cookie can we satisfy it? Like suppose our demand for cookies is 2, 4 and 6. We want cookies of this size and what cookies do we have. T 3 and F. If we have a cookie of this size, then what do we do? We have sorted them. The demand has come in increasing order. Similarly, the sizes of the cookies we have come in increasing order. What do we see? Is this the smallest cookie that we can give to any child? How do we know that? It will be okay, we will see from the starting children, if we can give this then we will give it, if we cannot give this only then the rest of the chin's pressure is more than this, we will not be able to give this cookie to anyone, that is, we cannot give this cookie to anyone, so we will give this cookie. We will move ahead in the cookie, we will see if we can give this to any chin. Again we will come to the smallest chiran, we will see two yes, we can give it to this one. What will be our answer one that we will give this cookie to this one. Now we have this If these two are left then our demand will come here and where will our cookie come on the index here that out of the starting two cookies, we gave one of the cookies as a distributor to one of the children, now we have this demand left and we have this cookie left. Now we will see whether we can satisfy anyone with three, what will we see for that, what is the smallest demand among our remaining demands, this is four. If we are not able to satisfy this one, then we cannot satisfy the next one. That is, we will not be able to give this cookie to anyone and then look at the next cookie again, we will see that this cookie is bigger than our four, that is, this cookie we can give to this one, how many total cookies have we distributed to this number, now we have Cookies are over, that is, we do not have any distributors left, so what is the maximum number of distributors we can get? What will be the distributor approach to cookies? First, we will shorten both the arrays so that we have the demand in increasing order and the size of the cookie. Also come in increasing order, then one by one we will consider the cookie. Can we give this cookie to any child? What will we do for that? We will go to the smallest demand. If we can satisfy it then we will consider it. We will satisfy it only if we are not able to satisfy it means we cannot satisfy any other demand from it, we will discard this cookie and will look at the cookie which is bigger than this, can we satisfy the demand of any children with it? We can do this, if we satisfy it then we will move ahead in the children also, we will move ahead in our cookies too. How long will we repeat this process until our array gets exhausted or our children array gets exhausted ? What does it mean when it is exhausted, ? What does it mean when it is exhausted, ? What does it mean when it is exhausted, we have no cookies left to give and if children are exhausted, what does it mean that we have no children left to whom we can give this cookie. We will distribute the cookie to all the children whenever. If any of our array gets exhausted, then simply what will be our approach? First we will sort both the arrays, after that we had to take two pointers, one pointer for which, one pointer for children array and one pointer for our cookie, we will set a cookie index cookie. It would take two pointers to traverse and a child index to traverse the chain's demand and we had to run the loop until none of our arrays were reached. The size of our cokey index s is smaller than the size of our cokey index. Child index: Our is smaller than the size of our cokey index. Child index: Our is smaller than the size of our cokey index. Child index: Our data size is smaller than the size of the array. We have to run the loop and what to check inside it. If we are able to satisfy the demand of our current children with this cookie, it means that the children are given that cookie. Give it, we will move ahead in Chin Ix and because we were able to satisfy the demand of a child, we will add one plus in the answer, we gave a distributor to a cookie, if it is not there, simply what we have to do is to discard this cookie and We have to check for the next cookie whether we are able to satisfy any demand with the next cookie or not and we will repeat this process until none of our errors are satisfied and in the last as many cookies as we distribute We will return that answer variable. We are sorting. From here, n is equal to one side of the array. Let m be the side of the other. From here, equal is equal to A. This will be our sorting key. Apart from that, what should we do, we are putting loops on both the arrays i.e. m p a, this is how much we will need to i.e. m p a, this is how much we will need to i.e. m p a, this is how much we will need to traverse the array, but which one will dominate our T n l n p a, then what will be our overall T due to sorting n Log a plug off and how much space will it take for us? We have not taken any extra space for the putt but we will need extra space for sorting. How much will it take for one sorting, logo fun plus, this much space will be required for the second sort. thank you guys
|
Assign Cookies
|
assign-cookies
|
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number.
**Example 1:**
**Input:** g = \[1,2,3\], s = \[1,1\]
**Output:** 1
**Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
**Example 2:**
**Input:** g = \[1,2\], s = \[1,2,3\]
**Output:** 2
**Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
**Constraints:**
* `1 <= g.length <= 3 * 104`
* `0 <= s.length <= 3 * 104`
* `1 <= g[i], s[j] <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Easy
| null |
77 |
okay this is throwing the number 77 combinations in this very simple problem the two integers n and k are given with a possible combination of k numbers out 0 1 from 1 to n you may written the answer in any order so let's see there example number one and it's poor so the all the possible uh sample we can pick is one two three four what kind of items and we just select the only two things from the poll samples so at another time so in this case two uh two and four are clicked and three four and two three one two one three one four so one two three four by missing six kind of cases are as we already know the combinations and k is looks like this and their equation of this is a minus are bacterial sodium and is called nr is two then four bacteria and four has two factorial so car three two factorial six is left so because there are six kind of commands can be generated with the given number of numbers as we already implemented uh other combination problem just like that we need to declare the recursive function here and their legacy functions the first time we start index and sequence and rate to store the output if we turkeys subsequently is the same as katie and we need to use output here and replacing iteration like this and called with a passive information with the increases index and text that store their nouns at the index of i and like this okay i think it looks like okay we can solve this simple communist problem like this thank you for watching this video and please subscribe to this channel and please click good permit greater better context that might be helpful for you thank you
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
148 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem 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 i post a new video so without any further ado let's get started so uh so problem is sort list right in this problem we are given head of a linked list and we have to return the list after sorting it in ascending order that is we are given a linkage and we just need to sort it fine so uh there are many ways we can do this so either we can use insertion sort right so this test case let's uh take this test case 4 2 1 3 so we are given this linked list 4 2 1 3 we have to sort it so after sorting it will be something like this 1 2 3 and 4 so this will be the output fine output will be this now see simply we need to do sorting right uh and sorting we can use insertion sort so you can check the video in the description insertion sort or but that will be c insertion sort will be o of n square approach in the worst case right uh so what we can do is we can use merge sort to sort this link list merge sort so merge sort is n login time complexity so we can use merge sort now the question is that how we can use merge sort in a linked list so for this problem right for this uh problem there are two prerequisites which you need to know first of all you need to know how to uh do merge sort in simple array like how to do mozart you basically you should know how merge sort works and secondly you should know how to merge two sorted link list so i have create i have created a video on this merge 2 sorted link list so link will be in the description i will highly recommend first go through this video and then come to this video so see these two prerequisites you need to know that is merge sort in array how it works add merge to sorted link list fine so see let's use merge sort to sort this linked list so see very it's very simple merge sort is very simple what in merge what we do in merge sort what we do basically is we divide the linked list so this linked list is given we will be doing merge sorting on this right so in what sort what we do we divide the linked list so we individually sort the left part so this will be the you can say left or you can say the first half this is the first half and this is the second half so we will divide the linked list into two halves we will sort this so recursively this will be sorted we will assume that it's sorted so this linked list is sorted to four and we will assume that the second also is sorted so like as of now it's already sorted so after sorting this will be one three fine now what we did was we have sorted the first half sorted first half then we sort first of all see first of all we found the middle of the linked list that is we divided the linked list into two halves right then we sorted the first half then we sorted the second half sorted second half that is this one fine after that what we will do we have to this is one linked list this is other linked list right what we will do we will merge these two link list together these are sorted link list this is also sorted linked list now we will apply the logic of merge to sorted linked list so merge to sorted linked list means uh we will be merging these two links together in sorted order so this when these two link lists are merged they will become one two three and four and this is our output so basically what we are doing here is what we are doing we will be finding first of all we will be finding the middle of the link list if we will recursive this is the recursive policy we are sorting now first of all firstly we have to sort this much linked list right we have to sort this entire linked list initially then what we do we divided this problem into sub problems what sub problems this is a sub problem smaller problem this is also a smaller problem fine this also we need to sort so sort earlier we were sorting the entire linked list now we are sorting this link list first so this is a recursive call right this is a recursive world we are just doing the same thing which we were doing for the whole linked list that is we are sorting it but right now the input is smaller than the whole english like this input is smaller so this is a recursive call and this will also be a recursive call so this recursive call will sort the right half like the second half and after that once we got the this link list which is sorted and this linked list which is sorted we will merge them we will merge these two linked lists together so merge fourth step will be merge to sorted link list merge 2 forted link list right so basically this was an overview of how merge sort uh in linked list work so these are four steps which we will do now let's diagram once right let's dive in so let's do one thing here let's have this linked list so we have linked list which is given to us as 4 two one and three fine the first step is we will find the middle of the linked list so for middle finding middle of the linked list we will be using a slow and fast pointer approach slow and fast pointer so if you do not know how this approach works then i will uh provide the link in the description uh for the middle of the linked list you can check that video first so see so in order to find the middle of the linked list what we will be doing we will be starting slow we will initialize it with the head right that is head is what 4 and fast we will initialize with head again which is what four so what we usually do in the slow and fast pointer approach slow moves by one position and fast moves by two positions right so slow and fast both are initially at four as of now then slow will come to two one step and fast will go two steps so one two so fast will come here then slow will go one step ahead and fast will go two steps so one and two so fast is now at null so see when fast reaches null so wherever your slow is that is your sec like the uh head of the second linked list like the divided link list so this is one linked list and this is the second link list fine so um the head of the first link list will be head only because this four was head and this one which is the head of the second linked list that is your slow point so slow will have the head of the you can say head of the second half or second linked list right so this way we will be dividing these two linked lists so 4 2 and also what we will do now we will be keeping a previous to this flow that is a temp variable we will be keeping it here that is it will be one step before slow because over here we have to write temps next to be null that is four two's next should be null now because then because right now two's next is one so we have to break that connection so for that we need to know what is this uh previous node before this slow so that's why you'll be keeping a temp variable also fine so this is one linked list so and the other one is one and three so r3 is not is already null so that's why we do not have to explicitly do null for this but here we will do temps next is equal to none right so this was one step right this is first step we are finding the middle of the linked list and we divide it into two linked lists so let's see the code for that also side by side we'll see the code and we will try it so see this function is given sort list and we are just like simply checking if head is null so this is the base case if it is null or there is single node in the linked list return head fine then what we are doing we are taking three variables see slow and fast initialize to head and temp is initially none then we are see this is a basic how to find the middle of a linked list this logic if you are not aware of this i will highly recommend you can watch uh the video to find middle of linked list so after this loop we will have uh in the slow we will have the head of the second link list and the attempts next we will do null times next we will do null so that four to four two's next is now null it's not pointing to one it's now so see now what was the next step was to sort first half right sort first half means this first link list which is there we need to sort it so this is a sub problem right earlier we have to sort this entire linked list so we have created this function sort list which will give us the head of the sorted link list right so here this function sort list will return one which is the head of the sorted link list now sub problem is that we have to sort this for this linked list so when we will recursively call this function as shortlist it will give us the head of the sorted link so if you sort this will be 2 this will be uh 2 4 something like this right after sorting so sort list function will return the head of the linked list so 2 will be returned so here l 1 will have two we will not see how this short list function is internally like again recursive called how it's working uh we will just simply assume that we are like this is working fine you can also dry run and see how it's basically working inside but i but let's not do that right now because then it will be very lengthy so basically we are assuming that it will give us the sorted link list so this will be the linked list and it will return the head so l one will have two and l two is the slow so slow we are passing the head of the second linkage so head of the second link list which is one three here slow was pointing to the head of this linked list right slow so we are passing this sort list so what we are doing we are sorting the second half and it will return the head so one will be the head of the sorted link list right so here we will have one fine now see what we need to do we have so we have this uh link list 2 4 and we have this necklace one three null l1 is here l2 is at one fine now we just need to do one thing we just need to merge this is also sorted linked list right we just need to merge these two sorted link list merging these means making a sorted linkage of both of these linked lists combined so when we will merge them so we are calling this function merge uh we are calling this function merge list and we are passing this l1 and l2 which is the head of these two linked list l1 and l2 so this merge list will give us the final head of the merge link list so if you merge them one two three four will be the merged answer right and from this modulus function we will get the head so one will be returned so that we are returning if you are not clear how this mergeless function is working i will highly recommend i will give the link in the description you can check that video how we can merge to link list to sorted link list so see guys in this way uh we are doing the more sort so one will be returned which is the head of the sorted linked list right so see it's exactly similar as we do merge sorting array same steps just here we have linked list and there we have arrays same steps we find the middle we divide the we sort the left half we sort the right half and then we merge them together right this is a classic merge sort so see time and space complexity let's see that so see time complexity is of n log n fine and space complexity because if you remember when we use arrays then space complex is often but here we are using linked list and we are not using any extra space right we are just changing there only so it will be of one fine so i hope you found the video helpful and you understood uh all the uh prerequisites video link will be in the description please go through that first otherwise you will not be able to understand and found the video helpful please like it subscribe to my channel and i'll see in the next video
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
763 |
Hello Super Singh Good Morning Good Afternoon Good Evening Time Video Problem Subscribe Side Subscribe Channel Subscribe Sure Partition post-partition Subscribe Sure Partition post-partition Subscribe Sure Partition post-partition Peeth Friend Character Pimpri Director Lies In Only One Subscribe To And Posting Richest Man In Its Need To Avoid Panicing For Positive Which party wears the latter years not fall on 21 minutes ago tracks present in this petition know the partition channel subscribe to that reach weapons can they have job screen crack aa that tum ki deposit wearer this partition buddhi please do subscribe like subscribe and subscribe And this entire operation is 30 last and subscribe to that 0.5 inch width partition track from Chinese lunar chit satellite subscribe the 0.5 inch width partition track from Chinese lunar chit satellite subscribe the channel definitely subscribe to that NTPC Difficult Corruption Laxative Services Seervi subscribe and subscribe the Channel and subscribe the Winners of Vice President 15th Extend England Ko Partition Was the Winner of the Year Subscribe [ England Ko Partition Was the Winner of the Year Subscribe Partition of All of U The Interpretation Agri Paneer 13131 Middle-aged man has to make the voice very low Maintenance and Value Pistol Pairs Lakh Induction Overcurrent Partition Building on the topic A Partition Last Point 151 We Will Do Subscribe Partition In Which Presidencies All The Others Like This Uttar Pradesh Current Plus One And Again Will Keep Updating Avoid Being This Point That This I Have maintained for two years which tell me the first last index of these taxes on fast in last row of all the characters on t-series presents online PDF t-series presents online PDF t-series presents online PDF format for its sexual subscribe and subscribe the Video then subscribe to the Page that and equal to a Maximum after and after last drop subscribe And subscribe The Amazing spider-man more subscribe The Amazing spider-man more subscribe The Amazing spider-man more subscribe apne partition loot this video like share and subscribe our channel video that this phone is coming
|
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,903 |
all right so let's talk about the largest odd numbering stream so you're giving a example so basically you just want to check every single digit from the last one to the first one and then to see if every single digit is what is even or out so if this is even then just skip if the last digit so you're starting from here right so if this digit is all then you just return the entire string and then basically you know like um this is super shift forward solution so I'm going to write a case when you return nothing and also you have to covers on the end to the beginning and then check every single digit so I'm going to say if num uh chart a i and I have to subtract by uh chart character Zero then this was another individual right and then you multiply two if this is equal to one zero we want to you want to skip right and then else at least it's going to be what the even number and even number you can just return number substring from 0 to I plus one so the reason why you use I plus one is because you don't want to include the last digit actually checking the current digit so we need to include list digit and this is doable for sure so let me to automate the solution so you want to get rid of else get rid of continue and then okay and then change the condition to see if this is all digit if this is true then you just want uh just want to return from 0 to I Plus 1. so still doable and yes so let's talk about the solution so uh this is what the time all of them so check it every single index so this is all of them for the client and for the space if you want to say this is a space because something under allocated memory and if this is the space I would say all of them because you want to contain every single digit so uh all of unfortunate all of them for the space and this is solution so I will see you next time if you have any question leave a comment below subscribe if you want it peace out
|
Largest Odd Number in String
|
design-most-recently-used-queue
|
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros.
|
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
|
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
|
Medium
|
146
|
77 |
Hello gas welcome to me youtube channel so today we are going to solve cheat code problem 77 combinations so what is the question that we have been given two numbers n and k and we have to find all the possible combinations of the size of k. I have to find out and number from where do I have to do the number thing, once again, the number should be in the middle of the given n, like, take the value of and, n is 3, n = 3, take the value of and, if you are ok, then it is n = 3, take the value of and, if you are ok, then it is n = 3, take the value of and, if you are ok, then it is 123. If there is a combination of two sizes, what will be the combination of 2 sizes? One, two, one, three, what is there in it? If there is 3, then what is there in it, one number has been A and may not be two. Two possibilities have been one number. One number may or may not be A. So in this, what option do I have whether to include one or not to include one? Okay, so first let's see what is one, what is the option in one, what is the option do I have to include one or not, green product one. If you become three then only one will remain. There is an option for you too and if 3 is not included then you were left here, now 3 has been included and 3 has become. Subset is being formed. How much is 123121312312, mother, we will print it. So we will check and after taking out the subset, we will count how many elements are there in it, like the value of tu will be what does it mean that two elements would like to come one or tu one three What is the combination of 3? Select one out of two to three, do not select even one out of three, that is why if two come, it will be made of two sizes, then two which will be of two sizes, if you have the value of k, then we will print two sizes in the same way. Okay, so how will it be coded? So how will be its code? Brother, what will we do first? For one, we took one in this and if we did not take it in this, then it was left empty. Then we must have come here for 3, tomorrow we will do only three. If you want, it's okay, then whatever size it is, it's okay, we will print it, that is, we will put the result in the result, create a vector of vectors of these types and return the second bag tracking. Okay, so the second bag is tracking, and the answer we give in this means very systematically. Will make it like 'one, two, one, very systematically. Will make it like 'one, two, one, very systematically. Will make it like 'one, two, one, three' means complete systematic Ali will be formed, three' means complete systematic Ali will be formed, three' means complete systematic Ali will be formed, what will be the benefit of this, you will know like write 'one', 'if you are trading in the first loop only, write 'one', 'if you are trading in the first loop only, write 'one', 'if you are trading in the first loop only, then my first hair is first, what is the option at this level, I have three options, first one' I have three options, first one' I have three options, first one' Then you again trade in three loops, then one came, now one has been taken, now what kind of child do I have, I will have the option of taking 2 out of 3. Okay, so now I have taken you, now I will take you in three first. We will take the forest, then we will take you, we will return from here, what will happen that now we will go back here, remove this one, then we will go to you, now we will remove you too, we will remove you, what will happen to that now this one will be the answer. Gya na one, tu one tu three, one will become one, three, this one will become 13, nothing will happen, then it will return, then we will remove the three, then it will go back, three is also done, nothing will return, now we will also give example to three and remove it from here. Given 3, now we will go back to 2, you have also removed it, now see when 3 comes, we will put 3, we will add 3 and after putting 3, we will move ahead tomorrow, we will return it will become four, so that's it, everything is set. So the same method to method number is okay, this is what happened here, it will go to the start first, if you do it tomorrow, then it will be found in the death, first one came one, as soon as it happens tomorrow, see here, one push will be done. One A is given in the answer, okay, I am of two sizes, we are not doing it right now, we are just telling you that we will leave it for now and see that one came here first, then came here, then did it yesterday, now what will happen here now one? You will be fine, if I do plus one tomorrow, then this loop will not work because there is only one more, if this loop will not work, then it will be taken out, it will go back when it will come back down from here because it cannot go further from here. If you did not move further then nothing happened, so now it will come down, what will it do here? If it came back on three, it will pop three from here. Here also three becomes the answer, so it will pop three, then go back. Popped, then went back again. When it comes back here, what will you do? One and Three 13 Here it was 123 happened. When it returns here, the control will come down from here, three again. 13 Here we are making pay lines exactly, meaning the whole thing is in sorted order. It is also becoming one, two, one, three and in this it will not be formed in just sorted order, then what are we doing here by filtering, if the size is of then we are taking it in the answer. Now see what is in Java. You must be doing code for that because there is a little difference in the code of Java, like this is the code of Java, okay now see what it is doing here, everything else is from here, why are you doing new array list answer, okay? So see here, if we enter the direct answer, then what will happen is that if we enter it like this in the last section, then the right answer will come, okay, what happened, it became black, now see, we are printing it and showing you what is printed. See what is happening on doing this, now look here 131423232424 so it goes with the reference otherwise what will be the result then this sir has changed himself and thought that we will have to make separate insects and insert them because see the whole is complete. 34 are going on and the same is going on in the last, that's why there is a blank in all because by the time going to the last, it is becoming an empty spot, that instance is complete, this is the instance that is being created, I will have to create a new one again and again, otherwise this one is the same. Whatever result is there, it will keep changing and look at it again and again. 3434 Everything has remained the same, everything has changed, so a new status will have to be created here, a new array will have to be listed here, se tu se ho jaayega tu ka power n ho. Gaya time complexity and space kya hoga 123 hai tu ka power n space complexity ok hai na maximum nahi minimum aapka agar maa liye ka value ban kya hai so see you in the next video please like and subscribe tu me channel
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
1,192 |
looky guys in this episode let's look at the lead code problem one nine two and the problem title is find all critical connections in a network let me quickly go through the problem statement see is that given an undirected graph find on critical connections inside it we'll see so this is the sample graph given to you and let me just before jump into the graph and explain you what critical Direction is let me just go let me go through the input and output basically so the input given to you is a value called n which is the number of nodes which is four in this case so there are four nodes in this and then you are also given a connections array so connection setting is nothing but a list of edges basically so it's a array of edges and you can see the edges are between 0 to 1 then 0 to 2 and 1 to 3 so basically four edges and four nodes total right and what you have to respond back is the output you have to give a list of edges basically so list of some of these edges which are actually critical connection now the next thing we need to understand is what is a critical connection so to give you an example let's just look at this sample graph given to you so this is the graph and then there's before--the node so what is the critical before--the node so what is the critical before--the node so what is the critical connection basically so out of these four edges some of the edges could be critical action the best way to figure that out whether a critical edge it is a critical connection or not is to just remove it so if I move this edge does it drop does it divide the graph into two parts basically and here you can see that all the nodes are still connected since this connection is not a critical connection now if I look at this one basically if I remove this edge this actually divides the graph in two parts there's one part well three and the other part is zero one two three cannot reach out all the other parts this actually ends up dividing the graph into two parts and hence this particular connection is a critical connection so that is the definition of critical connection let's quickly look at look through some of the other examples are simple examples as well so suppose you have just two nodes in the system and they are connected with a single edge now is this edge or critical connection very simple you know just remove it does it divide it up into parts yes now you have to do this strings part which are not connected and hence this is a critical connection let's look at another example if I give you a graph like this in this case if you remove any of the edges suppose I remove this edge does it divide the graph into two parts no it does not so this is not a critical connection similarly this is not an innovative in action and this is also not a political action so in this graph there are no critical connections let me give you a counter example so if you place a node in the center and if you do this right in this graph if you see if you remove any of the edge it ends up dividing the graph into two parts and hence every edge this sense listen it is that all the edges are actually critical connections so I hope that makes the concept of critical connection extremely fear well now let's jump into the brute force way of solving this problem so let me just remove this okay so let's look at this particular example for instance and to explain the problem in a better way what I will do is I will take a slightly modified version of this graph and I will just add one more a node to it and one more edge to it which is three to four so basically now if you see your n is going to be fine you know in the sample input given was four but then I have added one more node so n is equals to five and your connections re connections array which is an array of edges basically it is going to be 0 comma 1 0 comma 2 then one comma two and then you have 1 comma 3 and one more extra edge which I've added is between 3 & 4 basically I've added is between 3 & 4 basically I've added is between 3 & 4 basically right now let's look at keep looking at this particular example let's figure out how do we found and find the critical connections by brute force now if you so the problem statement says that we have to find such connections if we remove those connections the condition is if we move those connections that should divide the graph in two parts right simply filter the edges on the basis of this condition so what we can simply do is just I treat over this array of connections and assume each connection is removed so you know when am i treating on this array and I'm looking at this particular connection what I do I assume that this connection is removed from the system now if this connection is removed from the system I just need to count the number of parts you know exist in the system after this edge is removed how do I do that there is something called as depth-first search which is the DFS so I depth-first search which is the DFS so I depth-first search which is the DFS so I can traverse and traverse the graph use the DFS and figure out how many nodes are reachable so I can figure out reachable nodes so if you're not familiar with DFS I will probably make another video and explain what depth-first search it is or you can look depth-first search it is or you can look depth-first search it is or you can look at other videos also on YouTube available which can explain their terms and search I will put the link in the description in case I will make a video on TFS the DFS search it starts from any of these modes so you know so to give an example suppose I remove this edge so if I remove this edge what happens to my graph starts to look like this you know so this edge is gone basically right now I could be starting my DFS term for Travis Epson from any of these nodes I can start from here or here by just first step of this Vanessa zoom we start from here and then we try and do the DFS Travis we will be able to traverse all the nodes basically and once we are able to traverse all the node and we know what is the total number of would count we immediately know that we are able to travel all the nodes starting from any of these nodes and hence you know my grass is actually connected and if my grass is connected and there are no two parts in the graph we see the my graph is not broken and hence this edge is not a critical connection right and I just repeat this operation for this edge and they said and so on right and when you repeat the operation you'll figure out this is not a critical connection this is not a little connection let's look at this one so once I remove this edge suppose I assume that this edge is removed right so suppose I remove this edge now what will happen is let me put this edge back what will happen is that when you do the DFS travel so you will do the DFS travel some either from any of these nodes are the any of these notes right suppose you do the difference travel for any of these thoughts you will see that you can only reach three info so you will be able to reach 3 and 4 and 0 1 2 will not be reachable and you know the total number of moves are 5 and you are only able to reach two nodes that means your graph is actually broken into 2 parts right or the other condition would be that you probably start with the new of these nodes in that case you will be able to traverse only 0 1 & 2 & 3 or 4 you will traverse only 0 1 & 2 & 3 or 4 you will traverse only 0 1 & 2 & 3 or 4 you will not be able to traverse and hence you know that your graph is broken into two parts hence that proves that this is a critical connection similarly let's look at this particular example also right so let me put this edge back and let me remove this edge the same story is going to happen over here also when you is assume that this edge is gone and you start throwing a doozy DFS traversal if you start sick note 4 then you will only be able to reach node 4 and rest of the nodes will not be reachable and hence you know this is a critical connection all your DFS travels and will start from any of these nodes and that is you will be able to reach 0 1 2 3 and you know total nodes are 4 5 and you are only able to reach for that means your graph must be broken into two parts and hence this is also indicate action so I hope that clears up the brute force way of solving this problem okay now let's look at the optimal way of solving this problem but before we look at the optimal way of counting this problem I forgot to mention the time complexity so the time complexity of this algorithm right can be calculated on the basis of the time complicity of DFS so on so a DFS traversal time complicities order of V Plus E right and how many times you are doing this DFS traversal if for every edge you are doing it once so you can just multiply it by H so this is the time complexity of this algorithm which you can see it's going to be almost order of ve plus e square right and you know that's like a order n square kind of algorithm basically now the optimal way of solving this problem is going to be an order n solution basically so let's look at how we're going to achieve another n solution so to be able to solve this problem we'll order n to be you something called as a thousands algorithm so now tarzan's algorithm you know is a sufficiently complex algorithm and no interview should expect you to come up with something like this in an interview but then it is always good to know these algorithms and the thought process behind them so that you can develop a way of thinking which can help you solve problems so before I jump into you know taxes and Carson let me just explain couple of terms so the first term is strongly connected component and the second term is DFS so devious we already talked about set up first search what is a strongly component connected component venable in a graph if you pick any pair of nodes and they are reachable so node if you pick a and B node and they are reachable you can reach from A to B and you can also reach from B to a and why I am talking about a to B and B to a because transients algorithm works for a directed graph as well you know so both for directed as well as undirected graphs so any pair of nodes if you pick any pair of nodes and they are reachable from A to B and B to a in a given graph that means or in a given come in a sub part of the graph that's a part is called a strongly connected component so that is the definition of song mechanic component and Tartans algorithm was built to find all strongly connected components given a graph you know okay now having said that let me just tell you how I'm going to approach this before STARTTLS into Arkham faced a complex algorithm to explain I will do it in two parts so part one I will talk about the I will explain the working of Tarzan's algorithm so I will explain the working and part two I am going to explain the thought process okay so let's first look at the working of what article gotta get me up this right so what I'm going to do is to be able to explain the working of thousands algorithm right let me just quickly fill of this and start without for graph searches which makes it easier to explain debugging your presence of garden so I'm going to put a graph like this so if you look at this graph right if you look at this graph you see removing this particular edge does not divide the graph in two parts because you know anybody can traverse via this wire node to and then will be this edge but also does not discount the graph this does not dispense it up and similarly for all these edges but this is a very important edge will remove this edge and suddenly your graph is divided to two parts right so this is the critical edge now let's see how tangents algorithm works right Japan's algorithm uses DFS to traverse the graph right first to note the second thing for every move so you know how does difference once you start with the node and you traverse to be next available node which is directly connected and once you reach this node you traverse through the next available this one on this one and once you are done exploding all the nodes like for instance if you go from here to here and this node does not have any new nodes to explore whether this already humans are only being sport that means you traverse back easily and your recursion bumpy so it's a recursive algorithm it a person completes and it comes back at this point in time you still have a part to explore and hence you go on this path and so on basically that's how DFS works so difference nodes aren't discovered you know we start with don't zero then you discover node one and then you discover node 2 then we'll come back then you don't just cover node 3 and so on these notes are notes I discovered that is one thing to you know in the second special what are things Oh while thousands travel bottom is trying to traverse the graph by our DFS it remembers it what it does is that every time a note gets discovered it assigns an ID to it so remember two things it does first thing it does is it assigns an ID on the basis of the order it would discovered so the first node is assigned an ID of zero the second node is assigned an ID of one the third node is I find an ID of 2 and so on basically and the second thing it tries to keep track of let's call it low right but what it essentially is this is the lowest ID reachable from that node right Lois I need reachable from that node now so let me just write it down lowest ID reachable right now this is what it tries to track for every node it Traverse right so these are the two things now the best way to disappear explain this will be by an example so let me just remove this and let's try and traverse through this graph and try these two items okay so suppose my DFS starts from this particular node right so if I'm a day if my DSL dfn starts from this particular mode this is not just quite discouraged I don't know about rest of the graph so what I do is I immediately assign 0 ID to it and because I know only about this node what is the lowest load reachable from this node that is going to be itself so you immediately assign 0 to it so do you know the two values which I am tracking for every mode ok now I go from here to here say for instance immediately assign an ID to it and what is the lowest node which is reachable from this mode remember the only condition is that you are not allowed to travel back right so you cannot look at this side but you can look at other sites but the thing is that other sides are not visible to you right now because you have just discovered this mode so the lowest note which is reachable from this node is itself again basis 1 comma 1 so typically that's how it works once you discover a note you immediately assign the same values to both the discover ID as well and still Louis mode so now suppose you start trying you traverse from here to here so immediately assigned 2 comma 2 now once you have Travis here you start exploring so we do see hey now I want to explore further you see that this guy can actually reach node 0 so that means the lowest note this way can reach is not 2 but 0 at that point in time you change this lowest value to 0 and now you don't have anything further to explore and Note 2 so your recursion comes back you come back here and again now once you come back you compare these low values to 1 and 0 so what this means is that if you can please 0 that means and 1 is connected to 2 that means one can also reach 0 why do you know without looking back remember so it can reach by I 2 so in that case the lowest note reachable is 0 here and at this point in time you have explored this side you came from the side so you have another path which though so now you go jump to this particular node because this is just discovered and the ID you have to assign is 0 1 2 is already gone so you have to assign 3 and the lowest mode reachable from 3 will be 3 basically without going back right now once you have discovered this node what you do is you discovered further right so you go and discover for severance we immediately assigned for and lowest no reachable from 4 will be 4 without way back at this point in time when you start exploring for you go to 5 so you know this is 5 comma 5 okay and once you've explored this node and you see that term now this node can actually reach number 3 you know files directly connected to number 3 so you take the low value three and then you're not no further exploration is possible over here so you've turns back when you travels back you compare the values remember then you when your recursion comes like you compare the low values three and four which is smaller three smaller that means if I can each free flow can also reach three wire five so the lowest mode reachable from four becomes three right and at this point in time you'd throw the travels back so when you Travis back what you do is you again compare at the low values remain the same and hence you know no need to update them basically at this point in time the discovery or a traversal of three has completed and now your recursion comes back so then now this is the important point right when you jump from three to one going back right in your Rico sure you compare the low values again your same algorithm follows right now zero power three when you compare these two zeroes already smaller right this is the more support this is the point you have to be very careful when she travels back and you see that the low value of this node where you come back after recursion completion the low values are already lower than the from the place you are coming back that means you know there is a gap in the low number and that means this node sorry this edge is a critical connection right I'll explain the thought process why this is so but this is what the task is Larkin says that once you traverse back and there is a gap in the low values after you have checked them and updated them so here you have already checked on zero comma zero and three when you compare this is smaller and you have not updated right at this point in time this node this edge becomes in particular action see this edge is not a critical connection because the low values for same after updating this edge is also not allow critical variation this as well so not again because the low values are same meeting at all he'll the low values differ and hence this is a critical connection when you're Travis has competed and you come back at the mean you can compare right the low values are seen and hence this is not a critical direction and one and hence once your travel completes you figured out that this edge was a critical connection so remember two points one an ID which is the discovery ID and the second thing is low the lowest ID reachable from that node to begin with whenever you just discover a node the low ID becomes its own ID and then once you've Traverse further you figure out which is a better lower ID and then when you come back when your recursion comes bad at that point in your point in time to keep comparing the new IDs and keep updating them right and that is algorithm and the third thing is that whenever you are when you have finished comparison at that point in time you figure out there is a difference in the Lu ID and you immediately mark that edge isn't as a political connection now before jumping into the thought process let me just quickly tell you the or time from that city the time complexity of this algorithm is going to be order of V Plus V because you are doing the DFS traversal and only once and that's it a DFS traversal time for Mercedes order be pressing right now comes the important right what is the thought process okay so the thought process in thousand silverton is to explain foreperson let me just tell you let me show you something you know suppose I'll give you a graph like this right if I give you a graph like this can you tell me which edge is a critical edge just remove any of these edge is it information no is this is a critical connection no this one not this one no so basically what we figured out is that if there is a central you know in a graph that graph does not have any critical connections now let's just let me just give you another example suppose the graph is like this looks like right now tell me if there is any edge which is a critical connection remove this edge it divides the traffic two parts one part and second part right remove this edge similarly it divides the graph into parts so what we understood is without a cycle no cycles every edge becomes a technical direction the disciple nor none of the edge become on critical direction and that is the primary part behind darkness important to not to explain that let me quickly tell you half so remember the algorithm say is that you know to be able to figure out the cycles in network - right what it does is - let's take an - right what it does is - let's take an - right what it does is - let's take an example right let's take this graph so remember so for simplicity sake let me assume that you know the IDS are ABC and D so these are not IDs these are the identifiers of the nodes right so what does important says do a DFS traversal and assign keep assigning ID as you discover the amounts so suppose you disability starts from here you won't assign 0 1 2 3 this is how the IDS are going to get assigned and got to be the lowest low numbers the second value tracked you can assume that to begin with it will be like this ok but once you the Commission has started here and remember this function is going to go one after the other and this 3 will be the last would get discovered when this node figures out that it is connected to an already discovered because the side is already lower than the idea of itself that is when we have found the cycle and once it has found the cycle it updates its lowest value to the lowest note region and that low numbers propagates while you are coming back so this becomes 1 and so in a loop the low values will be the lowest number in the loop itself you know so if there is a loop in us in a graph see the low value will become the lowest node involved in that room you can see over here there was a loop over here of 3 4 & 5 nodes and the lowest fan here of 3 4 & 5 nodes and the lowest fan here of 3 4 & 5 nodes and the lowest fan low value became 3 if you can look at this one there's a loop in here and the low-value became zero and the low-value became zero and the low-value became zero right and that is what does is not some is trying to track and so and why so I talked about right whenever there is a gap in the low value you immediately map an edge as a critical connection and that is what does logic says that if the low values are different that means these nodes are part of different loops and hence if they are part of different loops this end becomes a critical direction so that is the thought process behind thousands and more of them and here you can see what will happen is with let's work through this right because I've done this graph let me just walk you through exactly hard so the first thing this gives discovered zero and the zero becomes the no value then this gets discovered one and one becomes the no value and suppose it just gets discovered so 2 comma 2 becomes the low value this gets discovered 3 power 3 becomes a no value at this point mu is figure out that B is connected to B so the minimum ID it is it can reach is one so you update this to 1 then you've got more Travis back you up take this one and because you know that there is no gap in the blue values you do not mark this edge is a critical connection you do not mark this as a critical connection who travels back no difference in low values you do not mark this is a critical connection and once you traverse back you see 0 is already lower than 1 so you don't replace 0 and hence and now you see there is a gap the low values and hence you mind this as a critical connection and that is the part behind cancel bottom of the city I already told you that it is going to be order of E Plus E and let's quickly run through thousand here are some three given problem and one last time so that you know it's extremely clear that how really UVU stands as welcome to solve this particular problem so what you have been given is 2 0 & 3 right now what been given is 2 0 & 3 right now what been given is 2 0 & 3 right now what will happen is that you will start the disparity from anymore possible so to make it slightly more interesting let me start the of the travel cell say from say this is not possible right so suppose I start to travel set from this morning this becomes the ID zero and the lowest mode reachable is zero right when you travels from here to say let me that starts on the other segment so if you tell us from here to here the idea becomes one comma one you know so the ID one and the lowest value reachable is 1 then you from here without going back you drive us on this side and the idea of this guy becomes 2 comma 2 and at this point in time let's turn some in this language so at when you travels from here to here this becomes the third node to believe a certain fourth row to be discovered so I did with times 3 and the lowest mode reachable right now s3 itself now if you don't wave back this node what is the lowest mode can reach it is still itself visible so nothing to update any further so once you've explored node 3 once you know that there is no more edges to explore node 3 at that point in time your recursion starts to go back and because 3 still can reach itself as the lowest node and once you go back you compare the low values 2 and 3 and remember you always take the lower one so you take 2 you see you don't update this and who becomes the lowest mode is still reachable from point 1 and because after you have compared you figure out that there is a jump in the new values you mmediately mark this edge as the critical direction at this point in time remember we came from here to here this H word stood unexplored right so what happens is that this at any PR at this node becomes baby expert this edge at this point in time you figure out that this node is actually reachable it can reach ID 0 so remember this value doesn't matter we can reach ID 0 so what we do at this point in time update will go value to 0 right and now but once you have reached once you have of export this particular edge and you know this is already explored node then that's when you recursion try and goes back so now once you go back your can prepare the low values 0 with 1 you figure out that 0 is smaller so you update the globe and you can see over here and then from here you go back here and then at this point in time your low values will mean the same and because there was no jump in zero so you none of these edges become critical connection and hence the Tarsus algorithm is completed and only one s was found as the critical connection I hope that clears up the Tarsus algorithm and the optimal way of finding critical connections on your network this is a fairly complex algorithm to understand but once you see the picture until you see the reasoning behind it then it is extremely clear to you yeah thank you
|
Critical Connections in a Network
|
divide-chocolate
|
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.
A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
**Example 1:**
**Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\]
**Output:** \[\[1,3\]\]
**Explanation:** \[\[3,1\]\] is also accepted.
**Example 2:**
**Input:** n = 2, connections = \[\[0,1\]\]
**Output:** \[\[0,1\]\]
**Constraints:**
* `2 <= n <= 105`
* `n - 1 <= connections.length <= 105`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* There are no repeated connections.
|
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
|
Array,Binary Search
|
Hard
|
410,1056
|
746 |
That God Today In This Video Will Give Water Problems From Its Problem Minimum Cost Climate So Let's Problem Statement States That Give Not Interior Cost Where Is The Cost For Is The Cost Of The Five Step On Shades Problem And Subscribe School Nov15 Separate Live One And to like going to subscribe by clicking on the like button, subscribe to Anupriya in very minimum amount and minimum cost you will like but do it by practice but whose stomach is full then this is the first problem in this novel of the first year. This fruit fly with different where no infinite different 20 it is the different 4286 minimum 50 from school that school every stage possible don't just amazed me poisonous 59 suet subscribe share and subscribe this channel now to play the song of the same problem with the best all the best hello how to find out the minimum kushwaha is tree should pincode of state for deaf years daughter of i will tell you.by minimum you.by minimum you.by minimum a call to reach filed step by step the water reservoirs step and when and Cost of this page guys let's you the same thing is I am the first how many cost artificial solid waste macrame dutiable tablet clear 123 456 latest like share and i want to two three four five 60 first come first year second year third subscribe channel to the Page if you liked The Video then subscribe to The Amazing spider-man Talk About All The Best I Constructed At I Want To Difficult Hair's The Gaali Bachchan Introduced S What Is The Cost Minimum Course If You Give Attention Deficit And Honesty Certificate Has Given Directly From This And This A Good Practice Turn On This Year Tired Of This Behavior That Boat In All Potato Your Stomach Woman Back To Options I Can Either This ₹3 Will put here Options I Can Either This ₹3 Will put here Options I Can Either This ₹3 Will put here gift Husan Chand Sahu and for watching can be I can or absorption of direction from which year student of aa that laundry vision smartphone option candidate of state district and dentist Anand from British Indian go from this purpose avoid this regard for students And distributed free of cost to validate 9 and third roadways this what is the minimum balance less than 108 in 70s and total cost of five plus one subject to notification total cost of rs 600 on flights from The amazing that is equal to the current cost Vikas Island in this particular ID block taste to give Into the account the first thing is the cost for this by doing development to land of sacrifice there costs and value is the prevented from which I am coming to recipe because system prevent yes I am who is pink and comment on distinctive head quarters pair that israeli light Come from next year students came from this taking roads traffic thum in the office of loop admin solas minimum of DPO Ivan most of and chief minister this that Azad Chowk and festivals of good crop order on this one Android user can choose from Lal Kitab And Astrology Problem Author Siddharth Yachha 2011 President subscribe The Channel Please subscribe and subscribe the 200 g Dasha Details for Pyun Two with the Cost Five Plus The Meaning of the Best to Take Water When and Respect Introspect and Tell the Final Answer C The 9th Thanks Edit Minimum Price Trigger Cutoff Two Boats Dadri Staff and OBC to Begusarai Junction From This Back to Add Cost of But I Don't Be So They Can Come From This President Two of Three Injured and Electronic Absolutely Minimum Two Value Stories Scientific Officer Tuesday State Back to Where I Can get message candidates from this president to aishwarya last put and third the elected mls to loot meaning of beef and was born into a I office late from Z2 status 2012 staircase that joy security I want to go out about freedom to freedom bluetooth on trees To Upload A To View To Bay In Right Earnest Request Na First Floor Back And Flag Na First Floor And Most Widely Observed By Women Want You To Know What Is A Follow Point Is The Top Floor The Last One Different Countries But Last Over Again It Is this what is the laptop from delhi to contest from last to options last option a and sunao and 1977 my mother very high volume because from any of the last step typing good player and will not in quantum yoni problem display logic and quotes for this Problem Ephedrine Thank you for watching my video Have established as malefic and white
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
518 |
hello everyone it's m satchel again and today we're going to solve another programming challenge this is actually the fourth problem in our series which was supposed to be 100 problems solved the website would be lead code but this time one of my friends has sent me this problem so let's just go through it and see what we could get out of it okay problem 518 coin change 2. you are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money return the number of combinations that make up the amount the total number of combinations that make up the amount if the amount of money cannot be made up by any combination of the coins return zero so you may assume that you have an infinite number of each kind of coin the answer is guaranteed to fit into a signed 32-bit integer signed 32-bit integer signed 32-bit integer okay so here basically uh the inputs if the amount is five and the coins are one two five we could do it in four ways either give them one five one coin with the value of five or give them three coins two with a value of two and one with the value of one or give them four coins one two and three ones or give them five ones and there are four ways to do this change okay but if the amount is three and we only have coins two unlimited number of them still we couldn't make three with the only coin two obvious and if the amount is ten and the only coin that we have is a type 10 coin even infinity number of amounts of coins we only could do 110 with one coin there's only one way to do it okay uh let's see what the constraints would be so the number of length of the coins is between one and three hundred each coin individually is between one and five thousand all of the values coins are unique and the amounts that we're going to change is between 0 and 5000 okay i think i've got a good sense of what this problem would be so let's just jump to the solution then so based on my experience this problem is some kind of dynamic programming type of problem so if we want to see we call it change of amount five with coins one two and five how many ways we could change this then this is how i would approach it first we say that we won't use the coin number one then we count how many times how many ways we could do the change with only coins two and five then we say we only use one coin number one how many chains we could do with coins two and five then we say we want two coins number one how many chains we could do with coins two and five three coins number one four coins number one and five coins number one and if we sum all these um values together then obviously we would get uh the total amounts that we are seeking so this would be for one zero usages of one then it's like we're solving this problem with five for two and five right so this means that uh the coin uh one is not used we only have two types of coins but if we use one of the coins then we would we used one so our absolute change has decreased by one now how many could we do if we do use two ones then it's not changes change how many could be done but it's going to be three if we use three coins uh obviously the remainder is two so the first parameter is the remainder and the second is a set of coins that we have if we use four of them then one and last but not least if we use five then we would have something like this so if we add all of these together at the end it's the number of values that we could have so for change zero and with the coins two and five there's only one way not to use any coins for the change one with coins two and five there's actually one way to use two coins of two and that's it for using one two coins of uh using three coins of uh one oh no sorry this doesn't have any so this is saying we're using four of ones four of one coins the remaining amount is one we couldn't do anything with these coins to make the change if we use three coins then there's one way just use one coin of type this type two if we use two coins there won't be any way to do it if we use only one coin there is one way to use two twos and if we don't use any ones then there is actually one way to use just one five and if we sum all of these together then we would have uh four which as the problem states here it's four and we got the correct answer but we have to remember something why did i say that in my experience this is dynamic programming problem because if we go this is a recursion right it's a recursive function if we go in deep in then there might be times that we are over uh we are calculating something multiple times and that's not pleasant for us so uh to make sure you understand what i mean let's do this let's do a simple implementation with the recursion and show you that this problem won't work with just a recursion and it's an easy step called memorization we could use that or use dynamic programming from the bottom up because memorization does it top down and we could do a dynamic program from the bottom up to figure out the numbers okay actually i'm not going to use this function as my recursive function i'm going to write another function which is going to be called number of ways for example then i'm going to pass in an amount as the problem says the number of coins because we must know how many coins are left and i want to pass in another value which would be uh coin index so what is what does this value mean it means uh we used one we use two we use three so on and so forth okay so this is going to return a number obviously if the amount or the change or whatever we call it remainder but the amount is good for now if the amount is zero obviously there is always one way to do it so number of ways if amount is zero it's one every recursion needs an endpoint and here in our case if the amount is zero then we're returning one if the coin index is greater than greater and or equal than the uh coins and low coins dot length in this case also we would return zero because uh like this is index zero index one index two now if we say that's the index that we're currently are going to see we're shortening the array i'm not going to actually pass the shortened array what i'm going to do which i could do it i'll tell you why i'm not passing the shortened array and i'm passing the coin index instead uh so if the coin index is uh greater than uh the size of this so imagine that we're always passing here the index is one this is the same as saying this so if now we say three it means we are out of scope and we don't have any coins so in that case obviously it's going to be zero okay so we're going to have a few uh things that we have to consider there is a for loop to generate all these sub calls so the forward loops would be like this let's remainder at the beginning is at the same as the amount then as long as the remainder is greater or equal to the amount we continue i don't have an increment for this problem at least so what i'm going to do is decrease an amount from the remainder first i'm going to say okay the coin index that we are in so remainder negative equals to this is equal to remainder minus coins at coin index so i'm going to decrease the amounts here but i'm not going to do it first i'm going to call the itself once more and i'm going to have the result which is initially zero so if we do know the number of ways that we could make this amount using with the same coins without using so at the beginning the remainder and the amount are the same so we say the remainder instead with the coins without using the coin index then we can just sum them up right and each time that we calculated that we'll decrease the remainder how much as the amount like we're using this coin one more time calculating it we're using this coin one more time recalculating it but we are increasing the coin index by one here to go to the next coin so the remainder which is initially the same as the amount with the same coins but from like it's like we're not using it at all then for the first time we use it once we use it twice we use it three times and so on and so forth then we want to return the remainder the results okay so in the main change function what we're going to do is number of ways the amount we're going to definitely return it amounts coins and yeah just gets what it returns so let's run this code for the first time okay so the initial index would be zero we're starting from coin zero it's complaining that we should have passed three i three parameters but we're passing two okay so it says that we got zero but we would expecting four let's see so if the amount is zero we have one way if the coin index is greater or equal than coins dot length we have nothing the result starts with zero then we start incrementing it a number of ways which would be decreased by the coin index so um should be starting from the amount as long as equal to zero yep that's the problem as long as the remainder is not is greater than zero because we're not going to do the negatives let's check it right now yes okay let's test the use cases and see if it works so we passed all the initial test cases that the problem stated so let's just submit it and i'm going to show you that we're going to get time limit exceeded because we have sub recursions overlapping subrecursions which is an obvious case for dynamic programming so let's submit it and we wait and the results would be waiting more yes time limit exceeded so it took way too long because we have tons of overlapping states as we imagined so let's solve this problem and i know exactly how with a simple memorization the trick to memorization is you first solve it with recursion then each time that you're going to read the data from the recursion you check the memory to see if it's been pre-calculated if it has pre-calculated if it has pre-calculated if it has then you just read the value from that calculation instead of recalculating it again so let's just double check the size of the problem once more as you can see the size of the problem is the number of coins is 300 and the value of amount is 5 thousand so we could have a two and this is exactly why uh i went for uh having a simple uh index instead of passing the area because now i could memoize it so this is what i'm going to do first i'm going to have a number of ways memoized something like this and it's going to be a two dimensional array so for let's i equals 0 to i 5001 i plus then number of ways memoized is going to be a new array and for let's say j from 0 to j equals 300 there are at most 300 coins then let's make it a little more clear a little prettier and readable then a number of ways memoized i dot push negative one so this is the way that we create a two dimensional array with dimensions 5001 and 301 so here as i said we first oh we have to do something else we first go to this part and change the contract of the function and add this number of ways memoized which is a number to uh the contract and we will pass it here as well so it would be number of ways memoized and here since we have access to this and it's always called by reference because it's an array so it would be changed mutate it's going to be mutable mutatable then we would have if this amount for what was the i it was the remainder the five thousand the maximum number was supposed to be five thousand so the remainder is from zero to five thousand and one and what was the index of hours the index would be coin index plus one right we want to see if this value is negative one meaning we have pre-calculated it we have pre-calculated it we have pre-calculated it if we have pre-calculated it if we have pre-calculated it if we have pre-calculated it then if we haven't pre-calculated it we haven't pre-calculated it we haven't pre-calculated it first we calculate and place it in the array would be remainder coin index plus one equals this and then use it remainder and coin index plus one so uh all we did was just memoize what we have pre-calculated memoize what we have pre-calculated memoize what we have pre-calculated let's make sure we don't have bugs and it works for its data okay but got three yes here in calling it we should have passed number of ways memorized as well so let's run the code again okay so initially we should have made it equal to an empty array so we could push stuff on it let's run the code once more and we get all the test cases again so if we submit it hopefully this time we would pass all the tests yes and as seen we get a great nice success here so let's wrap it up once more we said let's use the name of the functions that we just used to not make it any more confusing that it is okay so the expectation here is that you know the basics of recursions so what we're doing is we create a function called number of ways this is the remainder amount that we want to calculate and we're passing the coins that we could use to do those calculations then this is the index of the start of the coins that we are going to use and the problem itself said that it's going to assure that it's actually unique so starting from zero uh we have all the possible combinations of coins one two three to solve that we take the coin one there are six possible outcomes either we don't use any ones we use one two three four or five ones if we don't if we use six ones as you can see here then what would happen is we are getting to a value which is negative obviously from here we couldn't make any more changes so if we use zero ones we have five left with these coins starting from one so it's two and five if we use one once we have four amounts to be changed left and we have uh three coins but starting from one so on and so forth and this code for the implementation we use memorization meaning we created a two dimensional array this is typescript by the way so we define the type it's going to be number one dimension would be the amount needed to be changed and one dimension would be the index of the coin we're starting from so first initially they're all negative ones we say as we said here the amounts we want to change the coins starting index the amount coin starting index and we are always passing this memory's memoized array to it then in the number of ways what we are doing is that if the amount is zero this is the base of the recursion we are sure we should return one if the index of the coin passes the length of the number of coins that we had there's no other way to do the change then for the other than these two base points we say the results starting from zero imagine that the remainder is this amount then unless the remainder is greater than 0 this semicolon says that we don't have any increments we could have done it with a while taking this making the while extracting this outside and having just one condition but i did with a four and there's no difference with in these two uh loops so if the memoized which is passed pre-process the remainder pre-process the remainder pre-process the remainder with the next coins means it's not negative one anymore we calculated remainder coins and put it in the mobilization otherwise we just added it means we have the value and we don't need to calculate it so we just add it to the results and there and use one more coin as we saw here use one coin use one more coin and the remainder just decreases and after we have done that we return the results and as we saw it gives us uh the perfect answer so uh thanks for your time for today hope you enjoyed it uh we are going to solve more problems in the upcoming uh days stay tuned like and subscribe if you want more content like this bye
|
Coin Change II
|
coin-change-2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Array,Dynamic Programming
|
Medium
|
1393
|
20 |
in this episode of coding adventures we're gonna implement valid pagan thesis from lead code so let's get started if we get here the text of the problem it's also an easy problem it says that we're gonna receive a string of characters made out only of these brackets like three types of brackets and we need to determine if the string is valid and there are some rules basically mostly saying that open brackets might be must be closed by the same type of brackets so let's look at a few examples for instance if this is the string that we receive because it's open close this is a valid string the same with this one it's open around parentheses opens close account parenthesis opens square parenthesis and close square open curly braces close square brackets so this looks valid uh this one they say it's invalid because we are opening one type of parenthesis but we are closing a different one so we need basically to write a function exactly like they provided here the prototype and we need to determine if basically this string is valid so let's switch a little bit to the white board to the notebook and right let's try to figure out the solution so let's take perhaps let's take a different type of string one that wasn't provided in the exercise in the examples there i'm wondering if this is a valid string according to the description should be because we are opening us round one then opening a square one but when we are closing them they match exactly these two match and then these two match so let's see how we take this problem so we obviously have here four characters and we take them one by one like this so the way we're gonna implement it is the following i'm thinking to create a stack structure which is basically let's name this one it's a it's type of a structure where basically um let's say if we add a number here or a second number it looks like a stack like you put numbers on the bottom but in the moment you put them they stack one on top of the other but in the moment you remove them you remove the one from the top so it's basically last in first out type structure and we're going to do it in this way if each time we're going to find uh account parenthesis here uh we're just going to push it to the stack each time we're going to find or each time we're going to find an open parenthesis we're gonna push it to the stack so let's say we found an open round bracket we push it to the stack we found the next one um square one we push it to the stack but in the moment we found a closed one this one we won't push it on the stack in the moment we found the closed one what we are doing we are removing the last one from the stack and we are comparing them and if they match it's fine they uh it we're gonna boost case and then of course the stack will be uh three here this element and then we found the other one and we are looking what's left on the stack oh it's an open around parenthesis okay it matches with this one so these things looks valid so let's see how we implement this one uh in the code like we said uh we're gonna implement it uh this kind of a stack which is very easily in javascript can be implemented with an array basically and again has this kind of um ability to push and pop elements into it but before let me arrange this code um in the in a different way that it's more um it's easier to read for good newbies so all right so we have the function is valid and we are receiving one of these strings as argument let me put one of these strings exactly this one so we are receiving uh yeah this thing as an argument it's a string we put it between codes and we need to determine if this uh string is valid or not so let's have a stack here instead it's inside which is like an empty array we can simulate a stack with an empty array and then let's integrate to all the characters of string s so see it's a character in this moment and we say if c basically if we said if c equal to open parenthesis well what we have to do is to push it so stack dot push we push the character and as a matter of fact we're gonna do the same so let me copy this one really quickly also if it's a round if it's a square and if it's a curly one okay so we are pushing it and now what will happen so after this let's put an elsif actually i'll see so if we are on this branch here else it means that the character is not one of these ones so can be totally different characters or it can be closed brackets but i think in the problem here just to keep it simple they say that uh the string contains only this uh yeah this thing contains only this kind of symbol so we should be fine we don't have to test for extra symbols and extra cases because it's a simple problem but in a more complex one probably we'll have to check it so right now we have to check the other one in the in this point on the else statement here we know for sure that it's either one of these symbols but which one it is so um at this moment we'll have to pop the last character from the stack and basically if it's a put again the logic if the current character it's a close parenthesis and the one that we popped from the stack it's an open one then we are in good shape it will be a lot of ifs let me think all right let's do something like this all right rather than pushing on the stack the ca the actual parent test is let's push on the stack what we should expect so i'm just putting the complementary of the parenthesis the complementary parenthesis in a sense so this is the open one this is the closed one so this is that curly okay let me take back the notebook and show you that these optimizations will help us a little bit to avoid just the extra ifs all right so the first case let's do again the stack so we encounter the first parenthesis here what we are putting on the stack we are putting this one we are encountering the next open one what we are putting we're putting the closed one now we encounter a closed one and now the pointer is here of course now we encounter a closed one well it will be very easy we just have to check if whatever closed one we encounter if it matches the stack and then we encounter if we take this one we just have to check if it matches we don't have to verify which is the complement again so we're gonna avoid all a bunch of beeps again so let's write it this way so we're gonna else we have to pop it out from the stack or we can do it in a single statement if basically if the current character it's equal to the stack dot pop or let's say if it's different then the one from the stack here we return false all right so the string is not valid otherwise if we just finish everything we return through so if we check all the characters of the string and all they are matching perfectly with the tank room well it's much better to restart to check the stack length if it's zero uh why just in case let's say somebody provides us with a string something like this it's open parenthesis but no close parentheses well in that case we're just gonna place this one on the stack so is this string valid obviously it's not valid because it doesn't have a close parenthesis but all this co will be just a lot of push on the stack this branch won't happen so basically we have to check here at the end if the stack is empty so the only way in which the string is valid is if we don't go out on this one so basically we don't encounter gonna stack an unexpected character and if at the end of all the iterations the stack is empty so let's try this code and see if we are correct let me zoom out a little bit and run the code all right our solution is accepted and it's actually a pretty simple one i'm not sure if we can do it much better perhaps a little bit better would be to and perhaps we can use a map again just to in case there are multiple symbols here uh not only this three symbols so in our case or three maybe it's much easier if we just have some sort of a lookup structure some sort of dictionary and we can check those so let's implement also that kind of let's have also that kind of implementation right so let's copy it again it's valid and let's start with the map now we're going to provide the second implementation but in this particular case there is no advantage in performance we just want to provide the different implementation all right so it's a new map and i think i saw this kind of implementation some time ago uh and i found it pretty clever so uh i'm gonna try to create a similar implementation like this one so let's put in the map first of all the symbols and what we're gonna put in the map we're gonna put as a key the opening parentheses and as a value we're gonna put what we expect for that parentheses so the complementary one all right and then from this point the algorithm is similar we're gonna scan uh the entire a and if we're gonna check if the character that we encounter inside the string is a key inside the dictionary so basically it's on the first column here um the map has a special property to check if a value it's a key basically then we're gonna push into the like we said we're gonna push into the uh dictionary the complementary so we're gonna push this one so uh basically the same implementation as below so let's have a stack like this one then we scan the entire string each character we scan each character in the string like we said and now we're gonna check the map if to check if basically if the character is on the first column or is a key we can ch we can say map has so if map has this c we can put a command here c is a key in the map structure so what we are doing if it has uh obviously we're going to push it exactly like he here on the stack but see what we are trying to do is to avoid all these the other ifs so if it's a key inside this one let's push it stack ah stack that push we are pushing the character and actually let's do it like here not push the character but actually push the expected uh closing character so that will be uh we'll have to obtain the value for dc which is basically instead of c it will be a map get of c parenthesis in parentheses if you are not comfortable with this we can put basically inside the block and we can read this one the value and then we are pushing the value in a separate line but i think we are fine uh with one line here so at this point uh if it's not a key it must be a value what we are encountering when we are scanning the string right so we can have an else here so i'll see if uh we're doing the same logic here we're gonna compare the stat the character with the character that we are giving from the stack and if they are different we return a force so it seems different than map stack dot pop we are returning force like here it's exactly the same logic like we did before and if not we are just returning and let me copy it in this line or say return if we finish scanning all the string and if there are no elementary thing remained on the stack stacked or length is zero so this gets evaluated to true if there are no more elements on the stack and we should be in good shape should return through basically the string being valid so uh is the same algorithm as before but we just avoided two more uh two extra ifs by keeping this in a dictionary so we switch it from code to a data structure kind of implementation so let's try to run it all right and the solution is accepted again we have here both our solutions let me uh minimize them okay the original one which is also pretty small um and the second one but as i said uh i saw this one some time ago and uh it looked you know i just wanted to present it to you all right so uh this concludes the today's episode and until next time happy coding and see you next time you
|
Valid Parentheses
|
valid-parentheses
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`.
|
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
|
String,Stack
|
Easy
|
22,32,301,1045,2221
|
1,187 |
um hello so today we are going to do this problem which is part of with code daily challenge make array strictly increasing so with this problem we have two arrays we have array one and we have array two and we want to return the minimum number of operations it's possibly zero that we need to make array 1 increasing okay now how do we use this array too well what we need to do is choose if we find an element in Array one where it's out of order it's not strictly increasing what we can do is take an element any element we want from array 2 that we having to of course use yet and um nanosol I haven't used yet it seems like we can use multiple times but we can take an element from array 2 and use it in Array one I'll place it basically replace that element in Array one so that we can get strictly increasing now if it's not possible with any elements of array 2 to get the array to be strictly increasing then we return minus one so let's look at an example that will make it easier so here you can see if this is out of order so we can do is take this 2 from array 2 and replace five with that right so put two here that way we have one two three six seven so we have an increasing um a strictly increasing array now another example here and what we want to return is the minimum number of operations so here we only need to use one so we return it's not possible to use zero and so the minimum is one now here with this one you can see 5 and 3 here are out of the order so what we can do is take this three and replace this one here but then the problem becomes that these two are equal three and so one applies this three here with four from this position that way we have one three four six seven which is equal now you if you can see if you can try multiple combinations but it won't work because we can't use one here because then it will be equal to the previous one we can't use four here because if you use it we use it then we can't get this three to be increasing um because 4 is bigger right so that's why this is the best we can do so return to so that's the idea now if we look at the constraint here we have up to two thousand okay so that tells us we could sort of try all possible combinations um but how can we be smart about it well the first thing to note is that with for array 2 you could all if you have multiple elements with the same value you can only use one of them because the array one has to be strictly increasing so let's say for example in Array 2 if we had um maybe three two three times four we can only use one three because if used if we use two threes that means in Array one we would have two elements that are equal but array one is strictly increasing so we can't and so the first thing we know is that we don't need we can remove duplicates from array two now the other interesting concept is that is sort of greedy concept which is that for array one if we find a position that is out of place it's always better to pick the smallest value from array 2 that will make it strictly increase and it's always better to pick the smallest right so if we find a position out of place it's always better to take smallest valid array too value okay why is that because let's say for example let's take a look at this example with array 2 here this one for this five because it's out of order because 5 is bigger than 3. what we did is we shows the smallest three because if we choose the biggest which is four then we may end up in a position where we can't make the array strictly increasing right because here if we use 4 the now for is then either we have to use four here or three or one but the problem is if is 4 then this would be equal so it's not strictly increasing if we use three it's smaller so it's not strictly increasing either and one also smaller right so it's always better to pick the smallest first that will satisfy the condition um because then we would have a better chance for the next one to use the greater value the bigger value right now here we can put one because it's equal that's why I said here valid the smallest valid one okay now how do we easily get the smallest valid one well for a position let's say here for five how do we do that well for five what we want is we want the closest larger value to three okay the closed value to three because all that matters actually is the next element so that it's smaller than it right so we can choose to pick the smallest the closest Value to the next one sorry the closest Value to the current one to the previous one right so let's say we are here for this one the previous one is one okay so we want to choose the smallest value that will be bigger than this one how do you do that well that's actually what bisect does what binary source does so what we can do is sort array two and now it should be easy to just bisect we want the closest bigger value to the previous element okay so we want to bisect right that's the to get the closest to the right closest bigger value so if there isn't one element closer to one we're going to get to the next one not one itself so we can basic to array two in Array two looking four what we want to look for is the closest to the previous element okay and so this will find us three it won't find one because we want to the right so it will find us three so once we get the index of this one this is the one that we are replaced with so already at this tells you that we need to keep track of prefix and since we want to try all possibilities as I said here because the um the limit is small what we can do is just have a function let's call it DFS because we'll explore everything passing the index in Array 1 and pass in the previous value now this previous value can be either the previous element from the array 1. or the one that we just replaced the one element of array one with from array two right so for example in this case let's do it so in this case first it starts out with the DFS from 0 to in the previous element initially let's just pick -1 because the array is just pick -1 because the array is just pick -1 because the array is guaranteed to be positive right the elements are guaranteed to be positive so we just pick an element that is outside of the bound so that it's always smaller it's for replacing we actually it's easier for us instead of doing it only if this is smaller if it's out of order what we can do is just for every case for every element you just try to replace with an element of array2 but pick the closest right pick the closest so we can do here is just bisect do this bisect here for the previous value so that we can find the smallest closer the closer value to pref and just replace it so what we will mean by that we don't actually need to replace it in theory we can just pass it to the function right and just here since we did the replacement we did an operation here and so we need to increment by one and so our count here would be for each call would be just need to be the Min of these two this one and this one okay and that's pretty much it without a cursive function so I'll just write out its color tone here so we need a DFS call at I and we need to pass the previous value so if we reach base case is if we reach the end of array one okay then we're going to return zero no operations needed anymore and now we need to do this call here so we do our DFS but we can't go to the next element using this one as pref if they are out of order we can only do it if they are in order however we can replace into an operation anytime and so that's why we do it like this but remember here the priv now is the element from array 2 because this is what we replace the element at index I with but instead of actually putting it in the array we can just pass it as the previous value that's all we need because we only need the number of operations but this is only if the element actually exists in Array two if it doesn't exist then we can't replace it with so we have to check if it exists which means smaller than the length of array2 then we can do this and now we need to keep track of the Min for the number of operations so let's start out with a bigger value let's say taking the mean of the count here so here we take the Min like this and here we want to also take them in of all possibilities here and then we return that now we want to call it with 0 and the priv initially is -1 but 0 and the priv initially is -1 but 0 and the priv initially is -1 but remember we wanted to also remove duplicates and sort array too so that's what we'll do first we'll remove duplicate by just getting a set and then getting the list out of that set the rule is sort array 2 and now we get a cast here or let's call account and now we return the account but we want to make sure that it's not in case there was no solution then this would be right in case this was false and this was false then this would be infinity and so that means it's not possible so when I return minus one so we check if count is different than this otherwise it's different than math if Infinity otherwise would return minus one like this so if we're on this it should work it looks good but we want to also cache right so we're going to catch the calls here so you could use a hash with just these two as the keys but in Python I'll just do it quickly using the using a cache like this so if I run it again this will do the same thing as using a map and so let's see if this works um still time limit exceeded so that means basically our cash limit was too small so let's just make it bigger okay looks good let's submit okay so that passes yeah so that's pretty much it with this problem um as an exercise you can try to do it with just Loops instead of recursion here uh but that's pretty much it thanks for watching and see you on the next one bye
|
Make Array Strictly Increasing
|
print-foobar-alternately
|
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9`
| null |
Concurrency
|
Medium
|
1203,1216
|
95 |
hey everyone today we are going to solve the little question unique binary search V2 so you are given integer and return all the structurally unique binary search V which has exactly any nodes of unique values from 1 to n returning the answer in any order so let's see the example so you are given n equals 3 and we can create a five unique binary so that's why output is like this yeah very simple question so let me explain how to solve this question okay so do solve a discussion I think there are three important things so first thing is that so in the code we call the same function recursively at the time we passed like a start value and end value so we try to create a subtree with this range so start value is a minimum number of distance and the value is a maximum number of this range so every time we pass the start value in the end value so that is one point and but how can we decide the like a start value in the end value so that is the second important point so for left side so we pass the same start point because this is a smallest number right and then for in end value is like a root minus 1. that's because uh all value on the left side must be smaller than its root value right so that's why we can't create a node like a which is a like a greater than root node so that's why uh antibody is always root to -1 to -1 to -1 and therefore right side or right side is so start point should be greater than root node right so that's why start point should be root plus one and then and the point is same and so that we can create a like a subtree on the left side and the subtree on the right side and then after that so we combine a little by little so that is the second important point and the third important thing is that um we call the same function recursively so I think we try to create a subtree with same starting value in the ending value so it's good idea to keep result of current starting value in the ending value so that's why we use a like a dynamic programming so key is a combination of starting value and ending value so let's say starting value is one and the ending value is five in the case we can create this tree and if starting value is 2 and the ending value is 4 we can create this and this triangle tree something like that it's very time saving right yeah that is a southern important point yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write the code so first of all if n equals zero we can immediately return empty list and not the case so now let's say memo so this is for dynamic programming and the digitalized with like a hashmap in the return so generate trees uh so generate trees and uh range should be one two n right and then let's create a generate tree and oops start value and end value so first of all if so start and in memo so we don't have to like uh create a subtree so that's why the memo in the start and end if not the case so initialize trees with an empty list and if start is greater than end in that case we stop the guardian and then tweeze Dot append so if study is greater than n so there's no range right so that's why we should append null so in Python no and then return treats to these if not the case so let's iterates from the range from the like a start and start to end so loot so this is a root bar in range and the start and the End plus one and then so Rift trees should be so call this function again and start value is same and the and barriers should be root bar minus one so this is a second important point we talk about and then right tweets equal so we use the same function and in this case so by all values are greater than root value so that's why loot Value Plus 1. 2 10. and then after that so let's combine the trees little by little so for left threes now left three in left 3 is and have all right between right and tweets and uh so root equal three you know so root value should be this value and then so left and the right so just a lift left 3 and the right three and then after that just append this dot three to trees so append and a root so after that um just uh we want to keep the result of our current starting point and starting value in the end value so that's why key should be start value and value equal to these and then after that just return tweets yeah I think that's it so let me submit it yeah looks good and I believe Central algorithm be the 98 percent so time complexity and the space complexity of this search and should be order of C so C is a carton number of n so I don't explain a detail of cutter number so if you are interested in the number please give it 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
|
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
|
41 |
hello everyone so today we're going to do the problem number 41 on lead code which is finding the first missing positive so we're given an array and we have to find the smallest positive integer that is not in the array so like this one you have one two zero the smallest integer that's not in the array is three here you have three four minus one the smallest positive integer that's not in the array is 2 and same as this one smallest positive integer that's not in the array is one so what we can do is that we put so before I go into the solution the trick I'm using here is that the smallest missing first missing positive number can never be greater than the size of the array right so like if it was one two three four five right so the smallest missing what positive number would always be from one to n plus 1 right it can never be beyond or greater than n plus one because if you like if you have an array of size five and you have something that's greater than five like six then you definitely have a number from one to five that's not in the array because the length is five and you already have a number greater than five that means you know there's definitely one number between one to five that's not in the array where and then the other case is when you have negative numbers so if your array length is five and you have a negative number then you know that between the of one-to-five there's at least one of one-to-five there's at least one of one-to-five there's at least one number that's missing because its place was taken by a negative number so that's how I'm looking at this problem so then if we know all the numbers that are in the array we can just iterate then from 1 to n plus 1 and see what number is not in that set so I'm gonna start coding here so I'm gonna pick a set of integer numbers equals you know hash set and then for each number in the array I will insert it into the set and then I'm going to iterate from 1 to the length of the array so and if I see that there's any number so I is the number to test and if not if I is not in numbers then we already found the first missing positive so we just return I otherwise we return now I'm still and plus 1 so this is the worst case when everything from 1 to 5 is in the array and then at the end we'll just return 6 because it knows that everything from 1 to the length was found in array in the erase that means every single slot was taken by a positive number there were no negative numbers or they were no numbers greater than 5 so given that we did not find any positive numbers from 1 to N in this loop then at the end we're sure that ok now so that length this one is definitely not in the array because every single spot was occupied by a positive number so the next positive number is definitely the smallest one that's not in the array which would be like 6 so let's try running this code make sure it compiles yep it compiles and let's submit it yep so it's accepted thank you for watching
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
64 |
sound test hello everybody I'm Erica and this will be problem minimum puffs some likely it will be in a graph or a greet given the rectangular grid filled with non-negative numbers grid filled with non-negative numbers grid filled with non-negative numbers find the path from top left about the right which minimizes the sum of numbers you can only move down or right this is extremely standard deeply problem and for that I recommend is it possible that this is empty I guess not I used to only recommend my deep eat fried EP lectures get up you can water them for free they teach about iterative DP which is a very nice way to write DP because it's very easy to compute the complexity and what else want it fast the running time is always fast for every cell here it's very often it's very common that if you need to find something some best path or a number of ways to get somewhere it's good to compute that for every object every vertex of a graph or here every cell of a grid and this creates a DP because to know how to best get here I can think about my previous step DP of row column is value here plus maximum of what is the previous my previous step DP of Romans one cow come - whoa just Romans one cow come - whoa just Romans one cow come - whoa just sometimes I will go outside of the arrow here height and H is height W sweet I'm just here if Rho is zero then I'm interested in zero otherwise this is called ternary operator if coal is zero then zero otherwise that turncoat I will not say her much more about this what's wrong brackets the rock I think sometimes Ditka doesn't put an ending bracket it things that I'm trying to close something I opened your also twelve expected this minimizes the Sun minimum then if this than zero but that's incorrect to say that I could like jump from outside of the grid instead I will say that here I take infinity here it's again infinity infinities said this I hope that I will not overflow if numbers in the input if the answer can be bigger than billion then I will get wrong answer your answer is this also if Rho is 0 and column 0 is grid of local this became not that trivial but still isn't that bad submit ruger surmised might mean numbers Arabic and here I didn't use int max the maximum possible value and int because that other two if this would overflow in max you cannot add it with anything on the other hand this was minimum of one and the other at least one of those will not be infinity so okay and then I think I could also use this submit int max is like absolute infinity in C++ but if you like absolute infinity in C++ but if you like absolute infinity in C++ but if you say in a is B plus int max this right part overflows yeah that's it for today short for five-minute video see you short for five-minute video see you short for five-minute video see you tomorrow in hopefully harder problem bye
|
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
|
961 |
let's go over question number 961 and repeat the element in size 2n array now the question says in an array a of size 2n there are n plus 1 unique elements so we have n plus 1 number of unique elements and exactly one of these elements is repeated n times return the element repeated end time so what we want to do is you want to return the number that was repeated n times now it says that we have an array a so these are our arrays of size 2 n so it's 2 n for all of them and for all of our arrays n is going to be for the first one this is going to be 2 because this has a size of 4. this has a size of 6 and this has a size of eight so our n is two for the first one because two times two is four three for the second one because that's six and then four for the third one that gives us eight now it says that we have unique elements that's n plus one if you were to add two to one that would be three right so that means that we're going to have three unique elements and if you look in our array we have one two and three unique elements so it's one two and three if you were to look at our example two we should have three plus one so that's four unique elements so we have one two three and five so one two three and five and finally for our third example we are going to have one two three four and five and that makes sense right because two plus one is three plus one is equal to four and four plus one is equal to five and as you can see we have five unique elements four here and three here the question also says that exactly one of these element is repeated n times so this is a key to solving our solution so what's our n for the first one is two for the second one is three for the third example it's four and if you look in into our array we have one element that's repeated two times n times this is our n and that's three and if you look at our example two we have to have an element that's repeated three times and that's two we have one two and three and same goes for our example three we should have one element that's repeated n times which is five one two three four so it's repeated four times so we have to look for the number that's repeated and just return that repeated element as our result to solve this problem what we want to do is we probably want to get a some kind of object to store the count of the keys right and for the first one we would have a key of one two and three and it would have a value of one for the first one for the second one and two for the third one because three has counts of two and everything else has one and we want to return this as our result but there is one thing to keep in mind well you should note that other elements are going to have a value of one because they're going to be all unique except for that one value so think about how you can maybe minimize the number of operations so instead of getting count of all the elements in our array maybe we can stop when we notice that we have more than one value for one of the keys so that's the way to optimize things so optimize you want to return early when number of the same key is greater than one so give it a go try to solve it yourself it doesn't have to be best solution and what matters is that you try if you guys find this helpful make sure you guys like and subscribe thanks now let's go over our first solution and like i said before our first solution isn't actually going to be the most optimal solution but i think this illustrates the problem really well so we will start with this one and as you can see our runtime and memory usage is actually really bad so faster than 13 less than 5 percent time is space wise it's not very good but the solution is going to have a time complexity and space complexity of o of n now the first thing i want to do is i want to create a variable and i'm going to name it counts and set this equal to an object so here we're gonna store our key value pairs where key represents the elements in our array and value is going to represent the count of the elements so one is going to have a value of one two is going to have a value of one and three is going to have a value of two because we have two threes next i want to declare another variable and i'm going to call this max count and set this equal to number and negative infinity so for this variable what we're going to do is we're just going to store the maximum count to this variable later and next i want to declare another variable and name it result and just declare it over here and obviously here we're going to store our result and let's just actually return our result here that's what we need to do later okay all right that looks good now our first step is to get the count of all the elements in our array so to do that we're going to use let's just use a for of loop so const is going to be key of our array and we check if count key does not exist in our object what are we going to do we're going to initialize it with a value of zero and if it does exist we are going to increment counts at key by one each time so let's just console.log our accounts object console.log our accounts object console.log our accounts object and you can see that we have our result we have key of one and it only has one value in the array key of two only has one count three has counts of two and that coincides with our input array and rest is for input two and input three okay so we know that our accounts looks good it just simply gets the keys and the input array and counts all the numbers up so this is always doing for now what we need to do is we need to go through our counts object and be able to access the counts and the key and we need to store our result in the result variable and maximum count and the maximum counts variable so let's just make a for overlook again so const and i'm going to destructure my array so i'm going to have a key and i'm going to call it count because it's count of numbers of what i'm going to do is object dot entries and pass in my account object okay if this confuses you what it does is let me just console.log to show you is let me just console.log to show you is let me just console.log to show you so i console.logged object entries.count so i console.logged object entries.count so i console.logged object entries.count and you can see that what it returns is an array of array but in the array it has my key value pairs so key is 1 and we had a value of 1 which is count we had key of 2 and we have a value of one we have key of three and value of two so it's going to give us these arrays and what we do here is we use array destructuring to represent key for the first one count for the second one and so on and so forth so if you're not familiar with already structuring or object entries that's all it's doing it's just printing all the values in our object into array of arrays and we are using array destructuring to access those values and the first one is going to be represented by key second one represented by count now what we need to do is we need to get the maximum count of the number so what we do is the current count greater than our max count if it is a case that our current count is greater than our max count we want to overwrite that max count with our current one because we're looking for the number that happens or occurs the most we overwrite that with count and then we want to store our result which is going to be represented by the key and this should be count not counts and as you can see we have our results so for the first one three occurred the most for the second one it was two and four our last one five occurred the most now let's just go over our code just one more time here again we're just simply getting all the count of the elements in our array and we are storing it in our accounts object next is the harder part of this solution object entries passing in our counts object returns an array of arrays where we get our key value pairs and we use array destructuring to get key for the first one and count for the second one and then we use our f statement to check well is our current count greater than whatever we stored for our max count and if it is we're gonna overwrite our max count with the current count and store our key to the result variable and when we're done itering through the whole thing we just return our result and we get our result so for this one again time is open space is oven but although time is all then we have two loops here right and that's a lot of work and that's why we are getting such a slow run time so let's try to optimize our code little by little now let's go over our second solution and while i was looking at this one i thought maybe i can use something similar to counting sort and if you don't know what counting sword is what counting sort does is it counts all the frequencies of the numbers and it source that frequency into the index of the element so what i mean by that is for the first input we will have something like zero one and two so where did this come from well we have one count of frequency of one of the number one right so our one will be stored at index one that's what represents the number and frequency will be stored as a value so our index represents the number the values in that index represents the count and we have one count or frequency one of two right so we would have one here at index two because our number is represented by the index itself so two has a count of one and now three has a count of two right so we go to index three and store two as our value so that's what counting sort is now if you notice our space complexity is actually worse it's o of n plus k and where does of k come from well i'll actually explain this later when we code i think that might be easier to see now for this solution what i'm going to do is i'm going to create a variable named counts and this is obviously going to store our count of the numbers but actually before that i want to find the maximum value in my array so i'm going to call it max value is equal to math dot max spread operator and pass all our elements okay that looks good and next what i want to do is make an array i want to use an array.from keep a array i want to use an array.from keep a array i want to use an array.from keep a length of max plus one and fill this up with zeros okay and this is and this should be max value okay that looks good so let's just constantly log our accounts array as you can see we just initialize our counts array with zeros that's all we did and we have to add one because if you were to get rid of one you had only three elements but we need to account for index of zero so that's the reason why we have to add one now what we need to do is we need to put our frequencies into the correct index let's just use four each for this one for each current value what we're going to do is accounts at index current value because our current values are going to be represented by the current index and we increment by one each time so as you can see we have frequency of zero for the element zero one for our element two count of two for our threes so it looks good right so let me just delete that and what we need to do now is we need to find the maximum count and let's just call that max count and for this one we are going to use math.max again and let's just spread all math.max again and let's just spread all math.max again and let's just spread all the elements from the count and if i were to console log this you should have two three and four because our maximum count for the first input is three which had a count of two count of three for the number two here and count the four for number five okay that looks good now all we're going to do is we're just going to return counts dot index of the max count okay we did get our result but let's just go over this so what we did was after finding our maximum count number what we did is we went to our count array and looked for that maximum count and returned the index of that number and remember i said that the index represents the number itself and a counting sort so that's why this whole thing worked now let's just go over why space complexity is of n plus k and let's just cancel out our accounts just one more time i'll console log it here well if you look for now we don't have any big gaps in our number so let's look at our input goes from one to three and one to five for our third one too but what if it was the case that we had a number that's really huge in our array so something like 20 and you can see that when we had an input of 20 we have our array counts array and it's all filled up with extra zeros that's really unnecessary you can see that for these extra zeros that we actually didn't use that represents the of k space complexity and that's where it comes from so o n is our number of inputs and of k is that extra space that we have to make for elements that's not in our array okay that explains our space complexity and let's just go over our code one last time so first thing we did was find the maximum value we use that so that we can create our counts array and we add one to our length because we need to account for zero and we initialize it with the number zero here we got the counts of all of our elements and stored it into our counts array and remember that the values in the array represents the count and the index represents the number next we created a max count variable to get the maximum count of our element and we use that element to find the index of that number and this works because index of the count array represents the element itself so this is pretty much kind of how counting swords work if you're interested in how counting sort work make sure to watch the counting sort video that i made i think it should be really helpful so this is another interesting solution but there is definitely a way we can optimize this first of all space is of n plus k which is really bad and this is still oven but there is a little optimization that we can do to maybe do it quicker on average now let's go over our final solution and this is going to have the best runtime so 96 faster and the logic is that if you remember from the problem all the numbers are going to be unique except one so that means that in our accounts object everything is going to have a value or count of one except one number and we can optimize this by saying well if the current element happened to be already in my accounts object well i know that i can stop because that's going to increase my count to 2 and there is no reason to keep looping through the rest of the array wasting our time because no matter how many times we look through the array we already found the answer already because again all the elements are going to have a count of one except one number so let me find that non-unique number we just want find that non-unique number we just want find that non-unique number we just want to stop and return that number and just end the whole thing so let's try implementing that solution so first thing i'm going to do is i'm going to make a variable name count and set this equal to an empty object and i want to iterate through my array so let's just use for of loop and let's call it key of a and our key are going to be the values right and i'll just call the key because it's going to be key value pairs in our object let's delete that so i need to check if counts at key exist i'll just want to stop and return that key and this works because if the key already exists in my object it means that at least is going to have a value of 1. and if that's the case you just want to return that key and just stop our loop next i need to check if my key does not exist in my object so if it doesn't i want to initialize it with a value of zero next i want to increment the value by one okay we do have our result and this is probably the shortest quote for all the three solutions that we had but let's just console log our counts over here and let's just look at our last one so what happened was when our input was five so our key is five well does our key exist in our counts object no right so this is false and we hit this statement well does it exist in our object well no so this evaluates true that's the key value paired to five and zero and we increment our value by one so we have five one next is one well does one exist in our accounts object no so we initialize it with zero and increment by one so we have one and one here next is 5 so 5 is a non-unique element next is 5 so 5 is a non-unique element next is 5 so 5 is a non-unique element so we go to our loop hit our first statement well does the key 5 exist in our object well it does right we have a value of 1 already or count of 1 already so what we do is we immediately return that key and just stop looping because we know that there is no reason to keep looping because no matter what we do all the elements are going to have a value of 1 except the number five so we stop there and just return our key and we are done so this way we are able to find the duplicate without looping the whole thing because we just stop when we find the duplicate immediately so this does actually have a time complexity of all event because worst case it might be the last two elements like this one that's going to be the non-unique element but going to be the non-unique element but going to be the non-unique element but usually on average it might be faster depending on the input that we are given if you guys find this helpful make sure you guys like and subscribe thanks
|
N-Repeated Element in Size 2N Array
|
long-pressed-name
|
You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times.
| null |
Two Pointers,String
|
Easy
| null |
159 |
hello and welcome today we're doing a question from lee code called longest substring with at most two distinct characters it's a medium let's get started given a string s find the length of the longest substring t that contains at most two distinct characters example one given the input e c e v a we output three because e c e has a length of three and at most two distinct characters e and c example two we are given this input of two c's two a's and three b's we output five because a b is our longest substring with at most two distinct characters okay so before we start let's look at another example this is similar to input one with just a few more characters added to it let's think about how we would approach it before we even try coding this up well we know that we are trying to find the longest substring so we want to go as far to the left and right as possible we want to start at the beginning and see if we can cover the entire substring so what we can do for that is start our substring at index 0 and also start our end at zero we can just keep incrementing until we reach the end and adjust start and end pointers as needed so over here we've just seen e and we have a substring of length one with at most one distinct character we can increment e or like the end now um to see how far to the right we can go from this starting point at zero so over here we've seen two distinct characters we have a length of two we are at index zero and one for start and end respectively we increment again ece still just two increments again now we have a length of four with still just two distinct characters now once we increment end one more time now we go from index zero to one two three four so we have a length of five and we've seen three distinct characters in our current substring from start to end which we don't want so now that we've moved right all the way how do we move our left pointer or start to as far as possible so we want start to remain as far left as possible we've moved our right and one as far to the right and you know how are we going to make sure that our current substring only has two distinct characters well from here just where the end is we just have to character um b if we move one to the left well now we see e and b which is good we've only seen two we move another to the left and we've only still seen two once we move one further back well now we've seen it three at c so what we're going to do is exclude c and simply move right after that occurrence so the last occurrence of c move right after that so we don't include c or anything before that in our substring and this way in our current substring we don't include any other characters besides e and b so we increment end again and our current substring from start to end has two e's two b's so we're good and again now we have two e's two b's and an a how do we move start now well now we want to move it again past the last occurrence of our least recently used character so what do i mean by that a is our last um endpoint character at our last part of the substring so now as we move left we see bna which is okay we move further back and we see two b's and one a still two distinct characters once we move back further well now we see our third character which we don't want so we're going to move our starting point one after the last occurrence of this third character and any time in our dictionary we would only be storing a max of three characters and the one we get rid of is the one with the minimum index so in this case e and keep the other two because there are the ones that can form the substring so to make this a little bit clearer let's add a few more um letters in here and try to go through this again before going into the code we have our start index at zero and our max ln also zero we're going to need a dictionary to be able to store the characters and what indices we see them on so the key values will be characters the values will be the indices we see them on and at our current substring we are at zero so our length is one and the formula for this would be end minus start plus one so it is end inclusive this is why it's zero minus zero plus one we currently have a length of one and we see character e at index zero we increment n by one so we are at ec we see c at one length is two increments and again now the last instance of e is at two and this is our substring so length three we increment and again we are at three we see e there length is four so we are over here the increments end one more time we have e c e b so we see b at four what do we get rid of well out of all of these values the smallest one is c that means right after c we never see another c again and we would only have these two distinct characters so our starting point should be right after the last occurrence of this c so start now becomes two that means start is at this e right here so 0 1 2 this e right here and we go up until this speed so it's e b and we are at a length of 3. so we go from two to four and now we can actually get rid of this c because it's not useful to us these are the two characters that we are working with e and b we increment and again to five it's again another b increments and again two six another b six um let's see zero one two three four five six okay so we are over here and we have a length of five we increment end again and this time we see a so again we have three characters which one do we get rid of the minimum value is what e has so start now moves to right after that is value so start is four and we can get rid of e that means we are at this substring right here from the b up until that first a and we have a length of four we increment and again we are at eight and we see a at eight and again we only have two characters in our dictionary right now so we are good this also has a length of five so no need to update maxlend and now we've iterated through and is at the very last part of our string we return whatever is in maxlen let's go ahead and code all of this up we can actually keep um what we'd written so zero initialize everything to zero get rid of this and write the code so while and is less than len of s until end reaches that last part of the string we add it to our dictionary the character end is at so s of n and what index we've seen that character we've seen it at end now we want to make a check if our current dictionary has more than two characters in which case we need to delete one so if len of d greater than two we get rid of something which one do we get rid of well which is the minimum index right now out of all of the characters what index is that so let's zoom them in of d dot values and this is going to give us the smallest of all the values in our dictionary so we have key and values out of all of the values which one is the smallest and remember in our dictionary we stored the character and the corresponding index as our key and then value so whatever this index is start is going to be one right after that and we want to delete the character of that index so we delete from d s of main index every time we want to update max len so it equals the max of maxilla n and n minus start plus one and we increment end by one at the very end all we have to do is return max blend let us run this code accepted and submit wrong answer abc output 3 expected 2. let's see here we have start zero and zero maximum zero start should be um minimum of index plus one we want to go after that first one and it is accepted so talking about space and time complexity for our space since we only ever store two values if we store that third one we always delete it so there is a cap on the number of values we are storing in our dictionary it has nothing to do with our input or the length of it we can say our space is constant o of one and for our time we iterate through the entire string s one time so that is a linear scan o of n and that is for space of one time o of n if you have any questions at all let me know down below otherwise i'll see you next time
|
Longest Substring with At Most Two Distinct Characters
|
longest-substring-with-at-most-two-distinct-characters
|
Given a string `s`, return _the length of the longest_ _substring_ _that contains at most **two distinct characters**_.
**Example 1:**
**Input:** s = "eceba "
**Output:** 3
**Explanation:** The substring is "ece " which its length is 3.
**Example 2:**
**Input:** s = "ccaabbb "
**Output:** 5
**Explanation:** The substring is "aabbb " which its length is 5.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
3,239,340,1034
|
1,761 |
hello welcome back today let's try to solve another lead code problem 1761 minimum degree of our connected Trail in a graph so this drill means a triangle which are conducted so the trail just means a triangle so we just need to return the minimum degree of a connected tree in a graph or -1 if the graph has no in a graph or -1 if the graph has no in a graph or -1 if the graph has no connected views yeah so in this example one two three so they are it is a connected field and we need to return the minimum degree of a connected view so the minimum degree is 3 because 1 and 4 2 and 5 3 and 6 they are connected so the minimum is three because here it is a sad the degree of a connected tree is the number of edges where one add point is in the field and the other is not for example this 2 and 5 2 is inside the triangle and five is not so it is a so yeah it is our degree so we're gonna plus one and here for this is three and six three is inside the trio six is not and this four is outside of the trail one is inside of the trail so in total there are three degrees so we're gonna just deter a three and for this example let's try to set this one four and three so this is a true button there's no other ends outside the trail so it's gonna be zero so zero is the minimum we're gonna return a zero if we cannot find the triangles like this we just need to return a minus one yeah because we need to return minus one if first graph has no conducted truth so for this problem we need to check the values of the earn and means how many vertices so the vertices is 400. yeah can we try to solve it in O in cubic it means 400 times 100 it is less than 10 to the power of 8 yeah without need to attack if it can pass normally for lead code it can pass otherwise maybe we may try to use other method yeah so 400 to the power of three equals to 6.4 6.4 6.4 times 10 to the power of seven yeah so it is no it is less than 10 to the power of eight it means normally this can pass for The Brute Force so for Brute Force we're gonna prepare a distancing Matrix so for the adjacency Matrix inside the adjacency Matrix so A4 T this C is a graph it's 3 i t equals to one admission it is connected yes let me initialize the adjacency Matrix first so from the beginning it's going to be 0 times L for IE ruins so inside of the adjacency Matrix so let me yeah prepare an example so if it is like y or one zero and let's prepare another one Maybe zero one so this means the inside of The Matrix this is one and one means it is a yeah it is the vertices zero connected with itself this is a vertices one connected it Flex itself it means it is not connected yes so if this is a one as you can see this is one it means vertices zero connected with vertices one so for vertices one also connected with vertices zero so this is the meaning of the adjacency Matrix so inside of the Matrix if it is one it means for I and it would say they are connected yes if we can find three points always be one inside the adjacency Matrix so we can get the conclusion that this three points can become a true yes so for example if I prepare the adjuster example prepare more points if one two three they are connected yeah so here gonna be one yeah and inside here gonna be one and here going to be one so if we can find three vertices inside the adjacency Matrix always be one it means this is three vertices are connected so it means we followed true what we need to return we just need to return the maximum the sum of the degrees for example the sum of this one the degree of this one is three but number two for the vertex 2 it is 3 for voltage three it is also three so the sum of them is nine needs two minus the six because for our Trail for itself it is going to be a six because two and three and two one and two and one two three two one yeah because the graph is undirected when we are preparing for the graph we will prepare for edges two three and three to two so this is why we can get the result by The Brute Force now let me prepare but we need also to prepare our declare way so the degree is our array degree is already inside it will be zero times n now we are going to attack one by one accumulate all those degrees if we are giving edges so we are we can use the answers to get the result of the adjacency Matrix and the degrees for each of the vertices yeah now we can start to Loop through the axis for U Bay in edges now because our vertices are starting from one but either for calculus to make it easier we can use U minus 1 and V minus 1 because the vertices here always more than equal to one It Started from one so basically for our calculation for the degrees we're going to start from zero and also for the graph basically we're going to start from zero further calculation because that is easier so u and v should equal to U minus 1 and V minus one so we are starting from zero now we first needed to Tech Harbor where this put the connected edges into the assistance in Matrix and the degrees Yeah so for the adjacency Matrix let me put it yeah let me delete this errors to make it easy for coding so for the assistance in Matrix so for the T U V should be equal to C the U and this would equal to 1 because they are conducted the edges always be connected now we just need to put it inside the degrees for the degree U so the plus equal one and degree base would also plus equal to one yeah so for this one we prepared The adjacency Matrix and the degrees for each of the vertices after that we first need to use the Brute Force to get the result because we need to calculate the minimum value so for the result I will Define a infinite because after that I will accept the minimum value we can first use brute force to look through all of them for adding rings and is the number of vertices so for J in range I plus 1 to n yeah so for here for this it say it will not start from zero otherwise there's a lot of a duplicate because for one two one three four we just need to calculate once one three four we don't need to calculate one three four three one four one three so in total there are six so it means if yeah from my previous calculation yeah if 6.4 6.4 6.4 times the tenth to the power of 7 and times R6 is going to be time limit exceeded as later on we're gonna try to attack if it is a time limit exceeded when we are not using the I plus one or not yeah now let's just prepare the code for the next vertices so for K in Ruins 3 plus 1 to n now we can first attack so the condition is f see I see and see i k it means I and K are connected and see this means I say connected it connected so that data should also be connected so the say and the K connected yeah if they are always be equal to one it means it becomes a triangle it becomes a trio now we can solve the depth the result should be the minimum because we need to calculate the minimum of the result with so if it'll always be one it means this the sum of them will be at least six so we need to use some of them it is the degree I Plus and plus degree k yeah let me make it longer yeah and here need to minus A6 because this number is more than equal to 6 so it will be more than equal to zero if we have the result otherwise the result will be the infinite so we can first return result if without not equal to if the result equal to if we're going to return a minus one it means we didn't buy it because here said if we didn't find we're going to return a minus one now let me run into that if it works so yeah else here we need else minus one yeah we'll return uh a full result not equal to infinite otherwise we're gonna return uh minus one let me yeah let me pre print out the degrees for set if there's something wrong yeah so for the degree it is a 333 and to this graph it is right and for other point it is the four five and six it is one it means it is a right Parable result is not right let me sucks the suck the result yeah let me print out the degree just to check if the degree inside is right or not I think I don't need to test the code anymore basically it's just a Brute Force yeah a lot of 311 yeah it means we got a three one it is not right we should not print out the one so here is this attack yeah here there's a typo so this is c u v and here should be the U yeah it's just a typo definitely have you got all wrong without no let's suck yeah now it seems okay yeah but before submitting let me delete the print otherwise it's gonna influence the speed and memory yeah now let me submit it to that if it works yeah and by the way the time complexity is in cubic yeah because this is just a Brute Force as you can see it works and it is like three seconds now I'm going to try yeah to use the ICT starting from the zero point first yeah have a double check if it works or time Limited yes now let me just to run again to talk if it works yeah if we times this is six it means it will be time limited yeah for this code I don't believe it can pass for 10 to the power of 8. no yes now let's start to try to check if it is a Time limited or not here as you can see it might be a time limit exceeded yeah because normally if it times a 6 it's gonna be yeah it's going to be 10 to the power of 8. if it is a to the scale of 10 to the power of 8 at least for this code it cannot pass if it is less than that it's going to pass I think this is also designed yeah for the lead code to let you to avoid the duplicate even you use a Brute Force you need to avoid the duplicate of each point now let me submit it again to attack if it works yeah as you can see it works first yeah the same time three seconds thank you for watching if you think this is helpful please like And subscribe I will prepare more lead for the problem like this see you next time
|
Minimum Degree of a Connected Trio in a Graph
|
count-sorted-vowel-strings
|
You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pair of them.
The **degree of a connected trio** is the number of edges where one endpoint is in the trio, and the other is not.
Return _the **minimum** degree of a connected trio in the graph, or_ `-1` _if the graph has no connected trios._
**Example 1:**
**Input:** n = 6, edges = \[\[1,2\],\[1,3\],\[3,2\],\[4,1\],\[5,2\],\[3,6\]\]
**Output:** 3
**Explanation:** There is exactly one trio, which is \[1,2,3\]. The edges that form its degree are bolded in the figure above.
**Example 2:**
**Input:** n = 7, edges = \[\[1,3\],\[4,1\],\[4,3\],\[2,5\],\[5,6\],\[6,7\],\[7,5\],\[2,6\]\]
**Output:** 0
**Explanation:** There are exactly three trios:
1) \[1,4,3\] with degree 0.
2) \[2,5,6\] with degree 2.
3) \[5,6,7\] with degree 2.
**Constraints:**
* `2 <= n <= 400`
* `edges[i].length == 2`
* `1 <= edges.length <= n * (n-1) / 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* There are no repeated edges.
|
For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c).
|
Dynamic Programming
|
Medium
| null |
26 |
in this video we'll go over lead code question number 26 remove duplicates from a sorted array given an integer array nums that is sorted in increasing order we need to remove all duplicate elements in place but there's a Twist instead of actually removing the elements we can just modify it so let's say there are K unique elements in the array then all we need to do is make the first K elements the unique elements in sorted order and the rest doesn't matter then we return K the number of unique elements in the array for example if this is the array we can see that there are only four unique elements 5 6 7 and 8 and the rest are duplicates so all we need to do is change the first four elements of the array to be five six seven and eight and return four the total number of unique elements now you may be wondering why would we do something like this when we could just use the pop method that's built into python lists we could just Traverse the list compare each element to the one before it and just pop duplicates until we reach the end now this actually works but the problem is that the pop method is very inefficient because once we pop an element we now have to shift all the other elements one space backwards each shift runs in O of end time and in the worst case you'd have to do n minus 1 shifts so this would run in O of n Square time so instead we'll use an O of n algorithm with two pointers and just overwrite the first K elements of the list instead let's look at the code and see how we can do this first we'll create an index variable called replace which will keep track of which element we need to replace in the array the first element by itself is already unique so we can start this at index 1. then we'll enter a loop that will again start at index 1 using the variable I this variable will Traverse through the entire list and find duplicates now since we know that the list is already sorted to find duplicates all we need to do is compare each element to the one before it if they're different then we found a unique element and if they're the same then it's a duplicate so let's enter the loop and compare the ith element to the one before it at I minus 1. 5 is equal to 5 so we found a duplicate that makes this if condition false so we actually don't need to do anything and we just go on to the next iteration basically we keep searching ahead until we find a unique element next We compare five with six and we see that they're different now we enter the if block and we'll overwrite the element at the replace index with the unique element that we just found then we'll increment the replace index so that it's ready to overwrite the next slot and we move on now we compare 6 and 7 and again they're different so we overwrite the duplicate 6 with 7. increment replace and move on next 7 is equal to seven so we just keep going finally seven and eight are different so we'll write the unique value of eight at the replace index and increment replace at this point we're done with a loop so all we need to do is return the total number of unique elements but instead of going back and Counting the unique elements we can just return the value of replace since it's been keeping track of the position of the last unique element that was written now you might say isn't it actually one index past the last unique element and you're right but since indices start at zero this actually ends up being the correct number of unique elements so here replace equals four so we'd return four and as you can see there are in fact four unique elements that now take up the first four spots in the array
|
Remove Duplicates from Sorted Array
|
remove-duplicates-from-sorted-array
|
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`.
Consider the number of unique elements of `nums` be `k`, to get accepted, you need to do the following things:
* Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. The remaining elements of `nums` are not important as well as the size of `nums`.
* Return `k`.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:** 2, nums = \[1,2,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,2,2,3,3,4\]
**Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-100 <= nums[i] <= 100`
* `nums` is sorted in **non-decreasing** order.
|
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
|
Array,Two Pointers
|
Easy
|
27,80
|
1,041 |
That further this volume to coding decoding rohit singh bobonga dental clinic and 150 grams daily the robot boy suit on and heard your ₹10 exit available and heard your ₹10 exit available and heard your ₹10 exit available average selling mini this vitamin e hu is the robot is for me so e can any person wash the year Take And South Indian School Certificate Incidentally A Person Post Temple At 110 Quickly Double LG G3 The Voted Up A Victim Dies In The Sanskrit Madhya Suggestion Setting On A Simple Keep Jamshed Gives It 150 Such Live All 2017 Login His field staff and cream on this, then put this difficult, logical, limited limit that Mangeshkar Gill Mist download deposit specific 's newly appointed smooth dance and finally here create 's newly appointed smooth dance and finally here create 's newly appointed smooth dance and finally here create account notification student commits suicide in witch can this cumin seeds fennel Bastar district president minutes will be to the train For instructions in love with oo a true love oo plain mode setting ke jeans give product means loot liya prediction for watching the robot boy ki mujhe bill pe karna hai [ ki mujhe bill pe karna hai [ ki mujhe bill pe karna hai ki baaki sab soha ulta problem subah promise this problem testing in this pic 200 Gr Take Off Sample Input Itne Me Kya And Doubts More Class 8 Hai Ki Are How To Electronics Store Electronics But Electronics And E Want Nothing Left Right Ok Welcome To Monitor Subscribe Must Drop Starting Point That Redmi 4 Cycle And United States In These Questions On Become Politics It Is It Mausam 021 Latest And Right But You Get Your Feet Times Idli Starting With A 's Seed Cancer And Municipal Commissioner Support It 's Seed Cancer And Municipal Commissioner Support It 's Seed Cancer And Municipal Commissioner Support It Drop Counts On Yesterday's Morning Breakfast Four Decades Ago In To-Do List To Avoid Traffic No That To-Do List To Avoid Traffic No That To-Do List To Avoid Traffic No That Sort Of A Fear The Robot Boy And Destruction A Tattoo In Abroad For Decoration International Travel Holidays Shop No Matter What The Ka Music Robot And Send A Is Encounter Bags The Road Far Pimps Degree Point Is This Point So A And Other Kitchen Hollywood Informed His old square account mode of world record never in any other circular leaves no room for inspection and active servi 200 then time traveling guddu buddhi suvvar the robot boy the movie has it and itne din rakhana ki aap and english of satire and solution text If you message then the British laugh 1919 that when the constitution letters O Kushwaha in the forest and different directions are there are o a little directions that a link on the mobile of song0 - that a link on the mobile of song0 - that a link on the mobile of song0 - 0 also stops - one also stops - one also stops - one is - 1310 and directions is - 1310 and directions is - 1310 and directions this year fourth travels robbers Robbers 9 Tags Page 10 North East and West Indies and Dual Air Chief Introduction Productions Hai Inverter 2012 30 Se Yaar Cleanliness Robot in T-20 Hai Inverter 2012 30 Se Yaar Cleanliness Robot in T-20 Hai Inverter 2012 30 Se Yaar Cleanliness Robot in T-20 and Tri-Nation One Day On this they want to be and Tri-Nation One Day On this they want to be and Tri-Nation One Day On this they want to be possible to and so and this point to 1 Minute yr solid liquid and take directions to chief minister in celebrities 920 820 mode turn on in examination present with blending and so yes or no that positive se add isi IEA Sports Times did not to determine weather cycle Or not 200 run writing mobile look to attract over the given instructions to four times the issue will be successful coordinator for the robot setting 202 alook who is the instruction back side effect at a positive is g date mutual you for more words in the direction Of Previous Song Export Garment The Urges On Because Of Director Of 10 2017 Dare Subscribe 10 It's Placement In Obscene Trace Of Because Of Direction Where One Guy Displacement Vibration Him Access Point Fluid It Feels Like 102 Free Officer Distraction Have Cleared 0f Means Only Front To Reference One Can Avoid Are You Can Practice Worn In For Directions To Reserve One Will Give A Clear Extra Rush Of Active Vrat Effective 12180 Subjective Will Give Detailed Android Reason Is Yes Reason Direction Minus One Existing Square Android And Record Previous Video People To and e will be treated as a plus minus one morning you are objective for details in human language a sit - loot and a sit - loot and a sit - loot and e will be treated for the computer labs Mr. Raghubir Result is set I am in Surat do the exam Due to have direction with sexual in law courts and they are always with oo do n't have seen that this 16304 is priceless the united states for science very cartage robbers that vijendra transfer rule and that's why answer only for all present on do Hai high flam tax player a fence support masking ay av us aa kar do ka vikas - 153 test loot off aur hai - 20 - from schedule 4282 hai - 20 - from schedule 4282 hai - 20 - from schedule 4282 ko mute get free ki siddharth gautam print dear she on the bed subject wise tapasya sub is line loss due Respect you want you can checkout interlock lead a pig in this training logical no hey man so let's move next reduce turn off 219 miles from eating meat puree gomez to ludhiana follow twitter from ludhiana on us the news of world records in this Year In Fighting 8450 Significance That Which Loot Site Rating Ones And How Valid Points While Doing This Points You Try 21000 Which Pizza Construction Will Always Remind Us That Director Of Loot Shares Are Going Upward Do That Subhash Ghai Pimple Loota Gyro Cycle Hai The motive your direction factory date change agree with that a feeling that makes sense sorry man down are not run on yes man fuel surcharge north indian literature display from this 212 that daily 272 language change to three that a finally a good throw solitaire was present I In this faq sample test is this prank or that this is our ready move one direction wedding night tomorrow morning politician dance class 10th are you should find different from the spinal cord pimple 2009 2013 that the world in this direction ko whatsapp gift and china will return direction were For Deposit That A Try Transit Of Paper And Adopting A Mathematical Group For Point Comment Section Bills On Twitter Also Like My Video You Like Share Like And Subscribe With This
|
Robot Bounded In Circle
|
available-captures-for-rook
|
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction** is the negative direction of the x-axis.
The robot can receive one of three instructions:
* `"G "`: go straight 1 unit.
* `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction).
* `"R "`: turn 90 degrees to the right (i.e., clockwise direction).
The robot performs the `instructions` given in order, and repeats them forever.
Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle.
**Example 1:**
**Input:** instructions = "GGLLGG "
**Output:** true
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"G ": move one step. Position: (0, 2). Direction: North.
"L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.
"L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.
"G ": move one step. Position: (0, 1). Direction: South.
"G ": move one step. Position: (0, 0). Direction: South.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).
Based on that, we return true.
**Example 2:**
**Input:** instructions = "GG "
**Output:** false
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"G ": move one step. Position: (0, 2). Direction: North.
Repeating the instructions, keeps advancing in the north direction and does not go into cycles.
Based on that, we return false.
**Example 3:**
**Input:** instructions = "GL "
**Output:** true
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.
"G ": move one step. Position: (-1, 1). Direction: West.
"L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.
"G ": move one step. Position: (-1, 0). Direction: South.
"L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.
"G ": move one step. Position: (0, 0). Direction: East.
"L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).
Based on that, we return true.
**Constraints:**
* `1 <= instructions.length <= 100`
* `instructions[i]` is `'G'`, `'L'` or, `'R'`.
| null |
Array,Matrix,Simulation
|
Easy
| null |
915 |
That Hello one my name is and today we are going to call a collection in the address model whose name is partition and your interest rate so what is the exact question and how to get it then we will click on it let's quit okay so Before calling this question, one special thing is asked of you that you will have to do two more questions. Okay, although solving this question does not depend on it, but if you clear that question and come back, then there will be a very good inside information that which of your two The question is that question is of Amazing Model only. Mixture to make are sorted part and to all friend. You see these two questions, you will develop a lot of it, so if you don't want to see then only you have to complete it, this year will be fine, it will give but this inside. There is a little bit, if seen, then put the right on a separate conference, so let's see what is the question, okay, so here you will get the right of an egg teacher, what do you have to do, hey, he has to participate, settle left this. Garlic every element of life is equal to every element of right and left to right both remedies will remain at and left should be near left is most close ok and you have to return do you have to return by partitioning the length of left no editor All you need to do is to land on the left partition. Okay, let's like this time on the board and let's do a test case and this quantum science on how to solve the lights. So be careful that I have hair. So let's be patient once. Ah, this is straightforward. Line comes 1 second day ok this is I have made one ray ok then one minute for Ajay to fold ok then he just needs this depth and I fill the limit in it came here and 20 here to 19 a free leg 1215 that came here 11:00 here that came here 11:00 here that came here 11:00 here a fat in right this I made a career right you look carefully everyone let's write its index once in this 0 4 5 6 7 Partition has to be done in such a way that which love Story element texture is smaller. Right smile murder can be equal. We of right toe element is in this that you can take the simple step from the party. If I draw a line here and I will talk about partition in it and support, this is the partition line. If this is a line from party, the spelling of A partition is not like this. If this is a line from party, then light is from party. If this is a line from party, then all the elements are here, this is 1234 856 and rapid, so all this is this entire set. That's the whole set of 18234 garlic that Ecuador can buy, that is 506 148, the rates of all these elements, all these limits are small, they will be equal, this year the elements are fine, so look at this with this tree, what can I say, I said that if you remember Do you have done the training technique ? The element here was ? The element here was ? The element here was said to be bad at maximum, it can be said to be tight at its maximum, what will I say to fold this thing, look at it was said to be at its maximum, I will say to everyone's maximum. How far will the rumor go? Okay, let's keep this aside, but what has happened is that remember the matter of partition is done, now I am channel technical, it is seen that it is the channel technique that people who are solid in it, we bring it to them, is n't it? Channel Technical What should I show, how far will the maximum impact go, what is the meaning of the maximum pack side effects, how far should it reach, it does this, as you see, I fold it, then take the tan to 10:00 then take the tan to 10:00 then take the tan to 10:00 In this generation, six, Wright tries to himself, this simple dream, you feel that he does n't tighten himself anywhere, ashes all this there and then brings himself back here, Wright and Trot, take care of yourself, trailer yourself Metrola Partition brings me here, so I take myself to this location, Fee Man takes myself to this location, 11:00, bring myself to this location, after all, it had 11:00, bring myself to this location, after all, it had 11:00, bring myself to this location, after all, it had become more cool, it is at this location, so here If I want to talk about the next part then I will not talk about the party. Now I want the left part to be looted and small S is possible, so I will talk about it from here. If I make a partition of so many elements, then neither are these all the elements nor all of this. The left part is what is on the right, the parts are a small, they are equal, why should I say equal then and here it is tango, here till the time, where till here, what is the problem, we have to do it right there, right to meet this. One person thought it was clear when we were not getting ads, make a left mic and from the left I will take the maximum, to what extent is the impact of which element on the right, like make an FMS and make a mean from the right, not where is the minimum from the right. Have to watch but carefully keep this channel on the technical side instead of Bandhan Mein Shayari, I come from the side of all the things. Yes, now look, I said that friend, you make a first right coming on flash light on to make this career. I have in which is lying in the minimum of right in a right comment it is good okay so on and from and feel which is right from mother brightness minimum which one is it is just that from any index ahead from some address Who is the minimum ahead? Okay, right min, look carefully. There is an infinity of people from here, let's change the color of this man. There is an infinity ahead of this. We here are the team, the minimum tennis, minimum, three minimum and three minimum. lol right minute now I solve left max fat left mehak left I am smart from here that in fact this one is difficult and for sms uh ok I this trend is very fun on technique and just send it on this very Everyone understands that the rate is maximum from here on the left side, from here, less extend this amount, extend till here, we extend till here, toll here, five here, 30 here and bring to front now carefully. See I have made up my mind about left right and max of left now I will do traversal Raees I am doing traversal and how will I shift whether a party can be formed here or not so see what I have said that I have max on this index I am asking him if the end skimming is how much, see if I travel on the left max, right left match patrol and from the right I ask how much is the main ahead of me, then he says that I was ahead of you by a minute. Right here, the maxthon on the left side, the maximum value of the one here is add 0 and beyond that, the minimum Vaibhav Tripathi date, this is zero with it, no meaning of sacrifice customer, how is the breakup of this collection, it should be further like this. Okay, let's move ahead, I came here to this address, yes, one tab ahead of me, now how much is this, so three admits, these two can be added to one now, I came here, one end space here, less actor. Look at how much main is ahead of me, she was, then you can also put this together right, I came here, edit, came here, ahead of me, till here, collector, told me, ahead of me, like, mind, we are ahead of you, comment tab, dominant. This first point was found where I would be of celebration, once I write 11:00 here, another '00' would appear. If you write 11:00 here, another '00' would appear. If you write 11:00 here, another '00' would appear. If you take care of the correctness, then what was there here, hence 1111 eleventh rate and eleventh yes, now from here, what am I here? I will say, okay, the mixture on the left side is the same and the elements next to the left are the minimum maximum elements, till the maximum element is the maximum element, and the next parts are the minimum elements, that too is simpler than this. From here to Bigg Boss, from here to here, okay, so this one can, okay, I will do it, I have commented here, see this, now let me fold it, what would he be doing just to me, right to the mind, right to me The man will have to bill in a deep and left match so I can go while creating or like there is no need to offer, only treatment is needed, tight then it is okay once tap is fit, I have done some steps tight so first of all Mez ki main ke andare hai to feel hua hai the right mins right travels yeh kaun hai re ki and mainten main left max hara right from the situation hua hai the situation ki they were in this which point to put abe van aise raha hoon left macay In this Lansdowne right min turn off one Shapley ahead of left max on that is graduated in this simple means that partition encounter we have partition and axis encounter has happened. Okay, this work can be done in the space of those people and off phone also. There are so many rabbits, that's why we will have to see this combination a little, okay, we will discuss it in the next video, then give it a code word once, okay, I have smelled it, now keep in mind, what did we decide first of all, we will have to make one or the other. Right mince right mitti ghrita hoon maker right me hey ok step number to maintain main me left max and figure out the apartition the index right so maine banaye re in ka a right me do n't this and right me have a new scent of a I take out the glass that and a gain is equal to a good thought length right so you a b plus one can follow right and preserve the right man and then I do this write a brief note here right now right minutes of man quality to mere donga interior Daughter 's max 's max 's max value is ok yaad meri tera in it me ab main rahoon for and request to and minus one se lekar i great think 120 Android - - one se lekar i great think 120 Android - - one se lekar i great think 120 Android - - ok to aisa kumar right meaning of varied meaning of wife 12 maths daughter of capital af r now Tak min tak means right of I plus one plus wave now current element now here I told left nothing but A's rate is zero now I give ₹ 1 point rate is zero now I give ₹ 1 point rate is zero now I give ₹ 1 point IS equal to one to I lashes and I plus what did I say if It happened, look, I have made one, okay, I should start it from zero, what do you see, here I have made time in the left match and now I smoke whether the element next to this point is bigger than me or not, tight hand. One more thing is definitely offered, let's stay here for a while and do n't keep anything here right now, if there is anything here then it will be realized here with you, make the left match like this, Enfield has heard of doing like this in the left, neither is the identity arranged. Interior dot mean value hai rate will continue till now like this I left mexico 129 dot mix of till now less My left is max muller right meaning of i plus one is smaller than one element ahead of me so its simple meaning i selection is basically a partition and extract so i answer goes here vijay jain 10 and here i gave me answer is Equal to i and return kaya an answer plus one tight due to which or Tabu in the house would have burst here from the party ahead of the heroine, then how would I know that till here the method tab and beyond that there is a minimum set in which there is fatty acid, so it would have come in the answer. What does it do in the robot? By adding a platform to it, the line on the left side remains because if I have set it as an index or if I want to return the answer, then will I entertain? If I am happy from there, then let's run it once and keep it as a photo copy. Please start the deposit, it is coming from 5000, how are you coming, turn it on, okay, it is 205 as minimum, I have kept it right minute, you are right and I connect from here to me, I am bra left max and From verification, the one who is bigger than me is in melt match and if left maxis left nd right five plus one then the answer is good, it is absolutely right, you had to stop here, don't go beyond this, friend, as I have broken the record, it is right. It has just happened that if you move ahead then you will get the wrong compound. As soon as I break the chord with ease, it is okay, it is the fastest question, I submit it, but let's go, let's do Hanji, hit right, so look again once from this stage. Let's see if we first of all make up my mind that what is the meaning of any right till this point, which value is smallest from any index till right, then after that I am making the left match and what rice do you do? I want to say that the part here has the highest value till this point, the next one is the smallest in India, this is the reason why a partition should be made here, right, feel like this, add it is on every movement, where I am meeting you right there by hitting I in my answer and then I am turning on answer plus mode because I will have to return the index. Rate for length and time complexity in this. See the special part of time committee. I have done travel karma twice. If I travel once made in ride, once I travel making a left match complete left neck, then to front is rock but time will be able toe fan and space, I have grinded a tightening a is piece for the right minute, then page mode OK, so we have canceled the order and it has been submitted. Next question, we will fold it with the right waves. Now how will Vodafone be tight in this, so it is hoped that you will like the video along with the question and the video. Subscribe to the channel and give it a plus to get updates on the upcoming videos, till then you will get electronic updates.
|
Partition Array into Disjoint Intervals
|
generate-random-point-in-a-circle
|
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that:
* Every element in `left` is less than or equal to every element in `right`.
* `left` and `right` are non-empty.
* `left` has the smallest possible size.
Return _the length of_ `left` _after such a partitioning_.
Test cases are generated such that partitioning exists.
**Example 1:**
**Input:** nums = \[5,0,3,8,6\]
**Output:** 3
**Explanation:** left = \[5,0,3\], right = \[8,6\]
**Example 2:**
**Input:** nums = \[1,1,1,0,6,12\]
**Output:** 4
**Explanation:** left = \[1,1,1,0\], right = \[6,12\]
**Constraints:**
* `2 <= nums.length <= 105`
* `0 <= nums[i] <= 106`
* There is at least one valid answer for the given input.
| null |
Math,Geometry,Rejection Sampling,Randomized
|
Medium
|
914
|
230 |
hi everyone welcome back in this video we're going to solve liquco 230 which is the cave smallest element in a virus search tree so it's a medium problem it needs a parent search type problem so let's run out the prom We are given the root of a binary search tree in integer K we must return the cave smallest value of all the values of the nodes in the tree so basically let's look at example I think that will be much clearer so we'll have something like this example right here and then they will say well K is equal to let's say for this case one and so we have to return the kth smallest value so this would be the first smallest value which in this case would look at the values and say well we have one have two have three and a half four this smallest value of all these follow these four values that's one so we'll return one here we had let's say we had something else let's say we had k equals two for instance if k equals 2 then we'll look at the balance again and say well the second smallest value that's two so that's what we will return so that's the main idea um I would say it's pretty simple like the whole concept or the problem is okay so we're looking now at for example and so we have to take into consideration that this is a BSC so BSC stands for binary search three so essentially a virus search in case you don't know what that is simple it simply says that the values on the left like this one right here are always lower or smaller than the ones on the right okay so for instance here we have um one and two and which are one and two which are smaller than the values on the right which would be four and so that's one of the Key Properties behind the virus or tree and so initially you know the first solution if we didn't think about bsts at all what we could do is simply iterate in root force or white through so basically go here seed three then go to one go to two go to four and so basically Implement DFS for instance get all the values inside a tree put them in a list like you know one two three whatever like crazy this could be something like three one two and four and then we could sort it right you'll be sort it then we simply get the cave index or Decay defined as my index I guess it's the first that way we get the zero the two and so on and so forth so you know that's one way but the problem is that this has a high complexity because not only we're going through the entire um the entire list so this would be of n in this case but we're also sorting and sorting this kind of list this takes oh and Lock n and so this already is not ideal this is low we're not really using the properties behind environment search trees and so we want to think something better something that would work more efficiently and take into consideration the properties of biosurgery so as explained earlier we know that the bellies on the left are smaller than the value is on the right and so if we for instance if we only want the first or the smallest value the cave smallest element the first smallest element why would I go to the right it makes no sense right I mean because we're guaranteed that if there's an element on the left this element will be the solution so there's a way to Traverse the tree such as that we are always going for the most optimal path right because if we're looking for the first smallest element it does not make sense to try to go visit the right child of you because we know that this oh man does the child the right child will be greater or it will be higher than the value here therefore this is smaller therefore if I want to get the first smallest value it makes no sense to go to the right I want to go to the left instead right away right and so that's something quite important in and so I think like you start to see where I'm going here so basically what we could do is if we want to get the cave smallest element then we always want to prior to prioritize going to the left why because if we go to the left we were guaranteed that these values will be smaller therefore if we have a choice to do if we can either go right or left and we're going to get the smallest value then it makes sense to First go left because the wires on the left are smaller therefore what I could do is if I'm here so obviously this will always start right I will always start at the root element from here what I can do is be like okay I can go left then here from this one I can try to go left I will see if there's nothing here in since the root element in this subtree is smaller than the tiles on the right subtree then I can simply append this guy the one here so one solution or one kind of like guideline would be the first go left um append it exists if not then take the element take the root element because this little element will be smaller than the on the right sub tree so therefore it makes sense right and then the third step would be to take the right subtree so this is one approach right these are like the first like the three most important things here uh always go left if the left does not exist then we take the root otherwise we take the right and so right so this works okay but like we want to get the K if it's my spelling right how do we do this well what we could do is simply whenever we go left we append the valley to a list whenever we take the root we also depend to a list and so we take the cave element from our list are the cave time we had to add something because that would be the Decay the smallest value so that's kind of the approach here so in order to like see your original let's take this example for instance let's say here my K was let's say three in this case and so I'm just going to repeat the presses so I'm going to go here on the root element I'm going to first go left because this is what it says I'm going to go left I have my one here I'll go live I will see that I cannot go left because there's not left substrate here so I will take the row element and I'll simply we could either store in the list which would make sense but also I feel like there's a better way or we could simply use the k here like a I guess K counter and we never would take an element we simply by one right so what I could do is when we take the root element here this when we take this one right here because this is as I said there's not a lapse of tree when we take this approved element what I can do is increment this K counter by one so therefore uh we could do is simply do this then over K in this case or the cake Hunter would be one now and so obviously if cave was equal to one we could just stop here but since that's not the case we'll continue the algorithm and now we'll go to the third step right here which is the take right sub tree uh step and so basically we'll do this third step we will go here to let's do right here we will try to go left we will see there is not a left subtree for this D2 almond and so we'll simply take the root as we did before so just know this was in the first iteration here is the second iteration then we'll say well K counter plus equals one and so this will be now two and so we'll check okay is my cake Hunter the same as my K as the my input k no it's not so we have to continue going and so on the third step now as we said this is going to be implemented with recursion right and so that means that when we did all of this subtree we're processing the root element right there's three right here okay so we were at the first step now in Second Step since this is finished the Second Step would be to take the root element right so that's exactly what I'll do so I'll simply in my third step I'll take the root element so I'll just simply going like I kind of Buy one again and then this will be three and now my k is equal to my K counter therefore I can stop here I can already return this three because I can guarantee that this is these malice the cave or the third smallest value in our tree which appears to check out so yeah that's pretty much about the implementation this is how you would do it um hope this makes sense basically we always want to take the left because we now did left sub tree is smaller than the right sub tree and also we know that the right sub tree is greater than my root therefore it makes sense to do these three steps and so we can either do this recursively or with iterations I think the best way would be to use recursion in this case so let's look at the solution in Python all right so I hope you will just solve this in yarn and now let's take a look at the solution so first of all let me just rewrite that we always look at the live sub tree then we'll take the root element and then the rise up tree we did with a binary tree that means that the left subtree the values inside the laptop tree they will be smaller than the root and right helmets and then the same thing goes for the right element but in Reverse so for the right subtree it will be greater than the left and the root and then the roots here is in the middle so the left subtree is smaller than the root but the root is greater than the right sub tree so now that we've kind of established this let's take a look now at how we will solve this so first of all I'm going to have here a res list this will contain my K counter then the actual value that I'm gonna return we're using a list because um that way we don't have to declare Global and non-local variables and I Global and non-local variables and I Global and non-local variables and I feel like it makes the go a little bit nicer to look at so now I'm gonna declare here my PFS function so first of all it's going to contain node why because that's what I'll iterate through so we'll reverse we'll Traverse the tree using this node next I'm going to check if the node the left if it has a lesser tree right because if it does have a little tree then we want to explore it so I'm gonna just call that then now we're at the Second Step here right here and we want to see we want to get the element so I will simply increase my K counter by one so be something like this and then we'll check if raise of zero equals k okay well this because like we want to check the current K counter and so we're going to get the first or the second or the third smallest element so we always check if my K counter equals my input okay if it does then we know we can stop and so therefore I will save the current value to rest F1 and then we'll return lastly I want to take a look at the right subtree so I'm going to say or another right if it exists then I'm going to explore it all right to end I'm gonna just call my VFS on the root and I'm going to turn rest of one so just to make sure that we're on the same page first of all I'm going to take a look at the live sub tree because that's the smallest one then I'm gonna get these root elements so the middle I guess you could say and then the right substitute which will be greater so we have this in case um we want it okay that's very big and so therefore we'll need to obviously visit entire tree and go for the right substrate lastly I'm going to call DFS on the root and I'm going to return rights of fun and if we submit this we'll see that it beats six percent um but over to that the printing complexity for this one and the very worse is going to be a local fan since we are just iterating through the entire um DFS well they're entire turbine tree and for the space and complexity it's going to be constant time because at the end of the day sorry I mean constant space all right now as for the runtime complexity is going to be of n since we're gonna iterate through the entire tree and the worst case scenario in case we can like if we give a k it's very big then we'll have to iterate through the entire thing so therefore that means that our renting complexity will require going through every single node so that would be of N and lastly for this complexity well we can say it's constant because it has two elements and they're bounded so it will be of one in terms of space complexity so that's about it I hope you enjoy watching this video if it helps please leave a like you have the channel a lot and I hope to see you next one bye
|
Kth Smallest Element in a BST
|
kth-smallest-element-in-a-bst
|
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
**Example 1:**
**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`
* `0 <= Node.val <= 104`
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
|
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,671
|
56 |
hi everyone today we'll be talking about merge intervals that's problem number 56 on leak code and it's one of the questions from blind 75 so let's get straight into it given an array of intervals where the interval i which is the element has a start and the end merge all the overlapping intervals and return an array of non-overlapping return an array of non-overlapping return an array of non-overlapping intervals so let's break down this question what do we need to merge all overlapping intervals and we have to return the non-overlapping portion return the non-overlapping portion return the non-overlapping portion so breaking down this question we need to define what an overlapping interval is what does it mean to have an overlapping interval and in this case simply an overlapping interval is when you have a previous end which is greater than or equal to the current start so when we're doing this question we will be starting at index 1 and we'll always be looking back so is the previous end of this blue one 3 is greater than or equal to the current start yes it is and this is an overlapping interval and then what we would do is we would merge this into one interval and let's take a look at another the second example right here this 2 to 6 and 8 to 10 is the previous end so we would be at index two looking back is the previous end greater than or equal to the current start six is less than eight so there is no overlap and as you can see there isn't and when we're actually plotting these points what we're essentially doing is we're sorting all the intervals in this list of arrays in an ordered form from lowest to highest and we're actually sorting it with the starting index of each interval right 1 2 8 and 15. so we've defined what an overlapping interval is what do we need to merge it and how do we merge this interval well we would have to take the minimum value of the previous start and the current start so of the one and the two one is the minimum and that would become our start of the interval and we would take the maximum of the end of the previous end and the current end so three and six that would be six so our merged interval in this case would be one through six right and i'll give you i'll show later why we're taking the minimum and the maximum as opposed to just taking the start of the previous and the end of the current there is a scenario where perhaps this blue interval is from 1 to eight it overlaps the bottom interval completely and in that case we're going to have to take the minimum and the maximum values of the two intervals so i would uh initialize our result with the first element of our list so that's one and three and when we're looping through all the intervals we can start from index one so we're going to take two and six and we're going to compare that to our result the first element and like we said the previous end is greater than the current start and that would require us to merge right so is there an overlap yes there is we would merge it this new interval becomes one through six and now our index would move to um position two where we compare eight to ten to one and six and we can see that there is no overlap so we can just push that into our results and similar to the 15 through eight and this image shows why we need to take the minimum you can see that when there is a longer interval at our previous state then we can't just take say for example the start of the previous interval and the end of the current interval because that would give us one through six which is incorrect we need one through eight so we take the minimum of the two and the maximum of the two for the end now let's go into the coding okay so the first step that we would want to do is sort the intervals so let's go ahead and do that and we're looking at the first element which is just the starting right so we're sorting it based on that once we have sorted the intervals what we want to do is we can initialize our result with the first index right this is what we're going to be comparing it to and i'm going to write a utility function that shows us whether or not there is an overlap so let's just call this has overlap and it should take in two arguments right so we said the previous end and the current start and we can just simply return previous end is greater than or equal to current start which is just going to tell us whether or not this if there's an overlap that exists now let's iterate through the list of intervals starting at index one so we start at the next one and we need to be within our length and we're going to be incrementing it by one so as i mentioned earlier we're going to be comparing it to the last value that is in the result you have that there so let's just say const last value in result is going to be our result array and result dot length minus 1. that is going to give us our last value in result now as we iterate through this let's compare okay so um if our intervals i right and we're going to be using our utility function in here right so has overlap okay and if the previous value which is going to be last vowel in result if the previous values end and our intervals um a value and so intervals i one so we have actually filled in the previous end and the current start right there so if there is an overlap we need to merge and the way we merge it is by taking in so what we're going to mutate the this last vowel in result right so last vowel in result its new starting value is going to be the minimum of these two so let's do last val and result 0 and the intervals i zero right so the minimum of the starting and we want the new ending which is going to be the maximum of the two intervals i and one so this becomes the new merged interval right so if there's an overlap we merge it otherwise we're just going to push this interval into our result and at the end of the day we can return our result and it should give us what we need let me submit that wrong answer last value in result let's take a look at where this bug could be
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
350 |
all right welcome back to the study planned data structure in depth day three today we will have two related to two problems related with race the second one is already solved in my channel so i will just put this in this playlist and now i will solve this the first one the name of this question let's see intersection of two arrays given two integer arrays number one and nam so pressing an array of their intersection each elements in the results must appear as many times as it shows in both arrays and you might resume the results in any order so for the example one we have one two one and for number two we have two is appears in the numbers one so we return so the output is two for the example two we have nums one contains four lines five lamps two contains nine four nine eight and four so then the intersection between these two arrays is nine and four so the rigid is nine four or four line the path is accepted like yes okay how we can solve this problem it's an easy one so let's do it in one line let's just return the list offer collections dot counter of the numbers one and the collections of the counter of namsu and let's check the elements so i will explain this line first we take the counter of the knobs one the counter is just okay for this example for uh for the second example the cancer is checked this is our array the counter is transferred this array into a hash map that's half numbers let's see for four repeats in one time so for one and nine represent one time so nine one and five repeats in one time so five one okay and for the second numbers we have 9 4 9 8 and 4. so let me start by nine is repeating one time so right then four is nine zero pieces twice then four is represented twice and finally eight is reporting once and we make andropulation and operation between these two guys so if for represent here one and here two we take four ones so we take this so now we have this these are this one and then we see nine near complete here we have one and he'll have two so we take mine one and that's it in exist but here we don't have five and here we don't have eight so we just take this and then we take the elements of these two guys so we take four and nine and finally we make it at least that's it should work let's run the code it's a linear complexity okay something wrong did you mean counter yes okay focus here and now let's submit the code okay it's worked fine i hope this video was useful for you and see you soon ciao
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
1,754 |
hi folks let's solve largest merge of two strings if you haven't read the problem you can take some time to read it the problem is we are given two strings rule one and word two and we want to construct a new string how to control it will merge in the following way we can either fix the first character in word one or we can pick the second and the first character in word two if we pick the first capital in word one then next we can pick the second character in word one or we can pick the first character in word two for example first we compare c and b we know c is better in lexical a and order so we pick c next and we compare the a with b is better so we pick being one two next we compare a in with one and the same word too we know c is better so let's take a look at how to solve this problem this is first example we have two words and we want to merge them first of all we know c is better so we pick c next we know b is better so we pick b and we do same c is better so we pick c okay now the problems comes which a we should pick we should in the way one or we should pick a and we're too okay so how do we choose we can look ahead we can compare substring of y1 and the substring of war2 we know the substring of world one is aba the substring of war 2 is aaa so aba is greater than aaa so we can pick a in would one so that we can reach b quicker since b is a better character so this time we pick a in word one and our answer becomes cbc a okay next we can pick b and now we with the same situation we have two syn characters so we apply the same methodology we just compare substitution of one to one and over two and we know the substituent for two is larger so we pick a and we two which then we just repeat the process until one of the word uh is used up then we can append the substring of another word into our answer so this is implementation we know we have two uh indexes and in this while loop we just compare the substring and we just pick the character of the largest substring and we just repeat this process at last if one word is used up then we can append the substring of another word into our answers now the time complexity is o n square since we have a while loop here and when we compare the substring you also need to scan almost on all the characters so it's o n square and a space is on we know it's a little bit slow and the memory usage is high since the substring copies unlike all the substring of this word is time consuming so we have another implementation we can change how it compares we don't use substring we implement a method called greater in this create function we pass original way one and word two we also pass the country index then we just compare them one by one and don't forget to and check the size for example we have two string a b and a b c and i and j is zero since a b are same so it will jump out of the while loop and we know abc is greater than a b so we just compare the size here the memory usage in this implementation is much less previous it's 400 meg by now it's just 10 megabytes okay thanks folks
|
Largest Merge Of Two Strings
|
largest-merge-of-two-strings
|
You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For example, if `word1 = "abc "` and `merge = "dv "`, then after choosing this operation, `word1 = "bc "` and `merge = "dva "`.
* If `word2` is non-empty, append the **first** character in `word2` to `merge` and delete it from `word2`.
* For example, if `word2 = "abc "` and `merge = " "`, then after choosing this operation, `word2 = "bc "` and `merge = "a "`.
Return _the lexicographically **largest**_ `merge` _you can construct_.
A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. For example, `"abcd "` is lexicographically larger than `"abcc "` because the first position they differ is at the fourth character, and `d` is greater than `c`.
**Example 1:**
**Input:** word1 = "cabaa ", word2 = "bcaaa "
**Output:** "cbcabaaaaa "
**Explanation:** One way to get the lexicographically largest merge is:
- Take from word1: merge = "c ", word1 = "abaa ", word2 = "bcaaa "
- Take from word2: merge = "cb ", word1 = "abaa ", word2 = "caaa "
- Take from word2: merge = "cbc ", word1 = "abaa ", word2 = "aaa "
- Take from word1: merge = "cbca ", word1 = "baa ", word2 = "aaa "
- Take from word1: merge = "cbcab ", word1 = "aa ", word2 = "aaa "
- Append the remaining 5 a's from word1 and word2 at the end of merge.
**Example 2:**
**Input:** word1 = "abcabc ", word2 = "abdcaba "
**Output:** "abdcabcabcaba "
**Constraints:**
* `1 <= word1.length, word2.length <= 3000`
* `word1` and `word2` consist only of lowercase English letters.
| null | null |
Medium
| null |
911 |
hey everybody this is Larry this is me doing an extra bonus to have attemp problem uh an RNG so let's go hit the like button hit the Subscribe button join me on Discord let me know what you think about this one especially since the other actual daily PR is a what is it power of two I don't even remember already that was like so let's get something slightly more challenging and we have a medium prom someone call 911 cuz it's an online election uh a lot of downloads but we'll see so you're given two integer arrays persons and times in election I was cast for person I at times I okay which query at a time I find the person that was leading the vote okay I mean it's kind of unnecessary un weird that's not how de democracy works but I guess that's kind of okay yeah it there's only one time uh where it matters which is at the end when everyone cast it vot of course but anyway all right uh all right for each carry T find the person that was leading the election at time T V Cast it at time T counts okay in case of a tie the most reason worlde wins okay so basically you have and you have times okay so this is a little bit awkward because you are given these strengths um and I say awkward only because like I feel like if this if you were trying to pretend this is a real world thing then of course you would say um uh you would say like you could like there's another function maybe you could cast a vad at a certain time and then you know you can't do that in order or something like that but here you can actually what they want you to do I suppose is pre-process the times um so suppose is pre-process the times um so suppose is pre-process the times um so that when you do a query you can just do like some sort of binary search type thing uh I mean that but yeah um how many candidates are there I guess it could be I mean there only 5,000 people or like 5,000 votes so only 5,000 people or like 5,000 votes so only 5,000 people or like 5,000 votes so it can be um yeah so up be to 5,000 yeah so up be to 5,000 yeah so up be to 5,000 um how do I want to do it I mean if there were not that many candidates then um then what you can do is just do like a prefix some or prefix array type thing right uh but is a little bit awkward for sure um because and it takes 5,000 or sure um because and it takes 5,000 or sure um because and it takes 5,000 or like a loop of 5,000 every time which is like a loop of 5,000 every time which is like a loop of 5,000 every time which is a little bit awkward uh is that fast enough though at most 10,000 or 10 to enough though at most 10,000 or 10 to enough though at most 10,000 or 10 to 4times 1,000 is already going to be 10 4times 1,000 is already going to be 10 4times 1,000 is already going to be 10 to the 7 right so yeah uh so that maybe that's a little bit too expensive so we have do a little bit smaller than that right um H how do we want to think about it I mean the times part doesn't really in interest me that much we got to do a binary search or you could Norm noriz all the numbers uh you know it's really not a big deal but h i mean it's probably still going to be prefix some I mean okay so it could be pref or initially my idea was going to be prefix some um but and then you kind of just do it that way but I guess what you can do is just calculate the winner at every time or the only 5,000 votes so you can just the only 5,000 votes so you can just the only 5,000 votes so you can just calculate the winner of 5,000 votes or calculate the winner of 5,000 votes or calculate the winner of 5,000 votes or like 5,000 distinct times less than that like 5,000 distinct times less than that like 5,000 distinct times less than that actually because in Fe sometimes they bothe together but oh wait it's actually strictly increasing order okay well fine but either way what I mean is that yeah uh oh with oh if this is already in strictly increasing order that's even easier but yeah we'll just kind of keep track of who's winning and then at you know at thing we just let you know right so how um and the winner is oh it doesn't have to be majority right it's just leading yeah okay so I was going to use uh what was it border Moore or one of those I forget is it border more uh the V the voting algo but uh the majority algo but I guess now I cannot okay so I mean okay there are a couple of ways we can think about this um and all of them yeah I mean I think my hesitancy is just about uh using too many D structures but maybe it is necessary and if is necessary it is necessary I so basically the idea that I have now is just bookkeeping from a reset so basically keep track of all the winners of all the possible times so that when you get the te later you just kind of binary search um so from that and keeping in mind we only have 5,000 things so we can only have 5,000 things so we can only have 5,000 things so we can probably just keep two things right um uh ass sorted list which you can maybe think about as a heap that you can dynamically uh look at uh or the other uh CU in that case I think technically uh if you're really careful and you have a real max Heap U that you can uh update on then this is actually the ideal case for it but we'll just use sord list sorted list as a proxy for that right and then just the current roots and then yeah that's pretty much it right so okay so then here we have maybe votes is equal to collections. counter that's just like a frequency thing you know Maps a person to votes pretty straightforward and then sort the list for um so this thing is so that we can get the most vote uh the person with the most vote uh at any time so we could do that in I guess I actually I don't know if get Maxes all one or all log in but either ways well it to be cheaper right so yeah and then maybe we have like winner by time or something like that um and then that'll be our uh array that we just kind of yeah and then here then now we can just do for person time in si persons times right and then now so p uh sub person we increment by one right yeah so then maybe we can do if person not in root then per uh we have to set it up is equal to zero even know I mean I know that is a default thing so you don't actually need to set it up manually but it also allow us to do uh the sorted list which we need to name a little bit better but whatever it's the same way that like a heap you just name it a heap maybe but yeah add uh um zero person right so that's just basically the thing and then now you increment it but here now you can say sl. remove um votes to a person uh person I know that this you know this looks a little bit awkward but just so that we don't have to check for it and then we increment by one and then we can add back the incremented thing right oh I guess this is now updated so yeah and that's pretty much the idea and then winner by time we can now update um time and then SL I guess we always have a thing right SL of uh the last element um just the person right so yeah oops Yeah because basically we're getting this index on the last one which is SL Max and that's pretty much the idea uh we'll just print it out here for now just for fun seies and then we can kind of just debug it real quick l or like I just like to get a visualization uh and yeah and I visualized type having a typo apparently so yeah you could see that at time zero is winning then five is one oh we have to what about in case the tie the most recent world huh that we actually have to fix that then H uh that's annoying actually I mean it's not that uh okay I mean I think our idea is about 95% done you I think our idea is about 95% done you I think our idea is about 95% done you kind of see what we're doing here um you know you could kind of you know at time five one is winning time 10 but of course we have to kind of do this other type working thing which is annoying but again it's just bookkeeping and by that I mean we just have to keep track of it right so last time is equal to um just a lookup table right so then here we can say last time of person is equal to1 and here we just add an additional tie breaker um because we want Max so then here we can say last time person which is negative one I guess you want to just for symmetry then we could WR something like this and then yeah now we remove that back we increment we set last time of person is equal to time and then we just update it back or this is what the way of updating the way to update these is just remove and then add right and we just have to make sure that we're consistent and then yeah and then now we don't have to change that and we should be good uh I actually don't know what to expect o oh yeah we have to change this because now it is an index to oops this is why you know you use like um like a name toppo or something like this is where you know so you don't make these kind of silly mistakes uh but okay yeah so then now five and then 10 and then 15 and I don't know if this is right but it doesn't even matter right because um it just yeah we just you know we just need it and uh and then now I mean I guess it matters in a sense that you really want to deliberate but for now we'll uh we'll spend the time by writing the queue right so uh so now we can do a binary search right on the winner by time oh I guess I need to make this part of itself whoops um so here we have winner by time we want to do binary search what is oh BC left uh yeah we want to be B wait let me double think basically this is the time it is updated so if at a given time actually it's not Bice so actually it's BCT right but then we have to subtract one because you basically theide and I'm just thinking it through right now but the idea is that okay let's say you have 10 and 20 in your array somewhere as your searching thing if you have 15 you actually want to get 10 right because we haven't done the rootes for 20 yet so we want to get 10 and of course if this is 10 then we do also want to get 10 so that means that we want to BCT right to the next thing and then we subtract one so okay uh yeah t no this is should be Infinity so whatever um you want this to be Infinity so that if the time is exactly the same you skip to the next one um so then now you have index is you go this and then now if index x - one is between 0 and now if index x - one is between 0 and now if index x - one is between 0 and length of uh and this should always be true I don't know how this can be forc that would be amusing maybe um so maybe we can assert this cuz I don't know what to do with I mean it could be Force if uh you do it before the first element but I don't I mean I just assumed that it'll be well formed but I don't actually it doesn't maybe it's like stated in here something like this thing but um but okay fine so I think this is fine but then and then now we can return self. winner by time index minus one and then the second element which is one right yeah all right let's give a submit hopefully I didn't make a silly mistake and yep there we go uh what's the complexity here right uh it's just a lot of pre-processing this is obviously of pre-processing this is obviously of pre-processing this is obviously going to be lock uh or sorry o of log n right I mean you know this a binary search there this has the most N Things um because for each of the inputs we have each of one item here so it's going to be a linear time or linear space sorry right and uh and yeah this is going to be all blog in So yeah so all these three things have all end space so it's going to be all of end space and this as well of course um for here I mean for here for each of the nend items the loop RS end times we do a couple of uh couple of Lock and operations the sorted list mostly everything else is all of One probably and so yeah so that means that this is be n log in as part of the pre-processing and that's pretty much pre-processing and that's pretty much pre-processing and that's pretty much all we have for this one let me know you what you bank got in 31 Lin of code and yeah that's it stay good stay healthy to go mental health I'll see youall later and take care bye-bye
|
Online Election
|
profitable-schemes
|
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`.
For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.
Implement the `TopVotedCandidate` class:
* `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays.
* `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules.
**Example 1:**
**Input**
\[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\]
\[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\]
**Output**
\[null, 0, 1, 1, 0, 0, 1\]
**Explanation**
TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]);
topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading.
topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading.
topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.)
topVotedCandidate.q(15); // return 0
topVotedCandidate.q(24); // return 0
topVotedCandidate.q(8); // return 1
**Constraints:**
* `1 <= persons.length <= 5000`
* `times.length == persons.length`
* `0 <= persons[i] < persons.length`
* `0 <= times[i] <= 109`
* `times` is sorted in a strictly increasing order.
* `times[0] <= t <= 109`
* At most `104` calls will be made to `q`.
| null |
Array,Dynamic Programming
|
Hard
| null |
257 |
hey everybody this is larry this is me doing the bonus question for the 1st of august let's do a quick one let's do something i haven't done before let's uh do a random let the computer decide hit the like button hit the subscribe button join me on discord let me know what you think about this setup and uh we get a yeezy one today so uh just we have to do them anyways eventually so okay binary tree paths given the root of a binary tree we turn all root to leaf paths in any order a leaf is a node with no children okay so you have an output here um yeah i mean this is gonna be output sensitive and what i mean by that is because you have to be you have to return every possible one um there's no way to optimize beyond that in terms of you know and so you can just do a record that for searches i guess what i'm trying to say so uh so yeah let's do that let's still recursion uh yeah let's do and then we do it from node uh let's just say we have an answer list that we you know i will use the global variable but yeah so if this is a leaf if node is none we just return um we also maybe want to do the current path and then here if no dot left is none and no doubt right is none that means that this is a leaf and then we could do answer dot append by looking at the path uh we could do something like maybe this join path and then we return otherwise for the regular deaf researcher left and to the right and this is very basic you know deaf research you uh three traversary rethinks um so yeah so here we also want to make like f dot append uh no dot value and then yeah and then path dot pop i guess uh but yeah and here of course we would have to do path dot append no dot value as well yeah and then pop i think this is roughly right maybe i missed one of these um yeah and then diabetes an empty array and then we can return answer this is roughly right maybe i have some minor mistakes that i can create very quickly uh oh whoops i meant to type that in i mean i don't know that kind of mistake still a silly typo though but hmm interfere oh because i see so that th this is a list of ins so we have to do something like that maybe we could handle this a little bit better this is basically it makes it a little bit slower um but we could amortize it if we just do like maybe just do this instead because instead of doing it every time on the leaf we do it on the note level instead so that the higher non-leaf notes will uh higher non-leaf notes will uh higher non-leaf notes will uh be more effective yeah this is easy so there are definitely many ways to do it so that definitely very good um i probably don't need to test another thing because i think this is a little bit i am a little bit confident about it and yeah and looks like it's justified what's the complexity right well this is going to be linear time in terms of space let me see is it linear space i mean it is output sensitive so i think it can be at worse you know there's can be at most uh like k leaves is that true yeah or something like that right they're all leaves well maybe it could be n over two leaves and then each of these paths i don't know i think maybe it's n square uh for space but that is gonna be output sensitive so yeah um cool that's all i have for today for the bonus one this is a relatively simple one just because you would uh you know maybe not this particular problem but problems similar to this is something i practice a lot and i urge you to do as well this is because a tree is the tree itself doesn't it's fine but it's just a recursive structure and people on interviews do love to use it to test your recursion so definitely be very familiar very good and very playing around with it but yeah that's what i have with this one let me know what you think stay good stay healthy take your mental health thanks for joining me on the next your question i'll see you later take care bye
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
1,933 |
hi there i'm texas tim thanks for tuning in to my ongoing quest to grind through all the algorithm problems on leak code i have completed all the easy ones and now i'm working on the medium ones although sometimes leak code adds some new easy ones and so i go back and pick those off so why don't we see what lee code has for us today could be an easy one that popped up but it could be a medium so let's see what we got here we are got my profile page and let's see problems and i'm doing algorithms uh let's check easy status to do uh yes there is one they must have added it recently let's check it out all right 19 1933 check if string is decomposable into value equal substrings okay i don't know if i know that word a value equals string is a string oh where all the characters are the same for example those are value equal strings and that one's not okay so given a digit string s decompose the string into some number of consecutive value equal substrings oh my goodness where exactly one substring has a length of two there are a lot of conditions here where one substring has a length of two and the remaining substrings have a length of three return true if you can do it otherwise false oh my goodness all right so that is very interesting let's look at their examples so here we have zero and then one and then zero so we would need one that has a length of two and then all the other ones have a length of three and we can't do that here so if we do any of these as a length of two there'd be one left over because it does have to be consecutive let's look at the second example so we have three in a row and then two in a row and then three in a row okay interesting i'm starting to think about how i could do this i think we'll traverse you know this is the first stab i haven't even finished going through the problem description or the constraints but i think it will traverse the input string and take it um each section at a time a section being all the same consecutive values or characters and then so if there's like five ones in a row that i can think oh that could be a two ones and a three ones and then i gotta just notate that i've used up my two and i think we can i think this is going to be fairly easy because if there's say five characters in a row that are the same i know that has to decompose into a two and a three substring and then i've used up the two if it's six then it would have to be two uh length of three sub strings so based on the length of the sub string that's all the same character i think it'll be pretty straightforward to figure out how it fits into these constraints of you know one with the length of two and the rest with a length of three all right let's see what else we got so here we have a zero and it's one and that doesn't fit at all so that's an immediate false so we can also probably do some early return as soon as we hit a substring that's of length one of the same character we can return false right away and constraints could be up to a thousand and it'll be zero through nine this long length makes me think we wanna go through this once we wanna be processing the string as we go we don't wanna have to you know traverse the whole string and collect some kind of data or statistics about it and then go back over it a second time we don't want to do that so we'll want to go through it one pass that seems kind of reasonable let's get in there let's see what we can do all right um i think we can just i think we can do this i think we could use that for our what is it an enhanced for loop as they say okay and what are some of the stats we're going to want to collect so let's see length of current substring equals zero we'll say curcare and we're going to initialize if i can spell that right initialize to a non-digit is what we're looking for a non-digit is what we're looking for a non-digit is what we're looking for there that way we can check if within the loop we can see if that uh current character matches the previous so length of current substring and then i want to track with a boolean of uh let's see has length two been used it'll initialize to false i think that's what i'll need as we get into it i reserve the right to add more variables okay so if c is not equal to the cur care we have new care okay else well if it's if c is not the kirk here then it must be a new care wait we have uh hold on how do i wanna set this up if c let's start with the equal if c equals occur care we have another care um let's say substring continues there you go that's kind of the meaning i want to um put across we have a new care and then we'll have to catch something we will have to have a little step at the end to handle the last to wrap up um the stats and stuff for the last character because if the last character is like a one a sub string of length one then we'll have to check for that outside the loop because the um because the loop checks for whether the previous character is the same when it goes to the next character but if it's the last character of the loop then there won't be a neck so we have to catch it on the exit so i'm going to put a little reminder um analyze last care i'm gonna put don't forget to okay there we go so if the substring continues then we can increment this little variable and i think that's about all we do we're just counting up how many of that character there are in a row if we have a new character um process previous character now this is fun because we're making the previous character the for the first character in the loop for the very first looping the curve here will be maybe kirk here is i don't think that's the right variable name let's say previous care that's better there we go so we'll always have a new care on the first time through and i'm gonna do this so if the number if the quantity of the previous character we had it's going to be either a multiple of 3 or it could be 2 plus a multiple of 3. and if it's not either of those then we can return false right away i think that's about how it goes so if length of current substring let's get rid of current previous is tricky naming things oh why did it do that okay all right so if the length of the sub string is a multiple of three then we're all good no problem do nothing else if let's check for the condition of length of substring minus two i gotta add my other parentheses if it's um two plus a multiple of three then we're gonna turn on has the length two been used it's gonna be true actually here's what we've gotta check if we've already done that so if and then we can we get an early return here so if we get a case where it would be multiple of three plus two but if we've already used our length two then we can return false because now we've got two length twos otherwise if that's not the case then we can indicate we have now used r2 and um yes if it's a two plus a multiple of three then we check to see if we've already gotten our two we handle that and now finally we have to if it's not one of if the count of the sub of the previous substring is not one of those two cases then it could be like one or four it could be something that's not one of those cases then we can return false not multiple of three and not two plus multiple of three all right to plus part of the reason i document is to help myself not to forget what's going on here let's put multiple of three there okay multiple three two plus multiple of three and here now i can say neither of those actually what i like to sometimes do is to put actually put like case one case two neither of those cases i think that seems all right um we have a new character we've handled the we've processed the data for the previous substring now we've got to set things up to start counting the upcoming substring so let's update the previous care is gonna be the current one we're currently on and the length is gonna be one because we just have one i'm just making sure that on the first the very first loop of this of our for loop i want to make sure we don't stumble because i've set previous care to a so it's gonna be a new care and the length of substring is zero and zero mod three is zero so that will work that will be fine okay that'll work so intricate and now as we come out of the loop we basically have to kind of do this again that's annoying is there another way to do it i am inclined for the moment to just copy that there probably is a cool way that i could like maybe a do while or something we just have to put the condition checking in the right place um let's try this i think this will work um two plus two that works and actually we don't we would um we could even just return true there and look do we so if the last substring is a mod 3 equals zero then we can return true there and neither of those actually that's case three neither of the first two cases i think this will work man there's a lot of ifs in there let's um let's run it i think it'll work dang it output true but it wanted false because there's no oh we need to have one substring of length two there has to be one so we're gonna um so what we can do is return this variable so return so if it has been used meaning it's been used once then we just return it and there we know we can just return false actually here so i don't need to so with this first one i can return that i can just return this flag variable and then here if we have a two plus multiple of three we've already used the two return false otherwise we know we can return true and then if it's neither of those like it could be if it's a 1 length 1 or length 4 return false okay i think this should work yes it worked let's submit it let's see where we're at uh performance but you know i'm not gonna get too excited because i think this is a very new problem i think they just released it like it might even say there's not enough data let's see not enough yeah see not enough submissions so it's fast but you know there could be just not it doesn't necessarily say anything um i would let's take a little look and see if there's any obvious ways to improve this so length of sub string there is overhead with um conditionals like if and else so a small optimization is to move the most likely or most common case up top so that you catch it first and move on and you don't bungle through a bunch of uncommon cases that you have to that you tack on to every check um so for example if we thought there were going to be not so many strings like not so many valid strings if we thought there were going to be a lot of invalid strings then maybe we could check if it's not the previous character first but it that's probably fine all right if we have a new character we check for the mod 3. i uh okay i'm not seeing a lot of opportunity for improvement part of me wants to try to rejigger this loop probably not using a for loop but maybe just like a while or a do while so that we can check this stuff one time but then i worry about this video being super long and me just kind of stumbling around tell you what if you found this interesting and it's enough for you go ahead and hit stop head on out that's fine but if you want to stay on and see if i can rejigger this loop so that we can have so that this uh so this testing of the length of the substring if we can have that appear in one block then stick around because i'm gonna do it right now okay so if we go away from the for loop i'm gonna need a little sip there to get going then we are going to have an index variable which will be zero start at zero and then i am i'm gonna put while true just to kind of um i think i can do let me go ahead and delete this so i'm going to have this wild true while i figure out how to break it or maybe depending on how i set things up i could just return from within the loop yeah we'll see i need now i need to populate c equals s carat index and as long as i'm not going to touch index again i guess i could increment it oh maybe the while condition could involve the index or i could check something at the end of the loop about the index so what i could do and all this really comes down to how we handle that last character well right after the last character so when index equals length minus 1 of s what if we had a boolean like good so far like a little signal variable called good so far that we could set as needed and then at the end of every while loop we check it we check the value of index hmm okay see hmm we could also the problem is when index gets incremented to the length of s then this will do an error because the string s doesn't have an index um location equal to its length because it would be length minus one it'll be the last character so what if and here i'm this is you know i'm adding an if block that would get checked every time so i feel like this would with this would slow down the overall algorithm because it's an additional check in every loop and so it's costing us a little bit of compute time what we are gaining is we only have this block one time you know it's a sort of where do you want to save you know do you want a shorter algorithm with less code there's value to that because then if you decide to modify the conditional checks then you don't have to have the risk of updating it in the conditional checks within the loop but then forgetting to do it in the copy of those checks that takes place after the loop so i'm going to say on the whole for maintainability it there's value in not having basically a copy so let's proceed you know if i thought there was no value i'd say why are we even doing this why am i trying to write a loop you know just to save lines um but i think there is value because then you don't have two virtually identical blocks of code so if index equals meaning we've run off past the end then instead of setting c to any character within the string let's make in that case let's make c again a non-digit let's say a non-digit let's say a non-digit let's say set to a non-digit when the entire set to a non-digit when the entire set to a non-digit when the entire string has been traversed and then it will always count it will trigger the if we have a new character hmm it's gonna do these things start counting your character and then i guess down here we'll have a check um if index is the length oh actually look at this we'll want to move that so i could have if index is equal to the length of s and then otherwise then assign it here and then i don't know if um i don't know if leak code will allow me to not initialize it why don't we find out we'll see i feel like i'm always learning what the elite code judge you know the jvm that they've got what it will allow and i guess i know what it is it's a java se13 so it's i guess it's not the judge if it's not specific to leak code then i probably should know i think it'll raise an error i think it will let's find out let's just find out real quick let me comment all this out see if it'll let me run it if i get a time limit exceeded that means that it worked okay so it will let you um it will let you not initialize it so i'll say we'll initialize in if block below oh i must have hit the developer key okay so if index is s length then if well here we would just return here's where i can just return the value of our boolean of whether we've gotten the two the length two done so i think this will work so we've we have just we have our conditional block one time right in here which is good for maintainability and the cost is that we have some checks in every loop see if it runs i hope it works yes okay it worked for this one let's submit it and see if it works why is why did it not work i told it false it wanted true how many sixes do we have here um let's see how many sixes one two three four five six seven eight nine ten eleven twelve so that should be okay that's a multiple of three and then it ends with a multiple of two so maybe we've failed to correctly account for the final substring why don't we add a break point and see what's going on let me get my debugger okay i've added a break point here let's debug let's see what's going on in there and what's the length of that guy so we have 12 plus 3 is 15 so 17. so index and i'm mainly interested my goodness this is gonna take a long time c is six next two oc is the current character here oh my goodness i'm just stepping over like a maniac where it's going to get interesting is up in 15 index of 15. is there a st no i don't want to do yeah i do want to try to find okay we're getting there scintillating watching isn't it okay we're getting close we're gonna see previous character change in a second so here's the next 12. now for index 13 c is now seven previous care is six now we're updated previous care you say in the comments let me know if you say care or char or something else i say care because it's short for like character right but i think i've heard other people say char if you do one of the other i would be curious let me know down in the comments index 15 it's about to get really interesting here we go c2 and we're about to update length of substring there it goes index 16. what i'm waiting to see is when has length 2 been used gets updated and it was not so what i can do is okay let's stop um if index is the so what i need to check is if the length of substring for the current one the last one in the list if that is two and we're gonna have like an ore here so if um if has two has been used okay let's see so if indexes s length tells us that we have com that we've run off the end of the string we've passed the last substring it feels like we're doing another conditional block which was the whole point of trying to avoid it okay so if we haven't done the has length the length two and you know we have a two then return true else um if we have found the length two and length of a substring mod 3 0 then return true and actually this would be um we need to test if it's minus two mod 3 that's what we really equals 0 that's what really need to test for then return true so this is if we haven't used the 2 and the most the last substring has the two then can return true otherwise if we've used the two already but the last substring is multiple three we can return true if neither of these are the case then we would turn false so could is it were we not able to i guess we weren't able to get away from what's that else line 48 no else if was i not able to get away from my blocks my multiple blocks got it accepted yes so it worked that's good and it is abbreviated because we don't have to update has length to been used or anything we just have we're just checking so i guess that's a little bit of a win i think i was and there's probably a way maybe there's a way in there with another flag hmm i'm not sure but i think we've done a good job for today i'm happy we explored an alternative solution and for those of you who hung on to the bitter end stay in the extra 20 minutes i appreciate it thank you for tuning in and sticking with if you want to see more videos that i do feel free to subscribe and like below and you'll always catch new ones that come out and um until next time see ya
|
Check if String Is Decomposable Into Value-Equal Substrings
|
number-of-different-integers-in-a-string
|
A **value-equal** string is a string where **all** characters are the same.
* For example, `"1111 "` and `"33 "` are value-equal strings.
* In contrast, `"123 "` is not a value-equal string.
Given a digit string `s`, decompose the string into some number of **consecutive value-equal** substrings where **exactly one** substring has a **length of** `2` and the remaining substrings have a **length of** `3`.
Return `true` _if you can decompose_ `s` _according to the above rules. Otherwise, return_ `false`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "000111000 "
**Output:** false
**Explanation:** s cannot be decomposed according to the rules because \[ "000 ", "111 ", "000 "\] does not have a substring of length 2.
**Example 2:**
**Input:** s = "00011111222 "
**Output:** true
**Explanation:** s can be decomposed into \[ "000 ", "111 ", "11 ", "222 "\].
**Example 3:**
**Input:** s = "011100022233 "
**Output:** false
**Explanation:** s cannot be decomposed according to the rules because of the first '0'.
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of only digits `'0'` through `'9'`.
|
Try to split the string so that each integer is in a different string. Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique.
|
Hash Table,String
|
Easy
| null |
1,447 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my daughter's I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go IQ to simplified fractions so yeah so this one you just have to generate or have a way to generate all the simplified fractions the key thing to note is that a fraction is simplified if they don't have a common denominator so basically which means we just use the GCD function to check whether and because n is equal to 100 you can generate or 100 squared pairs or 100 choose two pairs if you will and then just make sure that yeah the cheesy theme befits and the numerator is smaller than denominator and that's it I think I just played around for pie once here but that's the general idea behind how to do I was thinking like I need enough or like it's an arrow and plus one or something like that and I took a little bit more time to think about the actual edge cases but then I was like whatever just we could generate it or we can filter it out later or something like that so yeah that's essentially what I did it pretty proof for C but it's cute too so I was confident about it so it was at this point is wrong cuz I have to convince these strings and also at that point I given though that wasn't positive thing I you know I said I should make sure that why is picking or yeah why is bigger than X and I was like ah that doesn't include one of the numbers so I need em off by one and I just I didn't need under X I was thinking about I was again I just get to it anyway because Jesus III would never be equal to one content but that's okay and then I sum it and then that's it q2 who simplified fractions so basically given a numerator and denominator for this one and there is only simplified if this GC D is equal to one meaning that the greatest common denominator between the numerator and the denominator is one damage you can't simplify any more so base a what I did was I just did the proof for since n is only 100 yeah I just check every X is equal to Y or X is less than Y and check that the GC T is less than or is equal to 1 sorry and then that's it and I just put it in and I also check that it could be in any order so we don't have to do any sorting so I just return it afterwards
|
Simplified Fractions
|
jump-game-iv
|
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**.
**Example 1:**
**Input:** n = 2
**Output:** \[ "1/2 "\]
**Explanation:** "1/2 " is the only unique fraction with a denominator less-than-or-equal-to 2.
**Example 2:**
**Input:** n = 3
**Output:** \[ "1/2 ", "1/3 ", "2/3 "\]
**Example 3:**
**Input:** n = 4
**Output:** \[ "1/2 ", "1/3 ", "1/4 ", "2/3 ", "3/4 "\]
**Explanation:** "2/4 " is not a simplified fraction because it can be simplified to "1/2 ".
**Constraints:**
* `1 <= n <= 100`
|
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
|
Array,Hash Table,Breadth-First Search
|
Hard
|
2001
|
606 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem construct string from binary tree before we get started i just want to mention if you haven't heard i recently launched neat code pro there's a 25 off launch sale going on right now you can get lifetime access to all current and future courses just before i started recording this i just launched the first batch of lessons for the advanced algorithms course i hope to have that finished by the end of september and by the end of october we should have the system designs course released okay now back to constructing a string from a binary tree we're given the root of a binary tree and we want to construct a string consisting of parentheses and integers from the binary tree with the pre-order traversal way tree with the pre-order traversal way tree with the pre-order traversal way and then return it now this is kind of confusing and i think they definitely could have worded this problem better especially for an easy problem but essentially we want to do a pre-order essentially we want to do a pre-order essentially we want to do a pre-order traversal that much is straightforward but for the first value it's going to be the first value in the output string so we're going to have a one then we want to do the same thing a pre-order to do the same thing a pre-order to do the same thing a pre-order traversal for the entire left subtree but we want to put the entire left subtree within a set of parentheses so now we want to put the entire you know all the values from the left subtree in this parentheses so we do that we have 2 so we put the 2 there but now for 2 recursively we want to repeat this so we want to put its entire left subtree in a set of parentheses in this case it'll just be a single 4 in a set of parentheses and then we want to do the same thing for the right subtree but there is nothing there but let's just put an empty set of parentheses for now okay and i just wrote it over here just to clean it up a little bit but now we did the entire left subtree now it's time to do the right subtree and remember before we even start we want to put it in a set of parentheses we just have a single value 3 so we put that 3 there it doesn't have a left subtree so i guess we can put some empty parentheses and it doesn't have a right subtree either so we can put some empty parentheses now the thing here is they say we want to omit all empty parentheses pairs that don't affect the one-to-one mapping relationship between one-to-one mapping relationship between one-to-one mapping relationship between the string and the original binary tree now the first time i read this problem i read it as we just want to eliminate all the empty parentheses so in this case our solution we could take this entire string get rid of this pair of parentheses get rid of that pair and get rid of this pair so then our solution looks like this and this is the expected solution so we did it correctly one thing to mention though i think it's interesting and it makes this problem slightly harder that we don't have a set of parentheses around the entire string that's kind of unusual it seems we only put parentheses around the subtrees but oh well now before you rush into writing the code there's actually a second example for this problem that illustrates you know what they mean by that one-to-one mapping relationship that one-to-one mapping relationship that one-to-one mapping relationship first of all this output string that we have is not ambiguous it tells us that the root node is one it has a left subtree that root of the left sub tree is a two and that two has a left child four and that two does not have a right child because if it did it would have some parentheses over here but it doesn't and then we get the right subtree which is just a three and of course it doesn't have any children this is not ambiguous at all but instead if we took this four node and it was actually a right child of this two and then we ran the same algorithm on this tree we would end up getting a similar string to this one the only difference would be that we would actually have an empty parenthesis in the spot of this and the four would be over here because the left child of two is empty but the right child is four but we would end up taking this string removing the empty parentheses anyway and then that would end up reducing back to this guy but how can two different trees have the same string representation that shouldn't be allowed so i think what they're getting at with this is that if we have a node where the left child is non-empty but where the left child is non-empty but where the left child is non-empty but the right child is empty then we can eliminate the parentheses just like we did but if the left child was null and the right child was non-null then the right child was non-null then the right child was non-null then the output string should actually look like this where two has a left child but the left child is empty but it also has a right child which is four and then we have three has two uh null children right it has it doesn't have any children at all so there's no need to add extra parentheses there but this is basically telling us that two does not have a left child but it does have a right child here we knew that two had a left child but it didn't have a right child basically when the parentheses are at the end then we can remove them the empty parentheses when they're at the end we can remove them or the way i think about it is just if we have a node that doesn't have a left child but it does have a right child then we keep that pair of empty parentheses okay enough talking now let's code it up it's not too bad once you kind of understand this caveat oh and of course since we're doing a pre-order traversal we're only doing a pre-order traversal we're only doing a pre-order traversal we're only going to visit each node once so the overall time complexity is going to be big o of n okay jumping into the code i'm actually going to declare the result as an array while we're trying to build an output string when we take strings and constantly add them together it's not an efficient operation it's usually not constant time so what i'm actually going to do is take each substring and add it to this array and then at the end what we're going to do is take every substring in the result and join them all together and then return that when i'm taking this empty string here i'm just saying that's the delimiter so we're going to take every string in result and then add them together they're going to be separated by an empty string that just means i'm concatenating these together okay now let's write our pre-order function i'm let's write our pre-order function i'm let's write our pre-order function i'm writing it nested inside the outer function so we have result in the scope of this function but our pre-order is of this function but our pre-order is of this function but our pre-order is going to be given some root note or some node and if that node is null we're just going to immediately return now you could return a pair of empty parentheses depending on how you're writing it especially if you're not writing it you know if you're just taking the result strings and then adding them together to create the result then you could probably return stuff but i'm doing it with an array so it's gonna be a little bit harder to do that so i'm just going to return nothing here then what i'm going to do is we know when we're given you know except for the root node when we're given any node value that's not null we want to add an opening parenthesis and then we're allowed to add that value itself remember the value is going to be an integer so we want to convert it to a string so we can take root.val and convert it to a string and root.val and convert it to a string and root.val and convert it to a string and then before now we append that closing parenthesis before we do that we have to also run pre-order traversal on the left also run pre-order traversal on the left also run pre-order traversal on the left and right subtree so we're going to run pre-order root.left pre-order pre-order root.left pre-order pre-order root.left pre-order root.right and it's as easy as that but root.right and it's as easy as that but root.right and it's as easy as that but believe it or not there are some issues with this code the first one is relatively simple the way this code is written it's going to put a pair of parentheses around every single node in this case even the root node but we don't want a pair of parentheses around the root node the pair should be around every sub tree but not the root nodes so this result is incorrectly going to look something like this where it's you know one let's say is the root node two is the left node and then three is the right node it's going to look like this but we don't want it to look like this we don't want that outer pair of parentheses so the easiest way to get rid of them is just to take this string this is a string by the way and then we can get rid of the first character so we're going to start at index 1 and we're going to go up until the last index but not including the last index negative one is the last index in python but whatever index we put as the second one is not going to be included so we're going to basically chop off the first character and chop off the last character by doing this so that's the first bug the second bug is what we talked about in the drawing explanation here the way i've written the code if we have an empty node or write an empty child we're not going to end up appending anything to the result and that's usually what we want to do usually we want to eliminate all empty parentheses except the case where the left child is null but the right child is not null so the easiest thing to do here actually believe it or not is just an if statement we can say if root.left an if statement we can say if root.left an if statement we can say if root.left is not is null so not root.left and not is null so not root.left and not is null so not root.left and root.right is non-null then we can root.right is non-null then we can root.right is non-null then we can simply say result.append simply say result.append simply say result.append a pair of parentheses so we're doing this we're adding that pair of parentheses when we only when we need to and then we're still running pre-order and then we're still running pre-order and then we're still running pre-order on left and right i mean technically if this does execute as true we would not need to execute this line of code but i'm just leaving it like this for simplicity so in that case this pre-order traversal would just pre-order traversal would just pre-order traversal would just immediately return but this pre-order immediately return but this pre-order immediately return but this pre-order traversal would still end up adding that right subtree oops i guess we had another couple bugs first of all we should not be appending to the root is a tree node so we want to append to the result i had it correct up here don't know i probably turned my brain off when i was writing that line of code and also we wrote our pre-order function and also we wrote our pre-order function and also we wrote our pre-order function but we never called it that's a really easy thing to forget we're going to call it passing in the root node that we were given in the outer function now let's run the code and make sure that it works and as you can see on the left yes it does and it's really efficient so i really hope that this was helpful if it was please like and subscribe check out neetco.io it has a ton of free resources neetco.io it has a ton of free resources neetco.io it has a ton of free resources and you can get 25 off neat code pro thank you so much for watching and hopefully i'll see you pretty soon
|
Construct String from Binary Tree
|
construct-string-from-binary-tree
|
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
**Example 1:**
**Input:** root = \[1,2,3,4\]
**Output:** "1(2(4))(3) "
**Explanation:** Originally, it needs to be "1(2(4)())(3()()) ", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3) "
**Example 2:**
**Input:** root = \[1,2,3,null,4\]
**Output:** "1(2()(4))(3) "
**Explanation:** Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Binary Tree
|
Easy
|
536,652
|
278 |
Hello Hi Guys Welcome Back To My Channel Tu Yaar Swagat Hai Once Question Me Family Was This Year's In This Today We Are Going To Discuss The First Version We Had Said In The Last Video That This Is The Category That Is Going On I Will Name It Pyaar Basic Questions and Binary Search Category is ok, I am giving basic and introduction questions for exam but I had said in the previous video that these are simple questions, these are very easy questions but friend, it does not mean that you should skip them. These are good questions, I told you that there are some questions asked on Google, one of them is ok, this question has been asked on Google, please do n't ask with me friend, online assessment, I don't know the entire interview after so long, I just Like, I definitely know that this question has been asked in Google because my friend has link premium etc. so I came to know from there, so whatever is there is ok, this question has been asked in Google, the question is change test what matters, ok, so this question Read it, Yeh Hai Tu 11078 was the first time on pad version free food, so that friend, look at the questions in this way, told me this in the interview, asked - interview, asked - interview, asked - Use it in judgment on me online, questions come in this way where But an attempt will be made to trap you by making up stories and twisting them, so friend, you can definitely try. Okay, then the story has been made up a bit dry in this question. Okay, so nine Let's Salute questions, so I have put them here too. From here I read your product manager and currently doing it will develop new product unfortunately the latest version of products qualities in this version is developed as is ww2 previous version however in female version coming early morning aversion and want to live with Positive one you are one and it is pad version and that used minimize number of two apk file okay so basically what is we are cropping us people na we are a product manager and forever what are we doing okay now It is the latest version, is n't that the quality checkup? What is the quality check on Railgariya? Quality check is done on every version. Quality checkup is done on every version. Now what happens is that ours was the latest version. If it is the latest version then The current version was the letter, there was any increase, it failed the quality checkup, that is, it turned out to be a bad version, the quality got confused, then the daily life turned out to be a bad version. What are you saying, send 30 inch vs developed, please listen all version, software version and And in the morning, now look at what it means, it could be that the previous words, I am bed, God, have passed on quality, so by playing with quality, this house has given you a feeling of quality, but what is that to say? As soon as one of your pad versions is released, all the subsequent versions after that are all breads, so whatever product you had made, as soon as one pad version is released, all the subsequent versions after that are now available to you in a particular word. These were found to be of quality, now what is the problem that you are sitting with the previous version but you do not know which was the first version and if you want to know then API has been given which tells you which version you are using. Will you tell me that there is this version also, he will tell you the weight sale, forget whether there is a band of memories of cats or not, now suppose that he gave you the call in the cafe, you played it again and after getting it to him, he called me through a letter, this bad idiot came and said that he Yes, the twist is that play the tweet that now there is a wristband version so can ask friend can definitely grow on the first bed only then the pad version is free itself the first pad version so is this backward question transition points you are feeling something where basically what is If I want to reduce this question then look what I am going to show you by reducing this question, it is nothing here, there are some zeros and some 101 stand for bed and strength for good, first few good versions. After that, there are all the bank versions, tell me the first bank bhajan, is this the first and is not the only one, is this a question for students of one i.e. is it not a transition point? Absolutely i.e. is it not a transition point? Absolutely i.e. is it not a transition point? Absolutely friend, this is exactly the same question, there is no difference in it, I have edited it. Like this question has been converted into the previous question, think carefully, apply a little brain, post the video and you will also think, you too must have got this confusion, till now it is fine, so this is nothing, this is a previous question, what to do here. Give to match transition point, that's all I am going to write. Apart from this, I am going to write more things in the notes otherwise there is no use. Only water has been kept in the question and you have to walk in the numbers. So let's go to waste transition point. Okay, now on to the code. Let me show you the code, how will it be, Harbhajan, I have taken it from my mind, you people will increase, the thing is that you people will increase and only use nov30 office is ok, so what I said was to front the software version. I said, friend, let's go till Pluto is nipple to and minute will be taken out like Aamir will be out brother people plus 5 - Aamir will be out brother people plus 5 - Aamir will be out brother people plus 5 - Lord made by two girlfriend so is that you have to balance the apk file calls minimum it was given to you that the lid You are applying that bad version, if you want to minimize it then you are a true Yogi because if you apply it closely, from close to close, while checking all these versions, you go that man, this button is this button, then you are many, now one. If you put it in a bowl then you will be able to do this call me clearly in it only when you show me what you want after research, so here this bad version of me has been given in this way, so sit here and check the version of but I, so that you can do it, friend, that happened. Is it or which one is it then if so friend this version is my pad version then see yours also have to do the mill here. Potential answer is written below - So Potential answer is written below - So Potential answer is written below - So what did I say that bed question, if this version is my idea then May be this back is the first and there is no guarantee of waterfalls, there is no guarantee, so what should I do by becoming the middle - Friends, there is so what should I do by becoming the middle - Friends, there is so what should I do by becoming the middle - Friends, there is no guarantee that this is the first time, be afraid otherwise what will you do to crores of people, Lakshman and in the end. Udan Chala, return the answer, is the potential answer ever going to be minus one in this case? It is not going to be there because the question given to us is that there is some pad version or the other, it is okay, so sometime or the other the answer is going to change here. If it is - the mind is never able to come up with the answer, it is a - the mind is never able to come up with the answer, it is a - the mind is never able to come up with the answer, it is a matter of - it will never come from us, matter of - it will never come from us, matter of - it will never come from us, I am so friend, look at the question has been solved easily. If you remove this condition, it is nothing, it is the same. Those of you who were worried about whether the value is off in the transition zone, you are checking this pad version with doctors, it is just a question about exactly in the transition point, it is fine, so come that friend, you must have liked this question and it is in Google. If there is a Pooja question then you can get some idea of what kind of questions of what kind of questions of what kind of questions you should ask for practice. Tuition people come to the factory to practice hard questions. Even hot practice is not beneficial for traffic. Extremely hard questions are not asked. Okay, Hotmail eclipse asks questions. Google, you lie a lot, then the day is mixed with topics and the question is asked but defense against that if I play Google, then I mean it is very good, it has been asked, then it is good, what is the time complexity, login again because despite this there is a question and we have If you have not used a suspense, then do the auxiliary food and actress or I felt a deficit, this cross has also remained off, you have come to this question about healthy sitting food, you must have understood the notes, this is enough for this one. For questions, just like this video, if you liked Lashes, share it and subscribe the channel, we will meet on these tracks, till then Siya have a nice day.
|
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
|
341 |
Hello Guys Welcome Water Mist President Loot In This Question Thursday Elements Class One Officer subscribe this Video give Video Please subscribe And subscribe The Amazing Difficult Subscribe Quid Left So Let's Robbers Loot Cash Withdrawal Necklace VCES Can They Have Three Idiots Rich Wives Subscribe Electronic Atal Bittu Increase Complexity of Problem Subscribe Will Introduce To More Subscribe Tours Value Subscribe Button Left Side It Close Loop Control Eid Diwali Decoration With Printed It White The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Thursday subscribe to the Video hua hai next bill check if the current point se left side and width values subscribe The Channel subscribe to subscribe And subscribe The Amazing Thursday Ko Ki Reddy Inductive Veer What they did in the lap of wave all subscribe now subscribe The Channel subscribe this Video Third The President Of Mid-July With Video Third The President Of Mid-July With Video Third The President Of Mid-July With Winning This Not Mean That Rule Vidmate Value Video Channel Radhe-Radhe A Cold Get List Mithlesh Lage In Return Alif Nested Which Knowledge Point Must Subscribe Button More Necklace Copper Metal Vid U Yesterday Morning Uthakar Dhairya Admit Us Emphasis Value And Join This Can Be Vidron The Colleges In The Amazing Subscribe Now To Receive New Updates Yet Otherwise Patience Liquid subscribe and Share And subscribe The Amazing fluid Karan Adhik Pinpoint Up Indiscriminate Increment Current Affair Expired And Mother Subscribe Video Subscribe In This Particular liked The Video then subscribe to the Page if you liked The Video then subscribe to the detention President Appointed A How to Approach Dandruff Problem Solve and Looking Problem Multi Level liked The Video then subscribe to Do
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
283 |
foreign other problem from uh Ray category uh called Moon zeros uh in this always we will start with our problem statement input output and then move to an uh concrete example and then finally conduct the solution so in this case we have a pretty safe for a problem statement we only have one input which is sent jury called nums and the return type is white so we don't really return anything the only thing that we have to do is move all zeros to the end of the array uh while moving the non-zero array uh while moving the non-zero array uh while moving the non-zero elements to the front and keeping their relative order the tricky part of this problem is that we have to do it in place which basically means that we cannot copy to another data structure we cannot create any helper data structures to using this uh to use in our solution and which basically means that we will have a constant time because it space complexity for the examples as you can see nothing special because I will start with the second example it's pretty uninteresting it's only one element and it's zero so the input is basically left untouched uh and there was nothing to do it's just a zero the first example is more interesting and as you can see we have 1 3 and 12 which are non-zero elements 3 and 12 which are non-zero elements 3 and 12 which are non-zero elements that are moved in front while the two zeros are moved uh to the back as for the constraints nothing wild nothing special uh the nuns values are in a range of the integer Max integer uh while the length of the array is uh from 1 to 10 to the four so in that case we will hope to find an algorithm that performs in a linear uh fashion because of the size of an array and we will now move to the concrete example and here I have the same example from the problem statement and usually how we solve this problem is that because we have to do it in place we will have one iterator that will basically just Traverse through the array and we'll call it iterator picture and we will position it the first uh first element and the second uh pointer will we will call writer now eater will be just basically an i variable inside the four it will just go from zero to the array of length minus one while the writer will only move if the uh element that it is pointing to fulfill some requirement for example in this case we want to place the non-zero this case we want to place the non-zero this case we want to place the non-zero elements to the front which basically means if the iter is pointing to a non-zero element we can write that non-zero element we can write that non-zero element we can write that element to the position where writer is pointing to do and move writer to the next position so in this case we will initialize the writer to zero as well so writer will point it here and we will have the data pointing to the uh to the first element as well uh the thing that you have to note is this is the same array uh this is just for the explanation purposes um so the first element is zero so the writer we don't move the writer we just move the iterator to point to the next element which is a non-zero element and element which is a non-zero element and element which is a non-zero element and so we can write it to the position where writer is pointing to this case is pointing to the first position so we just write it here and we move the writer to the second position so this will be called uh one and this will become one and then we move the picture to the next as you remember it's just a for Loop we move it to the next uh to the next element which is a zero again so nothing interesting is happening we move it to the we don't move the r writer we just move the iterator to the next element which is three so we can write it to the power to the position where the writer is pointing to in this case the second position so we just copy it over and we can move also our writer to the next position so we do the same for the 12 because it is the cell pointing to uh the last number and our writer is now pointing to this element and but we are at the end of our array the interested pointing to the last Outlet of the array and to finish up the solution we just have to copy all the zeros that we had and that basically means just filled the rest of the array with zeros and that's basically it in this case where we'll have all the non-zero elements in the front and they non-zero elements in the front and they non-zero elements in the front and they will also keep the relative order let's move to the coding part first we will initialize our writer pointer uh we'll initialize it so it can point to the first location first element of the array now to represent our ether from the example that we saw we will just use the plane for Loop and the I that's declared inside the for Loop statement will represent our iterator which will basically just iterate over all the elements of the array next we will check if we if the current element that the director is pointing to is not zero in that case uh it fulfills the requirement to be written and the position where the writer is we're currently pointing to so we basically just do that we take the current element of the iterator is pointing to and we just place it to the position where the writer is pointing to and we finally increment the writer to move it to the next cell so if we can prepare for the next non-zero element next non-zero element next non-zero element after we reach the end of the law we just have to fill the rest of the array with zeros we do that by incrementing all the way incrementing the wire writer all the way to the end of the array and each time placing the zero the space complexity is constant because we are doing all in place all operations are bad in place while the fertile complexity we just basically have a simple four Loops that tribute the polar array and that means that the tanglebox this linear
|
Move Zeroes
|
move-zeroes
|
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
**Note** that you must do this in-place without making a copy of the array.
**Example 1:**
**Input:** nums = \[0,1,0,3,12\]
**Output:** \[1,3,12,0,0\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you minimize the total number of operations done?
|
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
|
Array,Two Pointers
|
Easy
|
27
|
1,930 |
hello everyone and good morning to all of you today we have problem which name is unique length 3 paric subsequences lead code 1 1930 problem so before going forward in this video please make sure that you have liked and subscribed to this Channel and also it's my advice to all of you that please read the problem and uh try to build up the intuition for this and uh try to do the code also it will be beneficial for you and if you are beginner then definitely you will St at from point uh then you can see this video and do that do the code okay let's read the problem statement we have given a string we have to return number of unique PS of length three okay this is important L for this that are the subsequences of S note that even if there are multiple ways to obate the same subsequence it is still only counted once it means if I can get the Same subsequence by using the characters of different indexes then I will not increase our count will be the same okay so a pendum is a string that reads the same forward and backward okay it means the same characters will come okay just like AA Abba like this okay a subsequence of a string is a new string generated from a orinal string with characters deleted without changing the relative order of the remaining characters Let's uh see the example is a b CA so I can get the subsequence like a that can be the one sequence for this let's open this and also I can get a B A and also a CA it means I have to find the number of unique characters in between of them a so I can get the number of unique characters by using an order set so that problem is solved so the ultimate solution is I have to find the unique characters for in this so let's see the approach for this so I can see that we have to return the three length subsequence like first and last index be same and middle index can be different or same also so let's see the example if I have two pointers I and J so I is indicating the first index and J is indicating our last index so first and last index should be same for the pantropic subsequences so I have to find the number of unique characters so I have to find the number of unique character in between of the I and J so I can find this by using the unorder set so this problem is resolved now see this we have this subsequence this a string and uh our index is starting from zero so I can create a map and uh I can make a pair like Z starting index and that is first is showing IND starting index and second is showing the ending index so we can see start starting index is zero and ending index is four so 0a 4 so I will see the in number of unique characters between 0a 4 that is one the starting index is one and ending index is three so this will be a b c so our answer will be three so let's see the code for this so firstly I will what I will do I'll create an ordered map of character that first is character and second is a pair of inter comb type that is showing a starting and ending index for the particular character int comma int MP now what I will do I will initialize the all the characters with initially minus one - one minus one - one minus one - one starting and ending IND 4 four care CH = to four care CH = to four care CH = to A2 CH is less than equals to Z and uh CH ++ map of that particular character is ++ map of that particular character is ++ map of that particular character is equals to minus one is starting in the X and minus one so it is done now what I do if that particular character like you can see I will initialize I and J so what can I do is for in i = 0 to I so what can I do is for in i = 0 to I so what can I do is for in i = 0 to I less than S do size then i++ and I will check if map of size then i++ and I will check if map of size then i++ and I will check if map of that particular character let's initialize a character in scare CH equals to S of I if that particular character do first I am initializing the first Index this first that is indicting the intej if equals to minus one then only I will change our index so it will be map of that character Vector do first equals to I and same for the J also so for in J = I and same for the J also so for in J = I and same for the J also so for in J = to S do size -1 2 J greater than = size -1 2 J greater than = size -1 2 J greater than = Z and G minus and uh same for this also SC CH equals to map of that particular J so sorry this will be S of J and I will check if map of that particular character do second because that is showing the ending index = to minus1 showing the ending index = to minus1 showing the ending index = to minus1 then only I will change our character so map of that character index equals to J now I have initialized our I and J now what I will do I will added the whole map for auto it belongs to map and I will check care what I will check I'll take uh I can take a character equals to S of it this I have taken so I have to find the number of unique characters in between of starting and ending index so I can inze in start this would be it do sorry we got that is denoting the our character so it. first is our character and in starting index equals to it dot second. first do first and in and equals to it do second it. second. first means it this is a in this iting the whole map and it. second. first means I in pair and that is showing the this int index starting index and it. second do setting uh second is showing the ending index list be ENT so this is done now I can create unordered web unordered set for finding out the number of unique characters in between of them so unordered set of in type SD now what can I do is for I can add from in IAL to start + one to I less than start + one to I less than start + one to I less than end because I have to find the number of uni in between of them I will not take the I less than equals to there and so I ++ now what can I ++ now what can I ++ now what can I do St do insert of I and finally I can store in this answer so let's create answer in answer equals to zero answer plus = to St do zero answer plus = to St do zero answer plus = to St do size and finally I can return our answer so return answer so let's run this and see yeah line number seven this should be only one line number 12 should be this line number 12 map of character do this is perfect let's this doesn't wrong let's see what is the problem this map of character = minus1 - character = minus1 - character = minus1 - Oneal to this it. second. first it. second set I cre this actually the problem with this should be to let's do this equals toal to and this should be S of I because we will posture the character into the set now let's run this as you can see it is working perfect let's some this so now time and space complexity you will find and write the com in comment section and if you find this helpful then please like share and subscribe
|
Unique Length-3 Palindromic Subsequences
|
maximum-number-of-consecutive-values-you-can-make
|
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is a string that reads the same forwards and backwards.
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.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "aabca "
**Output:** 3
**Explanation:** The 3 palindromic subsequences of length 3 are:
- "aba " (subsequence of "aabca ")
- "aaa " (subsequence of "aabca ")
- "aca " (subsequence of "aabca ")
**Example 2:**
**Input:** s = "adc "
**Output:** 0
**Explanation:** There are no palindromic subsequences of length 3 in "adc ".
**Example 3:**
**Input:** s = "bbcbaba "
**Output:** 4
**Explanation:** The 4 palindromic subsequences of length 3 are:
- "bbb " (subsequence of "bbcbaba ")
- "bcb " (subsequence of "bbcbaba ")
- "bab " (subsequence of "bbcbaba ")
- "aba " (subsequence of "bbcbaba ")
**Constraints:**
* `3 <= s.length <= 105`
* `s` consists of only lowercase English letters.
|
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
|
Array,Greedy
|
Medium
|
330
|
1,035 |
hey everyone welcome back today we are going to see problem number 1035 uncrossed lights first you will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I have the first example from the Liker website so here we are given two input arrays nums 1 and num2 and we need to find a connecting line from an element from num1 and num2 right so we can draw a line if two values are same in my num1 and num2 so here one and one are same so I can draw a straight line so in this case our starting point of the line will be from num1 from this one right we always consider the num1 as the starting point so here one and one are equal so we can draw a straight line here next here we have four and I can also draw a horizontal line here since we have 4 in num2 as well and there's also an condition so here we have two right so here we have 2 in num1 and in num2 also there is two so we can draw a line here also this is also valid line but in this case this line what we are drawing here is intersecting the 4 and 4. since it intersects the 4 and 4 connection we should not draw a line here right we cannot draw a horizontal line here so we will be done with the input array we have to return 2 since we can draw two connecting lines so the aim of the problem is to find the maximum number of connecting lines right so to solve this problem we are going to use a dynamic programming approach so now we will see how we are going to do this so initially we will be taking the length of nums 1. and length of nums 2 right so here M represents the length of nums 1 and N represents length of nums 2 then we have the dynamic programming array with the list of zeros so we have initialized by taking the minimum between M and M plus 1. so we have taken this particular value to create the dynamic programming so in this case so the minimum between M and N is 3 and plus 1 is 4 so we have four zeros here so here M and N are both are three right we have only three values in both of them so the minimum between them is three only the reason why we are taking minimum between M and N is that we will be having less space and we will be able to handle all the cases right so here we will be writing two for loops so the first for loop I where we will be tracking the first input array the nums one input array right and this Loop starts from 1 to M plus 1 right where m is the length of the first input array then we will be having a variable previous which will be initialized as 0. then we will be writing the second for Loop where it starts from one again so this will be helpful to track this second input array right and we will also use the J pointer to update in the dynamic programming array so inside the second for Loop we will initialize the current maximum scene crossed lines at this start so we need to look the dynamic programming array and we will use the J index in the dynamic programming array so here J is 1 so in the first index it is 0 so we will initialize the current maximum seen crossed lines as 0. so now we need to check the two values in the input array so where we will check the I minus 1 element in the first input array so here we will check the I minus 1 in the first input array so I minus 1 in the first input array is 1 right and J minus 1 in the second input array so J is also 1 so minus 1 will be 0th index so in the 0th index in second input array it is 1. so now we need to check whether these two values are equal or not so when these two values are equal which means I can draw a line so I will update my jet index in my dynamic programming array as previously seen maximum crossed lines Plus 1. so here the previously seen maximum lines are zero so plus 1 so this is our first connecting line so in the jet index in my dynamic programming array I will update as 1. now I will update my previous pointer that is previously seen Maxim connecting line so here previous will be equal to the current so now I will update my previous pointer as the current pointer since current is 0 it will be 0 1 so now our J will be increased to 2 right so now again I need to update my current pointer that is jth index in my dynamic programming array which is nothing but 0 so we don't have to do anything here so now we need to check the I minus 1 value and J minus 1 value so when the values are not equal we will keep the maximum connecting line seen so far as the answer for the JP index in my dynamic programming array so we will be taking maximum between the J minus 1 value in the dynamic programming array so J is 2 minus 1 will be the first index that is 1. and the current value right since the answer is 1 here the maximum between 1 and 0 is 1 so index of my dynamic programming array will be initialized as 1. so we are just initializing the previous T scene connecting maximum lines right since we are updating 1 here our current pointer will also be 1. since we are initializing the current pointer as the jth index of this start right so since we are changing 1 it will be changed as in place so my current pointer will also become 1 right so then I will update my previous variable as current pointer that is 1. so now our J will be increased to 3 then we need to update our current pointer which is nothing but the jth index value that is third index J is 3 so third index in my dprd is zero so current will be zero now so then we need to check I minus 1 value in the nums one input array and J minus 1 value in the num2 input array whether they are equal or not so here I minus 1 is 1 J minus 1 is 4. since both the values are not equal we just need to keep the previously seen maximum connecting lines so we just pick the J minus 1 value from the dynamic programming array that is 1 and the current value that is current index value which is nothing but 0 and we need to take maximum between them so we are going to have 1 so that I will be initializing it for the jth index in my dpre right so since we are updating in the jet index in my dynamic programming array it will change in the current variable as well then we will update the previous pointer as my current variable which is nothing but 1 again then we are done with the second for Loop so we return back to the first for Loop we will increase our I by 2. then we will reset the previous pointer as 0 then we need to restart the second for loop as well that is from 1 to n plus 1. so if I keep on doing this we will end up having the maximum connecting line at the end as 2 right so the time complexity for the problem is order of M into n and space will be minimum between am and N right which we use for the dynamic programming array that's all the logicals now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so here we are initializing M and N by taking the length of num1 and num2 then we will swap the num1 and num2 if num2 is greater than num1 since we need to draw the connecting line from the first input array right so we always keep the first input array as the maximum length array right so in order to handle the edge case if the length of the num2 input array is greater than the num1 we are just swapping it and we also swap MN as well right then we will be creating the dynamic programming array of list of zeros at the start the reason why we are not taking minimum between M and N is that we are already swapping the input arrays right so obviously n will be the minimum length between num1 and num2 right then we will be writing the first for Loop to keep track of the input array of num1 then we will be initializing previous as 0 then we will be writing second for Loop to track the num2 array right and we will be initializing current variable as the current value in the jth index of dpra then we need to check if the value in num1 and num2 are equal we will update the maximum previously seen connecting y by one and we will update that in the jth index of my DP array right else I will update the previously seen maximum connecting lines by taking the maximum between current and J minus 1 value in my DP array then I will update my previous pointer as current pointer then finally I will return the last index in my DP array right that's all the orders now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
|
Uncrossed Lines
|
cousins-in-binary-tree
|
You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return _the maximum number of connecting lines we can draw in this way_.
**Example 1:**
**Input:** nums1 = \[1,4,2\], nums2 = \[1,2,4\]
**Output:** 2
**Explanation:** We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from nums1\[1\] = 4 to nums2\[2\] = 4 will intersect the line from nums1\[2\]=2 to nums2\[1\]=2.
**Example 2:**
**Input:** nums1 = \[2,5,1,2,5\], nums2 = \[10,5,2,1,5,2\]
**Output:** 3
**Example 3:**
**Input:** nums1 = \[1,3,7,1,7,5\], nums2 = \[1,9,2,5,1\]
**Output:** 2
**Constraints:**
* `1 <= nums1.length, nums2.length <= 500`
* `1 <= nums1[i], nums2[j] <= 2000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102
|
725 |
Hello Hi Guys Welcome At Least Three People Doing The Soldier's Problem September Challenge Its Play List Part Plus To The Problem British Sexual Speaker Latest Tips And Avoid Okay To Given Her Lips And Teachers Play List * Quantity List Subscribe Now To Parts Puberty With U That World Let's Come Parts Been Also Apart Improve 9th Fact Proven Input List Parts According Earlier Part Securities Size Grade To The Next Good Only Then Return Are Of Parts So What Is Mean Profile Link Least One To Three Benefits Play List In Five Parts Mist is first fluid part and subscribe maximum possible different parts of the world just before after split into please like this is this third you and fourth part plus channel subs are least one place to another world believe this point to you but leaders not for international the So this Vansh Latest Example for Example to Understand and Quick Want to Listen According to Share MP3 Done Requests on Subscribe Tab Less Into Three Parts How Can I Do It I Can Do Something Like This Steve 1234 First Part Second 567 Third Part 2893 Hey Difficult Front Part First Part Plus Size Greater Than A Little Bit Channel Torch Light Distic Notes Printed Like This One Two Three Over 45 to 60 Developed Not Falling The Question Subscribe Toe's Rate 102 Jhal A Senior Par Stop Water Will Do It Will Find The length of the list is the length of the list length Google assistant sleep from it play list it's possible at each part subscribe to have eyes like subscribe it's eyes want to see is to isi Arvind leave length button bike 300 tennis not exactly divisible by 3 so Will Have A Reminder To Top One Extra No Dignity And Notes Ruby In The Question Parts Akram Ali Subscribe Button And Two Parts Mid Length On Subscribe Like Subscribe And Radhe Uda Vasai Answers Life But Istri Correct Points Ka 10 One Should Not Be Tried To Explain Notes In The Liquid Tried To Gifts In The Field Of Hai To Batan Singh Gill Half During His One To Three Left Parties Of Fighters 300 Will Give At Least One To Three Languages To Give They To Know And Varun First Page Number 90 Minutes Will Have Eat That Now How Do You Do Part Interlink List Wishes Next9 Ik Shab Screen Only Are Needed To The FlashLight On Question Now Will Be Easy How To Celebrate The Input Least In Two Different Parts Lakshmi Teacher 12321 Next Point Chronic Pointed To One 457 380 Will See What's The Part Subscribe To Hai To Aansoo Na Zurich Clear To So Mussoorie Share What We Do Ideally Should Ideally Specific Short Notes Okay So Vighno Don't Know How To Use A Node In Vwe Tuesday Time Will Not And Will Not Do Any Part Of Delhi Will Not Be And Will Not Give Voice To Not Only This Is Another 5000 Flats And You Want To See The First Cartoon Channel Subscribe Or Like This A Source Of Cost Part Vikram Bisht Much And Second Part Body Something Like This Cycle Also Onion One In This Process Possible So What Will Doob Veer Will Take 2016 Node 1251 Not Doing So Will Give One Node And Come Here Comes The List What Do Subscribe My Channel Here Deposit Internal Ayushman Yoga My Point Appears To Be R Next PM Of Start And Make New List From Clear To Concept Previous Pointer Current Pointer Will Play A Crucial Role With Me To Your Previous Pointer To The Way Amir Way To Make The Way To Make How To Make Your Previous Pointer Appoint Channel Subscribe If Important C &D Okay &D Okay &D Okay -Okay But Heart Attack Another Example Ansh -Okay But Heart Attack Another Example Ansh -Okay But Heart Attack Another Example Ansh You Now So Related Also Like This Song Very Significant Two Three I Will Take Care Is Equal To 4 9 Pimple Two For Land Distant Voices Of Which Parts Of Speech Part Will Be Easy 0 Setting Of To Reduce Minute That Pranav Length Fiction Tabs Equal To For What Is Land Of Each Part Time Before It's Too Right To And Half Inch Part But What Does Not Have Any Extra Notes Will Be Tamed For What Does Not Know What Will U Will Start From The Hidden Old Okay And Travels Until And another parts of but its share after are at a greater part size veer 549 of making list and share will not be listed in one successful and years will take one extra knot and make twist fennel bombs new list that your own this One list that is similar from where to start now and school Vikram and list a main to anmol space and 5 to 6 channel winner list hum trio extra notes all weak so one should not be too kheer one action or visit to clear extra notes have changed from 120 9 And Remaining Parts Will Be Of Size Chest Size The Seventh Month Not Solve Its Play List * For Part Sach Debit The Prevent Is That * For Part Sach Debit The Prevent Is That * For Part Sach Debit The Prevent Is That Size Greater Than Or Equal To The Later Part Of So This Is Basically The Meaning Of Solving 10 Code C Si ki aapke achha to ok br given this function where given her daughter in Christ and k fufa calculate the length of the list singh to the function at single point and the length of the channel subscribe k notes are always silent mod of ki Lakshmi make extra notes will have gaze at him the answer and make current no dance class previous nod a wild head latest bridal wear established its eyes will be equal to the fast size tube calculated and oil flower and answer about answer current is starting of Every part of every part of this revolution to the same way end of next point subscribe channel like comment subscribe mode turn on it's time we are the most important party where torch light we need to make the end of every part point two Null to-do list part point two Null to-do list part point two Null to-do list senior distic us point internal fennel bun hair previousnext null new hairdo point note current work after three layers current affair setting off setting of the next list subscribe example 1234 on the likes of this time it is the list and physical 500 And run the list Aishwarya and the answer is like this is the parts of the two parts Nalla do the left and doing year until our answer size Note the remaining value is going to win all decisions for the condition when the length of the list is loop example To-Do List Channel Subscribe One Myth The Final Submit Is Running You Are At The Key Soumya Take More Examples Where Are You Keep Changing The Volume One Care 6 Care Skin This I Want To Feel And Liberation-in-Life And Liberation-in-Life And Liberation-in-Life Button Share and subscribe the Channel Motivational Videos and Subscribe to
|
Split Linked List in Parts
|
split-linked-list-in-parts
|
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50`
|
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
|
Linked List
|
Medium
|
61,328
|
266 |
hello everybody this is a male with another cognitive preparation video for you and this time I'm going to show you this problem palindrome permutation so given a string determining if a permutation of the string could form a palindrome so they give you a string and can you rearrange it such that what you get is a palindrome remember that a palindrome is a stream that is the same forward as it is backward so for instance here you have the string code you return false but here you have a B you return true because you can rearrange it to make a palindrome so you can say a B a you can put a B here and the a at the end there will be a PA and from back a BA so how can you solve this problem there are multiple ways to solve this problem but I'm going to show you my favorite way to solve it which is very efficient so the main property of a palindrome is that at most one character can have odd count so every character has to be even count in the string has to appear an infinite number of times for instance here you see that a appears twice and B Bobby only appears one time so at most one character can appear an odd number of times so if you pay attention to this observation you realize that if you check this condition that at most one character appears an odd number of times if that condition is valid and then that's going to tell you if it is a permutation of a palindrome or not so how can we do this we can use several data structures we can use us a set or we can use an array put in or a hash map but in this case and when I use a beat set so a beat set is like a set but it works at the level of bits so it is more efficient you can save a lot of space because you're dealing with the bits so what I'm gonna do is that I'm gonna go through the string from left to right whenever I see a character I'm gonna flip it so the position of that character is gonna flip it if I see it again I flip it back so by the end it's like a light switch if you turn around and turn it back off so if you think of a number of times the light switch is cannot go back to off so first it is off but if you - okay you CNA it's gonna be but if you - okay you CNA it's gonna be but if you - okay you CNA it's gonna be on you see another is gonna be off so there should be only one that is on if it is a palindrome and we can use a class in Java the bit set class to check that the cardinality is less than or equal to one so without further ado I'm gonna show you the code so first if the reference is no I can return false because this is no this is not a permutation of a palindrome okay so I'm gonna need a big set be s there's a value of new bit set of 256 this is the size because remember this is for extended ASCII since I'm only dealing with characters a to Z I can use 256 positions and then I go for charge C in s that to char array so I go from left to right and whenever I see a character in the string I just flip it in the set so initially the position for s gonna be off is gonna be 0 when I see Na is gonna be on FC another a then it's gonna be off again so that tells me it is even but a B it will be on because it is odd so by the end if I find that there's only 1 or less than 1 that is on then I know this is a palindrome permutation so when I say they said flip C and then just return is the cardinality less than or equal to 1 so this means there's at most one character with odd count if that's true if this is true then that's gonna be true if that's false doesn't it's gonna be false so let me run the test compiling accepted false expected false now I'm gonna submit accepted okay so thank you for watching please like the video don't forget to subscribe and happy coding
|
Palindrome Permutation
|
palindrome-permutation
|
Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_.
**Example 1:**
**Input:** s = "code "
**Output:** false
**Example 2:**
**Input:** s = "aab "
**Output:** true
**Example 3:**
**Input:** s = "carerac "
**Output:** true
**Constraints:**
* `1 <= s.length <= 5000`
* `s` consists of only lowercase English letters.
|
Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
|
Hash Table,String,Bit Manipulation
|
Easy
|
5,242,267,409
|
1,926 |
all right welcome to my next newest video where I'll take you through my process as I solve a random elak code and I'll walk you through my approach to seeing it for the first time and then um afterwards I'll walk through the Optimal Solutions afterwards so let's begin let's choose another medium the last two have been disasters but let's go again oh no looks like a graph problem already all right nearest exit from entrance in maze you are given an MBI and Matrix maze with empty cells represented by dots and walls represented by pluses you're also given the entrance of the maze um H where entrance ah yes the entrance is the row and the column which is where we initially start in one step we can move one cell up one cell down one cell left or one cell right you cannot skip step into a cell with a wall and you cannot step outside the maze your goal is to find the nearest exit from the entrance an exit is defined as an empty cell that is at the border of the maze the entrance does not count as an exit return the number of steps in the shortest path from the entrance to the nearest exit or minus one if no such path exists so in this one we've got the maze um and the entrance is at 1 two so 0 1 012 there we are Co safe with the mask on for whatever reason and there are three exits one there and one there we can reach that one by moving I mean this one by going left that one and that's the closest one all right similar for this one except we cannot count the starting the entrance as an exit in this one there are no such exits all right so straight away it's shortest path problem um each shortest path BFS is straight away calling out to me um where it's just the number of um edges that we cross is the number of steps so shortest path from entrance to an exit not including the BFS yeah think that's a good idea um so what we do what we would do I think is yeah just to BFS um check each cell check if each visited cell is um exit oh wait hold on BFS I can't remember this BF FS find do you have to I think you have to complete BFS to find the shest PATH yeah I think I'm not sure if it's different in this case though um oh dear um I guess if it is Market has the wait yeah how you oh dear do you need a target for BFS H oh dear can do BFS where the target is any exit cell and so we can check um if each visited so is an exit if it is Mark as the end I think that's where you have to return the distance um if no exits are found after BFS turn minus one okay so what do I remember about BFS I know use a q um q and starting at the start uh soell we I guess we push it NQ it we NQ is neor oh I don't remember um res distance to Z and NQ its neighbors maybe um oops oh wait no so we've got three we've got discovered yeah undiscovered we've got um discovered and processed um you have to keep track of discovered and processed cells and we use a key and then power so start at the initial starting cell um oh dear Market discovered and do we Market is processed because there's no negative weights or anything um or do we have to do count it as processed when it's outgoing edges I think we marked it as processed is there an Undiscovered do you keep check up undiscovered um not sure um it's on the tip of my t um add just um just add starting q and then we can do po off oh no for each cell in the que we put off oh no not D DQ it and then we mark it as discovered No it should already be discovered um set to and process is it processed when you process its neighbors or process everything going to it I don't remember anyway we DQ it prach cell in the qbd Q it um do we add do we it unded NE maybe um should we also use parent Maybe I don't know what if there no it doesn't know if there's two parents um oh I don't remember I need more practice FR so in the Q we want to DQ it in NQ its discovered Neighbors when do we process the edge fruit cell and yeah so the cells that we care about are only those that have a plus if it's a DOT they don't count as neighbors or anything and inur it's discovered Neighbors how do we keep track of the distance to each node to each cell do we even worry about that so in the Que process Edge I remember there being a process Edge somewhere um if it's um processed is that correct oh and do we have I don't even know if we have an Undiscovered thing or we just keep track discovered maybe we only have a discovered process s explicitly we can implicitly figure if a so is undiscovered it's not in the discovered array H and then after it's empty after Q is empty then what maybe we do keep a distance um thing maybe track of distance use an M Matrix where um distance and or distance um i j is the best is the shortest distance to maze that makes sense to me that makes sense I think um so process Edge that might just be if um distance how do we know which so we're on maybe uh Q uh are they called like doubles umented by um it's like the entrance just like that represent is column sort of like that maybe um so if distance um something like this maybe hopefully we can do like yeah just to make it a bit easier so if distance s colum um hold on I'm stuck I might be I think I might be getting mixed up with BFS and DTR algorithm let's get paint up so we start there and then we go there and like that and they're unweighted oh yes I'm getting confused so we start here whoops start at zero one just number these and so we are at zero oops zero yeah I think we use a parent array and we just count the number yes no we have keep track of the distance because it's is unweighted keep track of parents of each cell um parent of starting set isus one parent H cell is the cell that discovered them at the end I'm not sure at the end um cute undiscovered neighbors add oh I'm so confused Mark is processed I think that's fine and then after the que is empty we want find shortest path from exit to the start parents array so yeah say we end up with parents equals is 58 um so that's these is the indexes underneath so and say um exits are cells three and one so oh one and three just so we know what the exits are which we can find pretty easy by just a quick scan through or we can keep track up here maybe um but so if xit uh at cell one then we see here that the parent of one is four and the parent of four is one so then we can't get there from zero so we can't do anything the parent of three is five and the parent of five is zero so the shortest part is zero is where we started so the shortest path is what's that two steps because we start at zero and we go to five and then we go to three yes and then after that we go to two doesn't I think that should be right I'm definitely missing some very important details in the bulk of the BFS um I think hopefully that's that'll give us a good start at least so what's the time complexity um oh I don't remember what BFS is it might be vertices plus edges but as the worst case is we have an N byn um Matrix and that all cells and we will have to check them all at least once is it um I'm not actually sure right now is it that I'm not sure M by n² which no that cancels does that um I think M plus n is that right and then after that is linear time to check that so that won't take long I think it's m byn squ I think space complexity is the number of cells we have which is also M by n CU we have to add them we in the worst case with the real sales you have to add them all to the CU all right this is a tricky question for me probably not that tricky if you're used to BFS but let's just try um well we need how do we do how do we make a vector where each thing is like a double like a maybe just 2D Vector um parent so parent AR I draw that so the parent array would be like this but um the cells are named by the M and N so it would be like this is oh what am I doing no I think that's right oh wait no yeah it's not 3D though so it's just like that so that's one cell and then you've got maybe the cell next to it just like that so that's what I'm going for with the parent um and then we want F the same way I guess we can put it up there it's processed no it's one c one C I think um when we need BFS which will take in the Maze oops I'll take in the Maze and does it need the entrance oh I remember I highly think it does I think it yeah I'm pretty sure it does what would it be in I don't think we need to pass it by reference um but we do need these ones I think by reference or no we're in a class so those can be like global I think um so pretty much just cool BFS on these entr and then do that after maybe oh you might do that in BFS I'm not sure um yeah I'm going to get I'm going to definitely mess this up but let's just go for it so yeah um parent at um entrance I entrance oneus one is that work that of entrance cell to1 BFS oh and add it to the Q what kind of is it a different queue or is like discovered the key that with I'm not sure no let's just call it Q might mess with up no key is not affected is it oh how do you use a key I'm not sure hopefully that's right so what we do and then we do cell Q doq um entrance maybe could we I just have that as entrance let's just see if we get an error just return minus one for now return nothing there see if we get an error this part no there at the very start because I forgot okay can you not do that well I would have thought maybe you could oh I'm allowed to look it up how to use a q um reference qu Q just a normal Q we want oh it's not in let's just push so's see if that works what is the problem with that one how do I can't be stuck here can I oh dear can we just to that where's the problem ah so it's here so how can we do that reiz resize I don't remember how to resize itbe so if we want to resize it how they do oh there's two so what does this give us gives us three which is just not quite what we want I'm stuck I forgot to run the timer oops been about 35 minutes H I don't see why it wouldn't work I see why this would work I mean this wouldn't work but if we do like oops let do parent do push back entrance I don't even there parent if we're doing it this one time it should hopefully work no see I might have to somehow refer to each cell by a number instead of a vector what's wrong with that ah CU entrance isn't the index we want the index oh dear I'm not sure I really don't know let's just try to write I don't know if it's a good now it's not a good idea to try to write the rest of it without dealing with this first what if so we get M = length and not sure if that's helpful just test that size it' be easier if I could read this size it' be easier if I could read this size it' be easier if I could read this one better so is that the first one yes so it's the 3 by 4 n i mean M yeah M by m 2 by three and one by two oh we got that one right good job okay so now that we've got that um I don't know I think I am being a bit silly we don't have to have these AS Global variables because BFS um doesn't isn't necessarily um per cursive so I think we can have this stuff in BFS and then we do in oops not visit visited oops excuse me okay and then we need a q that okay and then so that's think we would I'm so lost [Laughter] um we get we've got the Q and then we get Q push entrance does that work so far no errors no oh yeah do that okay no errors empty not empty we do equals see in the key pop three um do that do we get access to that um where is I want is it front and then pop maybe that's what it means equals Q front and then we do Q all that work then not work but give no errors good no errors so we pop it off the Q and then we want to um make sure it's visited so we can do visitor push back Carell I think believe that should work um so off next cell the to as liards visited and then we want to do we need to do any processing and but then after that we spot Neighbors now how can we find the neighbors of a cell it would just be one above it left of it below it or to the right of it which is not a DOT you can't go diagonally no so we can do a um a function maybe so if we Neighbors given a I think that's We need oh I'm a bit L we need the maze don't we in cell so we do vector um what the word I just I'm tied for some reason and that's empty the start and then we just do um we can do in car J and then we just do if ma doesn't equal and a DOT do a bad right no plus it's a bad then we just do Neighbors push back that one neighbors copy and paste that four times spech Direction and then just do this oops i j and then I + one I wait yeah hold on J + on J + on J + one IUS one and Jus one that will check um uh thingies I suppose any issue is if there an edge case um might be a bit tricky oops I just need to do that probably not the fastest way but all right that I believe that should work do maybe we have to check if they're not no as well something like that have make sure there oh yeah so maybe just instead of doing is plus do I mean isn't plus do that might be better um okay so do VOR find NE B hopefully that's all we need and then for each neighbor we have to add it to the queue if it's not visited I think H for I know there something you can do you like Auto neighbor nebor something like that let's just test if I know how to do it if neighbor I don't even know if it's in the visited um thing on the vector um right dear can you not do that uhoh if it's not in neighbor I mean not in the visited um yeah what if we use like a set find okay so said if we use a set that be better and then to add it to the set we have three have to in place because there's no um no push back or anything to maybe I don't know um and if NE I'm guessing find or return or count maybe um zero one Zer yeah so if okay if count no if visited cat neighbor then we put it in there and then we also add it to the Q is that do we need let me see if there's any errors I expect there will be okay what that push back maze because why can't we do that if it's a vector why can't we push that back it's a car no oh dear maybe it's something like that I have no clue oh no something that just do like a c let see if this one works before changing all of them okay good that looks like a good sign hopefully this wants to work I have no idea what that means and where that issue is all right maybe the issues down here if we just remove that what happens no I don't know oh dear um let me see well we should pass these by reference as we so we just have to copy them because we're not changing them um where could the proper be okay h interesting guess we going have to do that if we do it the neighbors not good this part I do feel dodgy about what if get rid that and that oh no error so the error is in this one why could that be how could that be I don't know maybe have to do Edge bound checking here um maybe I + 1 we have to make sure that's maybe I + 1 we have to make sure that's maybe I + 1 we have to make sure that's less than n otherwise out side and then here we have to do J + 1 side and then here we have to do J + 1 side and then here we have to do J + 1 less than n otherwise or outside and then the Opposites i+ one outside and then the Opposites i+ one outside and then the Opposites i+ one is that ch now does it like that it get somewhere to be fair no here we go we want these um so I guess we can just pass them in let see why not okay now we are getting somewhere return one though so we're not quite finished so what I think maybe we need to process something I reckon we need the parents array back but it wouldn't work before so maybe we can use a um like a map um yeah so like the index now CU yeah so it works like the vector SLE I showed before but the index and key are the ones that look like this I feel like this is over complicating things I'm not sure don't need to come in there yes and then add cell um is that right I don't is it the other way around the index oops what all right what I do that for I've got it up here as well oh no I did it wrong I put that in the wrong place oh was that comma is that better what's the problem Vector int why does that not work's wrong with that I don't understand what the issue is what I'm going to be honest I have no idea how to do this question and I might have to start looking for help online all right so let's get this up and just try to do this so if we just put that on the side go here and we just see what chat GPT does and see what we can learn all right so they got this up here which I had I know they have it all in the nearest exit they have whole BFS thing here so maybe they don't even have any helper functions so that's what they have a thing of directions too guess we can have that this counts as another failure unfortunately okay just copy that and then they make a cube but they use pairs that's what I should have done I reckon I have never seen that done before so that's probably why and then we do I see so pushing the whole entrance so we push entrance yeah they do it like that makes much more sense one all right and then ah we set the entrance as a wall so we can't come back on it right and then we just count how many steps we've done so while the Q is not empty what do we need the size for interisting why do we need this oh the size of the Q is and then uh for the entire Q I think doing that's fine um we pop off the next cell but a little different to how I was trying to do that which is annoying uh yeah and then we do if x isn't ah so if we're not on the exit I mean if we're not on the entrance um yeah so if we're not on the entrance this is annoying and we're on an exit I see and if we're on an exit not so much how was up to that poet and then we just oops return the number of steps we've done um otherwise we do that really direction direction up there NX = X okay so what does that do is that a new X yeah I see that's so that's the new direction we're going and so then maze NX and NY will give us a neighboring cell and so I'm guessing this means if they're in bounds yeah if that above zero yep if they're in bounds and we're at a blank space or an empty cell then we push the mine and we set ah I see we set them I guess yeah we set them as a wall That's the way our way of setting them as being um discovered or and processed and then after that we increment steps I don't actually know what doing the plus first does otherwise we return minus one now let's see if this works oh I have to delete all this what's wrong with that um aess key of course ah see I was pretty close I the general idea but not quite good enough let's submit that and look at some of the other Solutions see if there's any better ones um oh it's very space efficient I guess that's cuz we don't use the visited and processed and whatnot um arrays here okay so you be pretty SP efficient but not as quick as it can be apparently um so let's what's this mean analysis um BFS solution so that's what they got pretty much the same thing it looks like yes I see so marking it is visited is the same as marking it as a plus as a wall y so that's exactly what theyed okay so this is the optimal solution it looks like or pretty close at least um yeah that's a very messy and not welln named variables in this one um or maybe it used to be called it couple years ago s millisecond the same how's that so much faster than this one oh well there's another medium that has beaten me I mean I got the general idea of what I what the correct thing was to do except yeah keep track of the parents we didn't have to do that actually um keep track discovered and processed we only had to keep track of the visited ones I think I got mixed up with D or DFS one of those ones use a parent array we didn't have to do that use a Q yeah we did have to do that c have doubles I don't think it's a real term I think I meant TBL but um a pair that's what they did that's what I was supposed to do um set starting set yeah add to yeah that's correct DQ and key them to parents no mark them as pre no mark them as visited and also check if they're an exit if they are um no not yet yes for each so in the que first if you check if there's an exit and then keep track so keep track of the um steps this whole way for each time we pop something off the que I think um yeah well it's not empty we what do we iterate where do we even use I gu we just have to repeat it oh that bits a bit confusing why do we have a loop there h that's a bit weird what happens if we get rid of that I'm not sure why that is there no it doesn't work let's ask wherever chat GPT went um what is the purpose of the for Loop inside the Lo um a levelwise Traverse with maze oh it's a bit confusing so what is a normal BFS look one can C++ do they have that Loop um no so that's a bit confusing um is it required it is required whoa this just repeating that okay I don't really understand it I think maybe that's why it's a bit slow H why do we need that so do we need the while thing um we need the I would have thought it did a similar thing do need bre yes not so that sounds DFS am I wrong because we po one that out and then do we get the breadth of it sounds like we're going all the way down whichever one oh no I'm just confusing myself I don't trust this now I trust chat gbt but that's what it feels like it's doing like it's popping them off and then going all the way across all the way to the edges and not going one by one and then one by one like a normal BFS I can't read the editorial or was the discussion is what's the hint say BFS I did that I got the hints I should probably use the hints when I'm stuck going straight to chck TPT all right if anyone can tell me in the comments um what that whole full loop thing for does anyone else use it they do ah no because the size of the que I thinking the size is the size of the maze which makes no sense it's the size of the Q so it explores all the adjacent um cells which haven't been visited yet but they've been discovered so here it will happen once and it will push at most four of those ones on and then I'll do it again and again okay I think I get it just sounds like it's doing the depth thearch a bit but I can't really remember well yep anyway this was another failure another defeat a medium has defeated me once again who would have thought I'm not very good at these but hopefully I'm getting better um anyway thank you for watching this um this new painful video and sure it was painful to watch but thank you very much anyway for watching uh leave a like if you somehow enjoyed comment any feedback you have or any help that you think I might need probably a lot um subscribe for more all the good stuff and I'll catch you in the next one all right thanks
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
342 |
hey this is Topher with a lonely Dash and today we're going over lead code question 342 power of four which states given an integer n return true if it is a power of four otherwise return false an integer N is a power of four if there exists an integer X such that n = 4 to exists an integer X such that n = 4 to exists an integer X such that n = 4 to the x X power and these are the important ones integer X and integer 4 in order to solve this problem so they gave us three examples uh for example we if they give us n equals 16 we know 16 is a power of four because 4 to the 2 power is in fact and I'm going to double check this just for my own brain uh okay four to the 2 power is in fact 16 five cannot be because there is no power of four that will get us to five and there is no power oh there is a power of four that will get us to one four to the zeroth power will give us one right and the trick is that power zero is an integer two is an integer there's no integer so that power has to be an integer that will get us five so that's what we're really working with here is trying to figure out what that x value is X such that 4 to the x equals n so how are we going to do that and for me it comes down to mathematics so let's use a very simple example okay so four uh let's say 4 the 3 power uh is equal to 64 right and this I want you to rethink this as thinking 4 to the x is equal to n right because they're going to be giving us n and in this case is 16 and in this case is 64 so 4 to the 3 is equal to 64 and we're going to think logarithmically right logarithmically so we can rewrite write this right here this can all be Rewritten as the log of Base what is it log of Base 4 of 64 is equal to three and we're going to be thinking over here okay well that's really log uh base 4 of n is equal to X cuz we're really looking for that X okay uh and that can even be Rewritten a little bit more down to log base 10 because we're going to be programming and I like to have everything in log base 10 so in our case log base 64 over log sorry log base 10 64 divided by log base 10 4 is equal to 3 and again this is just going to be log coming over here log of 64 is our n divided log of 4 is equal to X okay and really this is as far as we need to go because we're going to be taking this equation CU we don't really need to know what x is we don't care what x is the only thing we care about is whether X is an integer or not because we're returning true or false based on the fact that it exists as an integer right so in our case when we're kind of writing out what we need to do we're going to say hey okay is log of n divided by our log of 4 is this an integer and the way we're going to do that at least for our purposes today is we're going to take this and we're going to modul it by one and we're going to say hey if this ends up equaling zero then we know that our X will be an integer now there are other languages you say hey is if log of n ID 4 is an integer if it is an integer then return true otherwise return false but for me this basic mathematics of using um using a modulo of one is the perfect solution because it'll work in every language no matter what you're typing in and so this is really all of the math that we're going to be using to solve this we're going to say hey uh is our log of n over the log of four uh an integer and you're golden but there's one other thing that we need to consider and I'm going to say that um in our edge cases so let's move on and see if there are any edge cases okay so for our edge cases and it's not really an edge case I just want to make everybody aware when we're thinking mathematically that the N can never actually be negative right because four to any power is never going to give us a negative n right so we can at the very beginning since we know n looking at our constraints could possibly be anywhere from -2 to 31st up to 0 that we anywhere from -2 to 31st up to 0 that we anywhere from -2 to 31st up to 0 that we should take care of that first if we can just say hey is n less than zero great we're going to return false um while not an edge case it's just something to consider right off the bat so let's keep that in mind and move on to some pseudo code okay so keeping uh in mind what we just talked about for our edge cases and though it's not really an edge case we can deal with it first so if n is less than or equal to zero right then we know that it's going to have to be return false um because there's not really uh an x value uh an exponent value that will give us the integer that we need to find n otherwise this is really simple very short uh we're going to return uh weather I have no idea if that's the right weather I'm really bad at choosing weathers whether the log of n right divided by the log of four is an integer and that's it that's all of the pseudo code work we really need for this question so let's copy let's paste it and let's get going okay here we are working with Java the first thing we need to do is to determine if n is less than or equal to zero so that's if uh n why I put a space there n is less than or equal to zero what do we do well we're just going to return false because there is no way that there is an exponent that uh four can have that will give us a value that is less than or equal to that so moving on now we need to return whether the log of n / by the log of four is an integer of n / by the log of four is an integer of n / by the log of four is an integer and like I said I love doing this with modulos so we're going to return whether and let's see here math. logbase 10 of n okay so far so good divided by math. log base 10 of 4 of all of that um if we modulo it by one and it equals zero then we know that it's an integer so it'll come back as true uh if it comes back as anything other than zero then it's not an integer the exponent wouldn't be an integer um so that we become false so that's it that's all of the code that we need to have here I'm going to hit I'm just going to go for it hit submit and see how we did Bam okay so uh maybe not the best I've ever seen but still pretty darn good we're hitting at 1 millisecond Beats 76 is% of people who running Java Beats 76 is% of people who running Java Beats 76 is% of people who running Java and definitely beating a lot of people from memory um so the I guess whenever I'm dealing with exponents I basically always say hey see if you can mathematically solve it first with the exception of power of two if you are a person who's already solved power of two watch our video because I don't solve it this way I actually use binary search patterns and to me it actually had a much better result uh it doesn't work as well in these situations because the number of exponents you're dealing with is a lot smaller but um for me I guess trying to solve this problem question 342 power of four is most elegantly solved using basic mathematics
|
Power of Four
|
power-of-four
|
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_.
An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`.
**Example 1:**
**Input:** n = 16
**Output:** true
**Example 2:**
**Input:** n = 5
**Output:** false
**Example 3:**
**Input:** n = 1
**Output:** true
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Bit Manipulation,Recursion
|
Easy
|
231,326
|
1,508 |
Hello Friends Welcome Back Coordinator Bring this channel on Great Difficulty Channel Please Share subscribe Hafte Ghanta Playlist Cover Various Categories of Problem Certificates That Link Click Asli Streets Grams in Programming and Maun President Ayub Upload Vote for This Prompted The Repository in Delhi From Description This Video Mid Range Of On Subscriptions A Given Are Norms Consisting Of And Positive Energy Is Yug Computer System Of All 999 Service From The Ray And Sold Them In Decreasing Order Creating New Year Of Any One Plus One By Two Numbers The Return Nashamukt Numbers From index left to index right 100 index starting from 1620 ok so let's start from one possible and include the new ones which come in and can be used to make model of 10th class 7 subscribe like they should be given with a are positive and the Thank You Hello Viewers Torrent Compute The Scientific Non MP Service Samudra In This Awareness As You Want 727 On That Angry Birds Shard Science And One The Answer Shot Android From Dam Good Cost To Get Dasham From Index Left To Index Right Down What Is The Intellect And white rates will give West Indies number means difficult Thursday what are the subscribe to 200 is draw and numbers in the following ride 100 there are into one plus one boy to survey number 212 Just give a that item se example enemies example want two three Four End Jobs Will Be But Just One There Ye Veer * Just One There Ye Veer * Just One There Ye Veer * Fixed Width The 12345 World In The Tarzan Picture And A Bird Is The Town Not Really So You Can Just Actually The Savage Element 12323 Phir Aa Hain Hands Free That If a and free 4hrs city ribbon mode support this one phone sadi sharda act and different shades possible on given rs 202 hu ke saamse tutte want to play screen spider at this time dance class board share step chu and relaxed for radhe shyam and get from left To Right The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Time Key and Calculate Assam Take Another Student Middle and Cube Listen Is Look Saath Shoot Me What To Do The Following Add I Will Come With A Technique President US Pandey Khol Will Be Amazed Andar Laxative Is So Instinct Of This One Opinion Version 1.1 10 So Instinct Of This One Opinion Version 1.1 10 So Instinct Of This One Opinion Version 1.1 10 Steps For A Given Her Wealth 12 Clean And Have Another Bra In You Step New Approach A New Approach Basically What They Want To Have First Claim One Want A Few Minutes Aam Kyun SMS Fateh Re Ek Naye Par Dishaye Main Kyun Late Ho Song Will Be That Vehicle Hands Free Hua Tha Aag And Effective Work Preludes Reception Diner Dash Ladies Aap Ko Shuddh Number One With Support For Fun That Exact Location 420 120 B Two Number Twenty One Plus Two Stree Edition Subscribe This Lineage 6 Nov Me Generator Saresham Fact Survey Songs From This Cream Latest Are Which Way Do Soul Admission In Getting Away And Calculating Us From Doing For Kids From This Point Numbers Are Different Subscribe To What Is Celebrate Velvet Favorite Song Way The Development Of That Share Now To-Do List 123 Rates On That In Order To Calculate All The Different Morning-Evening Grade Saugata Roy Don't Calculate From Morning-Evening Grade Saugata Roy Don't Calculate From Morning-Evening Grade Saugata Roy Don't Calculate From Morning To Three Four What Is Eliminated To WhatsApp Two Three Four So Please 991 Generator Not From Distant Relatives We So Thank You - Women Want To Relatives We So Thank You - Women Want To Relatives We So Thank You - Women Want To Remove V Front Arm 2014 Stand Awards Amount Withered Is Celery Just Friend Number Change Minus One Is Not Sure What Is The Technical Don't You satri floor what is the song ispat aur cement gaye jukke between To Calculate The Dark Remaining Material Election Withdrawal From Subscribe The Input Request First To Do Ko Khol Padh Lo Hua Hai Van Month Then This Year Itself And Answer Can Be Used In Number And Written By Sudarshan Important Hai On Which God Declared Today Survey 100 List A ki ai hai ki a yeh vada kyun ho late ho are miss Icon Its length is given and names were supposed to add the numbers from left to right in the sense in what she says give it is subscribe now just what is the first day subscribe to the Page is there you do the why are you late evening art 2 songs to the separation vikas subscribe na will see how do you say yes to improve are friend and generating friend dark science and adding m2di subscribe and subscribe the liquid want to The Sun Tan - subscribe the liquid want to The Sun Tan - subscribe the liquid want to The Sun Tan - Free Behavior - From Where Were You Are Free Behavior - From Where Were You Are Free Behavior - From Where Were You Are Very Difficult To Give The All Are With Us Hai Tu Fruit Us Wearable To Calculate The Dark Texture Will Have All Survey Systems In 110 021 Jis Vansh Yaar Do Is Left To Right Side Click subscribe button and subscribe my channel thank you to what is the return of the day hua hai chhayenge and space sukhbir wa how much time time time ki main plus hello how much time to get all survey systems and order and end Service Clip Side End Square Plus Hello How Much Time It's Good-Good Then Decimal How Much Time It's Good-Good Then Decimal How Much Time It's Good-Good Then Decimal Triad Is Properly Left - Rider Triad Is Properly Left - Rider Triad Is Properly Left - Rider Definitive Developed Calculated And Hidden In Thee To It Will Be Considered As One Two Three Don't Know The Number Three Idiots Say And Draft Total Will B N A Hello How Much Space Were Using Are They Using Space For Storing All The Songs Come And Waves To Reduce Vitamin A B C And D O APlus Co Subs How Many Elements With Were Using Space From Anywhere And At Least Take 122 Licenses And D And Super Soft Means The Space Complexity Will Be Harder And Thanks Complexities Of Saints And Pious Soul From The First President Of You Do Subscribe Channel Subscribe Video Like You Can Find The Retreat From This Video That History And Subscribe The Channel Please Share subscribe and Share with your friends Adventure Camp Please Click on the Bell Icon If It Will Be Notified About All In Feature Videos Thank You For Watching Ayurvedic Pay Agar Problem Very Soon Children's Day 744
|
Range Sum of Sorted Subarray Sums
|
longest-happy-prefix
|
You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed from 1**)_, inclusive, in the new array._ Since the answer can be a huge number return it modulo `109 + 7`.
**Example 1:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 5
**Output:** 13
**Explanation:** All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
**Example 2:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 3, right = 4
**Output:** 6
**Explanation:** The given array is the same as example 1. We have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
**Example 3:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 10
**Output:** 50
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 100`
* `1 <= left <= right <= n * (n + 1) / 2`
|
Use Longest Prefix Suffix (KMP-table) or String Hashing.
|
String,Rolling Hash,String Matching,Hash Function
|
Hard
|
2326
|
1,688 |
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to do video number four of our playlist of lead code easy, okay the lead is number 1688 easy is marked count of matches in tournament Microsoft has asked this question so this The question seems very easy and actually it is also easy but the main question arises that why would Microsoft ask such an easy question? Well, most probably such a question might have been asked in a phone interview. Okay, this is how questions are asked in phone interviews. But the most important question here is that what is there in this question due to which it must have been asked. Okay, so let's see, first of all the question comes that we have given the integer n which means the number of teams in the Tournament That Has Some Strange Rules There are two rules, if we assume the current number of teams is even, then each team gets paired with another team, then there will be a total of n matches between them, they play lead and end by. Two teams advance to the next round. Okay. If the current number of teams is odd then one team randomly advances in the tournament. Okay. One team will advance in the tournament and Ba and the rest gets paired and the remaining teams are their If there are matches in between then a total of n - 1/2 matches are played and then a total of n - 1/2 matches are played and then a total of n - 1/2 matches are played and n - 1/2 + 1 teams are advanced to the next n - 1/2 + 1 teams are advanced to the next n - 1/2 + 1 teams are advanced to the next round. OK Return the number of matches played in the tournament. Points means only one team will be left in the last. You have to keep doing both of these till the winner is the one, so it is a very simple simulation, keep doing whatever is telling you, okay if n is even then do this, if n is odd then do this okay if n is even then see come. In the next match, n Batu teams will go. If there are n odds, then in the next matches n - 1/2 + 1 teams will go. All in the next matches n - 1/2 + 1 teams will go. All in the next matches n - 1/2 + 1 teams will go. All you have to do is a simple simulation for example. If n = 7, then let's for example. If n = 7, then let's for example. If n = 7, then let's see the seven odds in the simulator. Is it yes seven is odd then what is it saying how many teams will go ahead each team gets paid with another team a total of n but matches are played if it was even but it is odd then the odds are looking at how many matches will be n - There will be 1/2 matches. Okay, how many matches will be n - There will be 1/2 matches. Okay, how many matches will be n - There will be 1/2 matches. Okay, so how many matches will there be? 7 -1 by 2 that is so how many matches will there be? 7 -1 by 2 that is so how many matches will there be? 7 -1 by 2 that is three matches. And how many teams will advance further? n-1 by 2, that is advance further? n-1 by 2, that is advance further? n-1 by 2, that is 7-1 by 2, that is 7-1 by 2, that is 7-1 by 2, that is four. So there are still four teams. Now if we play, is it even? Yes, it is even. This time, how many matches were going to be even? Remember simply n number, that is, 4/2. Here, there were going to be 4/2 matches. Okay, how is, 4/2. Here, there were going to be 4/2 matches. Okay, how is, 4/2. Here, there were going to be 4/2 matches. Okay, how many people will proceed further? n number now. Look, n is my four, so there will be a match between the 4 teams, that is equal to two teams. This is also even, so in the case of even, how many matches were going to be there. 2 Batu is one team will proceed, only one team is left, that means it will be the winner, look at how many matches are there in my total, three chars paa and these are six total matches, our answer is only six, okay, so how long do you have to do it? Look, it is not equal to one because one means only one team is left and that will be the winner. Okay, so its code will be quite simple, it will be a very simple code that as long as the number of teams is greater than one. Matches can happen right, if the team was the same team then where will the match happen then it is a greater day and till then we have to check only two things that if n percentile to e is 0 then it is ok means it is even. Right, in the case of even, remember how many matches were going to happen, matches plus n after 2 are ok and n further what was going to happen would be updated in n bats because now only n bat teams will move ahead ok and if n is not even. If it is then there will be an odd in the others. What did I say that how many matches will there be? Out of that, n matches plus n-1 times 2 be? Out of that, n matches plus n-1 times 2 be? Out of that, n matches plus n-1 times 2 will be that many matches. Look, n 1/2 and will be that many matches. Look, n 1/2 and will be that many matches. Look, n 1/2 and how many further play teams will play n-1 times. If it is how many further play teams will play n-1 times. If it is how many further play teams will play n-1 times. If it is ok, then what will happen next? It is clear till now, okay, so it is simple, look, it is off n, why see its time complexity because every time n, which is n, is being divided by two, this is what is happening here too, approximately okay, so Our time complex is fine because see first there was n then nn2 then n became n/2 then nn2 then was n then nn2 then n became n/2 then nn2 then was n then nn2 then n became n/2 then nn2 then either n - 1/2 and approximately it is either n - 1/2 and approximately it is either n - 1/2 and approximately it is fine I am going with n/2 n/2 n/2 fine I am going with n/2 n/2 n/2 fine I am going with n/2 n/2 n/2 so It is obvious that when we do not reach one, we are fine, then the time complex will be log off n, but now it is a very simple problem. Okay, as I said, we have done both the steps as it is, but this question. What is the special thing in this, why would you have asked, okay, actually, there is one O off and solution and it is quite simple, if you look, then okay, there is O off one approach too and why is it simple, you understand like this, friend, look at this. Will also expect from you, if you are asked this problem in the interview, then look, pay attention to what is happening in the tournament, let's assume that if there are end teams, let's assume that it is even, then n weights were placed here and n Batu was kept here and a fight was made between these two. Okay, so see, when this match happened, one of them must have won. He came here for the next round. One of them must have won. For the next round, one of them must have won. What will he do for the next round? One of them must have won, he will go to the next round, so one thing you are noticing is that when a match happens, a winner is chosen and a loser is chosen, okay? There is a winner and there is a loser, so now think about one thing, when there is a match, it is always between how many teams, it is obvious that it will be between two teams, see, this is a first match, this is a second match, so look at a match, right? This also happens between two teams. If a match happens between two teams then it is okay and how many are eliminated. How many people lose due to this? There is one loser and one winner. Right, if two teams are playing, one will win and one will lose. There is one loser. One person will be eliminated and he will not play again. He is out of the tournament. So think about how many teams we have in total, see how many people. One person is losing, one person is losing, okay, we have total N teams, okay, now you tell me how many people will be eliminated because there will be only one winner of the entire tournament, even if there are many matches, how long do we have to reach till? We have to keep going till we get equal to ave, meaning there will be only one winner in the last, ok there will be only one winner in the last and how many total will have been eliminated, total and teams were there no and if there will be only one winner then total will be a mine Teams must have been eliminated till now, it is clear and I just told you that if there is a match, then one team is eliminated. Here, if there is a match, then one team is eliminated and here is how many teams are being eliminated, A team only then So in the end one person will be the winner, if there is A minus and the team is eliminated, then yes, it is a question of how many matches there will be, the matches will definitely be A minus, like what I told you here, see when a team is eliminated, when there is a match. Right, there is one match only if one team is eliminated from it, so one eliminate in one match, for A minus elimination, it is obvious that you will have to do A minus and matches, is n't it? If you have to eliminate A minus and team, then Get A minus and match done, otherwise all the A minus teams will be eliminated. There will be only one winner in the end. Okay, so how did we derive that we had N teams in total and it is obvious that there will be only one winner. One is and the rest is A My, those who will be eliminated, there is one elimination in a match, okay there will be n-1 eliminations in n-1 match, this is the okay there will be n-1 eliminations in n-1 match, this is the okay there will be n-1 eliminations in n-1 match, this is the answer, our direct is n-1, that is, answer, our direct is n-1, that is, answer, our direct is n-1, that is, simply what we have to return is n. -1 simply what we have to return is n. -1 simply what we have to return is n. -1 Okay, generally what many people do is that they run a lot of example test cases and from there they understand the pattern that whenever the value of n was five, the answer was four, if the value of a was then the answer was Six was coming, the value of n was 10, so the answer was no. Okay, so actually the reason behind it is this, even if you catch it from the pattern, but the actual reason is this, isn't it? It is a very simple reason, the total is a matches, sorry a teams. There will be one winner n Maive people will be eliminated n To eliminate human people n Maive matches should also be there One person will be the winner in the end Okay so the answer is going to be our direct n Maive That's it our story is over We have also seen from the oven approach that this is the reason this is a very good question for phone interviews. Okay and so most probably this would have been the reason why Microsoft would have asked this easy question also. Let's code quickly and finish it. So let's code it and finish it. What is our first approach going to be? Simply return n -1, What is our first approach going to be? Simply return n -1, What is our first approach going to be? Simply return n -1, submit it and see. Even in o1 approach, it is easily solved. It is okay whether you find it from the pattern or not. Do it or you can understand logically how n-1 will be the answer. Okay, as how n-1 will be the answer. Okay, as how n-1 will be the answer. Okay, as I explained, after this, come to your logical approach, which is not even logical to you, which is given to you in the question. That is what you are doing when Till the number of teams becomes greater than one, we just have to keep doing it. Parl to e 0 means there is even number of teams, okay, if there is even number of teams, then the obvious thing is, how many will be the total matches plus in number is okay. Here the name of the variable will be matches and further n will be equal to n for further n ect. If it is not so then matches will be equal to n mye batu matches will be ok and for further what will be n ect n My Bat Pv Okay, in the end what we have to do is to submit the return matches and see if any doubt arises in the comment section try to help or out see you next video thank you
|
Count of Matches in Tournament
|
the-most-recent-orders-for-each-product
|
You are given an integer `n`, the number of teams in a tournament that has strange rules:
* If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round.
* If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round.
Return _the number of matches played in the tournament until a winner is decided._
**Example 1:**
**Input:** n = 7
**Output:** 6
**Explanation:** Details of the tournament:
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.
**Example 2:**
**Input:** n = 14
**Output:** 13
**Explanation:** Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.
**Constraints:**
* `1 <= n <= 200`
| null |
Database
|
Medium
|
1671,1735
|
1,712 |
hey everybody this is larry this is q3 of the weekly leco contest ways to split it away into three step away um yeah hit the like button to subscribe and join me on discord uh let me know what you think about this problem i had a lot of issues with this problem uh solving it i mean the problem is perfectly fine um it's just that i don't know there's just a lot of issues um for me um the worst thing was that during the contest i spent way too much time on this i had the idea pretty much right away and i knew how to do it right away but my math was wrong um and just took over my thought process um yeah i think if i were to do it again i think i was just a little bit lazy in the sense that i just didn't have i was a little bit tired today and um and i should have priced that out but this was a little bit trickier and i just couldn't grind for it um what i should have done is um you know i have my piece of paper and pencil and stuff like that ready i should have just did the math so that it's clear what my numbers are that i'm looking for in a binary search i had a couple of numbers on the binary search and it was uh the wrong number and that's basically the answer um i did at the very end i um and this is after the contest i wasn't able to get it during the contest i did a co-review which you the contest i did a co-review which you the contest i did a co-review which you can watch me do afterwards um and after that um this was pretty much it i had most of everything else uh like i said the only thing that was missing was uh this value i was using this instead for a little bit um and i just couldn't figure it out so okay so that was my thought process a little bit during the contest and a little bit of postmortem of what i did during the contest but to explain the problem um basically first of all we need the prefix sum so basically um now we have an array of the pre this prefix sum right and if you're not super familiar prefix some i urge that you practice on easier problems because this one is not going to be a easy problem to kind of visualize for that um and then after that um it's just brute force in a way moving the left um you know because basically you have two dividers right one on the left that divides you know the beginning the middle and then the end right so that two dividers be dividing left middle and end um and then for me i just um you know move forwards going from left to right on the first divider and then binary search on the second divider um and there and the two elements of binary search which is that um you know um which is for the second pointer you have i wanted to get where's the left most positions i can get and what's the right most position that i can get and that's basically the idea um you know left target is just a prefix times two meaning that you know the middle chunk is as close to the um the first chunk as possible and then the right index is just well this is as big as possible meaning that it divides uh the middle perfectly as much as possible given minus the prefix um but yeah so that's the idea this is the code um hopefully that makes sense there are other ways to solve it seems like as i was doing quick review i'm not gonna go over it too much because to be honest i'm just a little bit tired today and i was terrible in this problem i spent the entire time doing this part so much that um i in q4 like i've gotten a great time on q4 i just focused on it but i keep on going back and forth because i was i felt like i was close on this one um but yeah um in terms of complexity so for each item it's gonna be you know this of n in this loop and this o of n here um but for each loop we do two binary search so it's gonna be log n so this entire algorithm is gonna be n log n um in terms of space obviously we have prefix sum it's gonna be o n so it's gonna be off and space um i have a long you could watch me like bundle like going back between like three or four different ways of solving it for this problem um let me know what you think and yeah um yeah that's all i have uh yeah let me know what you think how did you do this problem and you could watch me bumble around the problem next but i didn't read it okay well this is gonna be a sloppy contest you know that was a easy problem two easy problems really okay okay mod again ah sloppy just kind of tricky problem but um this is a messy one i know how to do it with a lot of by one issues you um that's not okay oh that's well what am i looking for what is this my this is not the freedom okay you now that should be three right so total is three minus two oh minus one now this should be 20. why is target that's hmm what is that before oh whoops this is not the right total that i want uh that's what happens when you shadow names one three one of this as well why have a lot of wrong answers today that's not right now okay oh i mean this should be right but i don't know why it's gonna be the wrong end for this part left toilet hmm five ten fifteen that sounds alright why is this not a two that's not violet one two three as well i mean it's not wrong but i'm doing something well so the right index is equal to um quite target no that's not right enough targets too my target is man i'm really struggling today unless there's a dumber way to do this as well which there might be that's how many people got in so far five people got in it so i guess this is harder than i think as well um and i wish that i didn't have two wrong answers on the first two parts which made it tough so what is this minus this okay i'm gonna think of something like that but i'm not doing it quite right it's close closer the right target here is eight that's right 225 doesn't this one doesn't really make sense oh that one's okay actually it's i don't know if this is right anymore now it's going the other way too much oh because it's not adding this but one two and five that's the one that as well one two and five okay this is two and three total is true this should be six two minus no that's not true yeah now it's true some minus if um is this point right at least no still wrong because this should be total sum is twelve minus two is ten how do you get four because the prefix is two zero one two prefix is three so you have twelve minus three is nine minus divided by two okay maybe that makes sense just the two come from two is the right target so that means that the prefix is gonna be three so we want something that's actually don't i did this though but maybe it's just wrong for another reason it's prefix up index right so we want this plus prefix okay that's why we get to five because we have three plus another two which is five so then this goes here but it just means that no i mean yes so this is the smallest thing but we actually want the biggest number so that's just wrong this should be so the rest of this is nine so nine plus it should be four so four plus three should be seven right what am i doing i am so bad at this so total sum minus prefix of left index uh okay and now we want to add when we divide this by two as we said and then we want to add this to left index okay so fix this one but then now this one as well why that's why target is two you know there should be three possibly due to rounding out oh that didn't help wanted what is 2 because totals 33 minus 2 is so we want the max of this and the prefix of left index plus i don't think this is right just by luck let's give it a summit yeah i didn't think it was going to be right this is too hacky to be right um so this is two because yeah i actually knew that the zeros actually might be an issue um like if we had something like this it's yeah it's also gonna be i don't know zero sweat um i really don't handle that well i spent too much time on this i should have skipped ahead already and then come back to it that's gonna cost me like even then this is probably not going to be right because here one three four five to do uh this is gonna be like some n square thing and this is clearly not right i mean i could do more binary search but i don't think that's quite the right answer maybe sliding windows if you have the right idea but i've i think i knew that implementation was always going to be a sketch this one i don't i just don't have to grind today actually i guess i could do suffix some as well okay foreign minus one i'm gonna have so many off by one issues i'm just thinking about it now and i'm being a little bit lazy i always forget about uh suffix um you i don't think this is vibe i just really wanted to see if i have any issues like that one for example um i'll just type one okay include the first element because i have a zero um this one's not right should be okay um man i am really struggling today sometimes life is hard this one is you this is right i don't know anymore also i think this is just wrong it should be something like that but i'm not even sure this is right it's just not pointing that much maybe i need to get back to fundamentals i am just really bad right now reset your mind now half an hour you can do it suffixes suffix is wrong for me okay why is this not oh left index white index some of your prefix uh 0 and we want the next sum to be greater than zero but i think this works if it there are no zeros and i think i'm just having issues of zeros maybe i have to take care of zeros differently so i'm just struggling a lot with the concept of zeros uh because everything else i think this works and i'm just not or even my original code may work if there were no zeros what happened i clicked on this and then i edited it i don't know what happened but so i think this is right for non-zero so i think this is right for non-zero so i think this is right for non-zero so can i handle it as it was in a clean way you i think the other zeros that i'm having issue going to have issues with that's why i'm just um i guess i just had to handle it differently uh still not a great score because a lot of people got the first three or the q3 but it is true that today i just don't have to grind in me shouldn't have done it i don't know this is right but this should still be one sound hmm yeah i mean this should not be zero and six on every time so that's not great okay this one is good just zoom not so good oh it should be same thing ten five choose two or something is that right okay here we go anyway this is another wrong answer why is that four so two and six where's the right answer three we're getting off by one somewhere yeah i mean there's this zero that's messing me up probably um 2 7 16 so that's not going to be right so that's 110 and then all of these that's one 15 is 2 and then this is 3 4 is this why do i have 4 what is 6 six is me searching for 20 and then 32 is do i want to search for 32 so it's 10 plus 50 it's 10 plus 10 so it's 20 so 45 20 what am i searching for so it's just another this doesn't even make sense there's a better sense of my indexes like i'm wrong and so i'm off by one in like three different places this is why i cannot make sense of this huh i mean this is kind of right except for not this should be i think my counting is just really off on this one uh maybe it's not even um now this is not like 20 why is 20 giving me six index 20 should give me two oh no my left right is one so okay how does this get four did i not print somewhere i am just very confused index enough right yes okay searching for 32 again okay reflexes 10 search for 20 okay and then that means that the third one should be i'm doing two things right am i off by one i mean clearly i'm off by one but because v1 is 28 good now we want the suffix and this suffix is r51 because i am bad at math okay so how do i fix this yeah it was 45-36 should not be good 45-36 should not be good 45-36 should not be good so yeah i should have done something good but this should be good this hmm okay i mean this is right at least finally but now everything is well because this should be 30 45 minus 28 which is 17 so that's it should be and the answer still should be three five minutes so we're going to um we're gonna do some code uh what you're calling that's not good today i just don't have the energy for this problem this type of problem 10 and 17 that's good that's what i want so why is that index not going because it's -1 for some reason it's -1 for some reason it's -1 for some reason uh these are just not even close to white anymore i don't know how it's out this far i think i just have a lot of i think the queen of palm it's not something just silly i think i'm just doing something really dumb uh let's think about it if i could do any other way um so for each thing you do a prefix and then i mean i think i'm roughly right but i don't know it's gonna be rough again i just don't know how to solve q3 uh what a way to start a year huh um having historically i always been kind of ignored to ignore the three sum e problems because i don't know i don't think this is that dope but am i just one i mean this should be right i mean there should be one minus some like silly off by one i don't know if there's any other and maybe zero things which i don't know how to handle um with this way i think if there's no zero i think this should be well that's not true because clearly here i'm getting it wrong it should be close um i feel like this is like a standard e problem but that's why i don't know how to do it uh i like i feel like a lot of people know the standard solution and i don't per se that's what i should have did q4 much quicker because i should have just done it but then i had to inward the way i've thought about it i mean at this point um let's just go over code review um terrible contest for me again uh to be honest gonna drop quite a bit but i don't know i maybe i need i uh a disappointing kind of um contest but i mean it was a hard contest even top 10 had 40 minutes um so yeah but a lot of people were able to get qtv which i really should have i got two four actually not that bad but because i raced i spent like 40 minutes on q3 and i got this in like i think relatively quick except for that i have one i was missing one piece so if i had full energy focus and i didn't have two three issues i probably would have gotten this much quicker but i couldn't get i kept on going back to q3 and can go think about it uh let's kind of look at the code review and then we'll observe and yeah and again i have two incorrect mistakes that kind of hurt uh let's see let's kind of see uh hmm okay so it is prefixed some i just couldn't i don't know why i couldn't get this one then i thought i had something close i mean prefix i'm in sliding windows but yeah i mean i guess didn't handle zeros correctly as well and i don't know um yeah this one is probably similar to mine with respect to binary search but i they probably handle i'm actually curious i think we had similar things but i don't know what that code is let's take a quick peek at q4 as well how people did it um that makes sense i mean this is kind of yeah i mean this is basically what i did maybe i don't know if that's true actually let's see what shall we do i mean yeah i did it with a segment tree which is not surprising because that's basically the same way that i did it except if i didn't use segment tree i'm just trying and another segment tree e problem i don't know if anyone else did it another way that's why uh oh i'm just increasing substitute oh yeah that's true you can map this you can yeah you can convert it to a long uh longest increasing sub sequence that makes sense actually that's actually yeah that's actually a great way of doing it um not sure about that one i mean it clearly works i just don't know how uh to think about it and i think they're just using maps or trees in a way i don't know that one actually i think to be honest i think that's just like uh longest um they're so common but uh i think those are just uh longest increasing subsequence uh yeah longest increasing subsequence uh variations that uh yeah relax through this one i don't know how to how come there's no uh code reviews is it only on page one nowadays i don't know that is that new that they don't let you see people's solutions on page two uh yeah i don't um wait i think this is the way that i would i was trying to do it but i don't i happen off by one or something i don't know what it is but i clearly have it wrong i mean clearly i just i search for the wrong answers but so here it seems like they search for given what is this eye let me look at another one this is what i want what i've loved to do but i don't oh i didn't know that you could do underscore for constants but um what does it mean we mean is some what is accumulator man that's too bad contest in the world i'm those sad but i'm just trying to get a clean solution data binary search fine what is this i don't um i mean i had this idea as well but yeah i don't know i'm still i mean i so i know how to solve it i just don't know how these things handle um handled off by one and this is kind of literally the same as mine except for he did it correctly so let's see how is it n minus one oh i mean i guess it doesn't matter but ideally now i'm cheating a little bit i'm just trying to figure out like what's the delta of my thing right um yeah and i mean we have the same thing here so i should so here's a cover um this thing which is the same so i'm trying to figure out i mean i'm cheating a little bit but i'm because right now um i'm confident that my implementation is co oh sorry my algorithm is correct but i'm trying to figure out why my implementation was incorrect so that's the thing um right as you go to you have a bunch of stuff um but bisect total plus a over two is that really that i mean i had something similar but total sum plus uh prefix index uh over two i don't know if it's and then they just made it with uh and which is kind of what i mean i have it in not an intentional way um really though is that all oops well i mean this is very good code but i'm off by one somewhere so i don't now i'm just trying to figure out like how wow like we have the same code pretty much am i doing something weird does this have to be this does that make it better i mean i guess he does this as a bicep right so i'm definitely cheating right now but uh but i'm just trying to really figure out uh why this is oh this is just me being dumb um can't even copy someone's i mean i'm not optimizing my mindset for copying someone's answer but wow i mean so i guess all i was missing was this formula why is this oh i am so bad at math i'm just i guess i'm just bad at math i was okay um i'm trying to figure out uh okay i'm looking at the wrong answer one okay friends um i have to think about this offline um i mean i think i did okay given that um i'm not i think one maybe lesson is that i already got stopped doing every contest um i wasn't feeling good today and uh and it shows like even during the competition i was just not uh going well um and this problem like i and it feeds back on each other right like i'm queued really fast or like actually gotten it at all um i would have gotten q4 because then i would have focused on it and then i would have uh changed it to the correct thing but instead i just kind of you know even got a bad time on it relatively um but two three i am very i mean i am happy that my uh my idea is right i'm a little bit sad that my math is so bad why did i get this so wrong how did i get from here to off to here from i mean i think some of it to be honest is that i was a little i was stubborn so i had this thing um and what i mean by that is that i was stubborn because i didn't get up a piece of paper i should i honestly should have just taken a piece of paper and like do the math out um but i was trying to be tried to do too much in my head um and i just got it well um if i had gotten this i would have gotten it right i don't know where the bisect right comes from a little bit um but i have to kind of figure out this math um yeah uh i'm gonna end the stream here uh happy new year hope you i don't know i hope y'all hey everybody uh yeah happy new year thanks for watching let me know what you think about this problem i had a rough contest but sometimes it happens uh so you know uh don't feel so bad if it you know happens to you either um but i for me you need to be more consistent let me know what you think about this problem and whatever i will see you later bye
|
Ways to Split Array Into Three Subarrays
|
unique-orders-and-customers-per-month
|
A split of an integer array is **good** if:
* The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right.
* The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`.
Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[1,1,1\]
**Output:** 1
**Explanation:** The only good way to split nums is \[1\] \[1\] \[1\].
**Example 2:**
**Input:** nums = \[1,2,2,2,5,0\]
**Output:** 3
**Explanation:** There are three good ways of splitting nums:
\[1\] \[2\] \[2,2,5,0\]
\[1\] \[2,2\] \[2,5,0\]
\[1,2\] \[2,2\] \[5,0\]
**Example 3:**
**Input:** nums = \[3,2,1\]
**Output:** 0
**Explanation:** There is no good way to split nums.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 104`
| null |
Database
|
Easy
| null |
1,078 |
hello everybody and welcome back to the DCC channel where in this series we solve litko technical interview questions later on probably some other technical interview questions when I'm done with all the little cold ones and let's see let's try occurences after bigram sounds weird so 10 1078 occurrences after bigram given words first and second consider occurrences in some texts of the forum 1st 2nd 3rd where ii comes immediately after 1st and 3rd comes immediately after 2nd so text first second what is the third or for each such occurrence at 3rd to the answer and return yes so I guess my first wait given words so we have two words consider occurrences be some texts of the forum bla so it means that any substring of this text right let's see our text Alice is a good girl she's a good student first is a second good ok these are basically really words output would be girl and what wait for each such occurrence at third to the answer and return the answer this oh I see so girl is the third and basically the word that is succeeding both those two words so basically when we have a case where we find these two words we can basically put out the next one and again we have a and good as well another case and we put out the next one again okay let's see a second input we will rock you and we have we will of course the first case of a third word will be the we the second case would be the rock and we rock okay let's see the house it coat with three constraints things length could be anything between one character and a thousand characters I mean if it's one character I don't see how you can maybe there are cases where for example let's see do we get something like first and second consider consists of lowercase English letters text consists of space separated words where each word consists of lowercase English letter so it's it cannot be easier at least in this sense and first length is at least one second length as well most them and that means we wouldn't be able we wouldn't really have to handle anything like empty words I hope that maybe later we can solve some other questions like maybe at medium difficulty I'll have to check that also have a bunch of pretty interesting edge cases to handle also because I mean the algorithm itself is interesting but also kind of cool to think about edge cases and they never ever give us any like they make it the most straightforward possible I assume that's why they are easy by time I'll check it out so how will we solve our algorithm while reading a kind of gutter idea okay why don't we just separate each of those words into a array all right so basically everything will be an element in the array we can just kind of like go over the array when we find our first match in words we just go and look at the second one if we find the second one to be as well matching as well then we just take the third one if there a possibility for a third one because maybe they're like the second to last in the last word then there wouldn't be any very last one right so we also have to kind of look ahead and see okay is there an index here and like at all if there is one we take it put it in the output and then just to be kind of like universal I wouldn't even skip maybe I'll just keep two indices yeah why not let's try and work with an iterator again so we will have an iterator and it will be enumerate in all the text that means now we will have the index and the elements as well and it will be actually text and basically flipped on an empty line so basically get a list out of that and I'm not even sure so let's quickly check that let's print what would be a word and another word oh my god I'm not typing correctly and then we're going to split on an empty on basically on space I'm expecting to get an array and I got an array okay so let's give our array and I could save it but I wouldn't like I could save it in a variable but in this case I mean it's so tiny we'll have our output it will be an empty list for now and now we could actually shorten our algorithm and say if the length of text is just one we know we wouldn't really be able to do our thingy actually from even to would also be a problem right so less than three well even that like let's think about it the minimum word would be a single character then we will need a space so I get to the second word minimum would be a single character so three then a space for then we're actually starting at five so anything less than five will definitely not be able to give us three words this is the minimum and then we'll just return out like this so this is our short kind of each case so for the other parts we got ourselves a iterator one eternity later yeah the problem I kind of saw the problem now I'm not really kind of confused about it but I think the best approach would be to just simplify our whole thingy and what I mean by that is we can actually just do something like this we can just go over each word and I thought okay let's just look at the second word and that would mean that if words would be for example the second and that our index plus one is less or equal to the length of words just this would basically mean would basically stay the same and of course yeah this should be the case if we find that the second word for example and let's say we find the second word we know that the next word is a possible word and also we want to see that let's see that there is a word before that and that would mean in X minus 1 is greater or equals to 0 that means there is at least 0 index and so basically we know ok there is something at the end that we can look up there is something beforehand like before the second word and if this is something that means if words index minus 1 is equal to the first word then we are basically in the middle right we are looking at the second word we know that there is a possible case for a first word and a possible case for a third word and we see that the previous word is actually also the first word then we can actually take the third words and that's all it's actually a so what would that be words index plus 1 and that is all right and then we move again and again we look at the next word again if it's a second word and the first one yeah this could still happen right if you get the same two words I'm not sure if the description said that they should be different it never said that they should be different right so if you had something like I'll still have this case you would like if you had words eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh-eh and then first would be a second would be a when you are here let's you have another one something like this when you are here you could be looking at this one and this one okay everything matches you take this one and then you're here and again you see the second word right you see oh there is a space for first foot and it's actually the first word again and you take this one and you here you'll see okay there is no space for words so I'm actually just gonna yeah I'm not gonna go inside here but yeah the Sun something like this should be possible and I'm not sure like they didn't say there is no possibility of duplicate first and second words right and as you can see that's the case okay let's have this case back and kind of I'm kind of wondering now it's accepted we really simplified our algorithm and I think this is what should if we should have done from the very first time but I didn't have it in yeah kind of like in mind but that's that the beauty of it I think at the end when you are solving these questions like in technical interviews kind of having this type of thinking that like just to see the final simplification of things really helps because basically now we are only running through the index like to the whole array only once and we are only looking at very specific cases and sure okay we do some simple or it may take here but like almost nothing like this is probably a hard-coded when like this is probably a hard-coded when like this is probably a hard-coded when you when we did this thing here and this is very simple arithmetic again simple arithmetic simple or it no logic I guess I would say these are like constant runtime for us this again probably constant so we are only doing linear time when it comes to a runtime complexity and when it comes to space technical complexity again probably sub linear at most yeah it would be basically at most kind of like bit less than linear or actually linear of course we do have the input array but still very what seemed very easy at the beginning turned out to be kind of complicated maybe a complicated myself again we DC traitor but our kind of lonely that so stick with me guys I think it's very it's worth actually having control of the iterator at some point and yeah it was interesting it turned out to be a very simple solution at the end so that's what I liked about it let me know what do you think about this solution and yeah if you're new to the channel and you want to see more of those questions being solved in a kind of like interview kind of version consider subscribing and I'll see you guys next time bye
|
Occurrences After Bigram
|
remove-outermost-parentheses
|
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`.
Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`.
**Example 1:**
**Input:** text = "alice is a good girl she is a good student", first = "a", second = "good"
**Output:** \["girl","student"\]
**Example 2:**
**Input:** text = "we will we will rock you", first = "we", second = "will"
**Output:** \["we","rock"\]
**Constraints:**
* `1 <= text.length <= 1000`
* `text` consists of lowercase English letters and spaces.
* All the words in `text` a separated by **a single space**.
* `1 <= first.length, second.length <= 10`
* `first` and `second` consist of lowercase English letters.
|
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
|
String,Stack
|
Easy
| null |
1,937 |
all right today i'm going to talk about question one 1937 maximum number of points was cost so the idea is we want to find a direct path from the first row to the last row and we want to sum up the numbers together we want to find the maximum sum that we can find from a pass and one caveat is there's a cost if you want to inherit a number that is not directly above it for example if you want to inherit three at this position we need to pay a cost of one and if we wanna inherit three at this position we need to pay a cost of 2 because the difference here is 2. all right we can there's many ways that we can do this we can do dfs and we can that and we can also use brute force uh i think both of these ways will give us will exceed the time limit allowed so one way that we can think of is using a dynamic programming where we can store on each world use a piece of memory that is the length of each row and they will store the maximum result that we can obtain on the current level for each uh index and therefore for the next iteration we can just read from this previous calculations to and then calculate the new solutions and another thing that we can utilize is we can keep track of uh the maximum value that we can find on each direction for example if um so there's two options right if we wanna uh if we're at this number one there's two options we can either um okay so if we can find the maximum number um on the for example we're f5 on the laptop the five and we can find the maximum number on the right of the five considering the cost on this current step 5 we can just compare the maximum number from the left or from the right and we can just take the maximum of the two and that maximum will be the solution for this current step five and uh yeah and then we can compute uh this solution for this row and then when we're looking at next row we can utilize this previous row to compute new values all right so let's go ahead and code this up first let me use some temporary variables because we're going to use the row and column length a lot we also need a array of memo to store the previously calculated solution and then we can first we need to populate the first row because there's nothing we can inherit so the first initial values for the memory will be the same as the first row of the input like this and then we can start the iteration from the first one the second index one all right so currently we're looking at the second row and like i said if we want to obtain the maximum result from the left and from the right we need to uh some you need some additional data structure to store the results so um all right so um we know that if there's for the first if we're at here the maximum number we can find from the left is just itself so it's equal to let's start from the second element and then i step we just want to calculate the maximum result we can obtain customering the cost so maximum of left j minus one because we need to pay a cost of one here that's what the minus one is this that's what this minus one is for and that's minus one that's four required is for reading the previous calculated results so or um all right so or we can we don't need to do anything and just inherit from the previous solution similarly from the right side we'll also want to maintain the maximum number we can find so pain of price is j plus one minus one or you can don't do anything and we have just entered the previous number okay now we can populate the memo we can prepare the memo for the next iteration um mammal i is equal to the left side result or the right side result plus a previous result so and here um no it's not memo j i think it should be point i j actually okay let's take a step back why what's what should be the number here so either we can inherit the previous number or we can just take the number that is not directly above us so shouldn't that be um so we want to calculate what's the maximum number that we can inherit so yeah so okay you heard one or two minus one or three minus two and on the other side we can inherit 3 or 2 minus 1 which is 1 or 1 minus 2 which is negative 1. and we did that all by okay what about here so we can either inherit um whatever um okay this should be that's right so this should be the current number there so we figure out the maximum number that we can inherit and we can just add that to the current number that we are looking at and last but not least we need to return we need to find the maximum number from the last row from the memo after we've gone through every row so let's find the result is equal to zero iterates through every number inside level number okay index all about four lengths two memory j right all right cool so for time complexity we're basically iterating through the entire points matrix once so the time complexity is o n and the space complexity we're just using this temporary memo array of length row and another two that's our ninth row as well so let's at most 3n and that's i will consider that as on as well because we are ignoring the constant and uh yeah so i'm going to put this down if um so the time complexity is oh wow and it becomes m and the space complexity is of 3n which is basically thank you
|
Maximum Number of Points with Cost
|
maximize-the-beauty-of-the-garden
|
You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix.
To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates `(r, c1)` and `(r + 1, c2)` will **subtract** `abs(c1 - c2)` from your score.
Return _the **maximum** number of points you can achieve_.
`abs(x)` is defined as:
* `x` for `x >= 0`.
* `-x` for `x < 0`.
**Example 1:**
**Input:** points = \[\[1,2,3\],\[1,5,1\],\[3,1,1\]\]
**Output:** 9
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
**Example 2:**
**Input:** points = \[\[1,5\],\[2,3\],\[4,2\]\]
**Output:** 11
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
**Constraints:**
* `m == points.length`
* `n == points[r].length`
* `1 <= m, n <= 105`
* `1 <= m * n <= 105`
* `0 <= points[r][c] <= 105`
|
Consider every possible beauty and its first and last index in flowers. Remove all flowers with negative beauties within those indices.
|
Array,Greedy,Prefix Sum
|
Hard
| null |
902 |
hello everyone welcome to quartus camp we are at 18th day of december lead code challenge and the problem we are going to cover in this video is number at most yen given digit set so the input given here is a set of digits which are in the string format and an integer yen and we have to return the number of possible numbers we can form using the given digits and that it is also said that we can return we can have or form numbers with repeated digits of any times so let's understand this with an example so here is a given example in the problem statement the digits given are 1 3 5 and 7 and the limit given is 100 so you have to form the numbers starting from 1 to 100 and you have to return how many numbers you can possibly form using this digits so let's start with having one digit numbers so how many one digit numbers you can possibly fro form from this given number it is very simple the given numbers are one three five seven and those are the possible one digit numbers you can form in total four so how many two digit numbers you can form so to count two digit numbers you have to start with one and combine it with every other number in the given list so in that case we cannot also have repeated numbers so we have 1 2 1 3 sorry 1 3 1 5 1 7 and same goes with 3 1 3 5 3 7 and same goes with 5 and 7 so in total you have got 16 numbers that can be formed by using the given four digits with two digit numbers so how do we actually find it mathematically so before getting into mathematical solution how many three digit numbers you can form so you can form three digit numbers but that is not necessary because the given limit is hundred and by calculating the two digit numbers you can possibly form that will cover till 99 and we don't have zeros left so we don't have to really concentrate on hundreds so if we calculate the one digit numbers and two digit numbers we could form by this digits we can return the solution so in total it is 14 plus 16 20 digits or 20 numbers you can possibly form in within the limit 100 by using these four digits so how do you calculate this mathematically so easily you can calculate it by uh doing 4 power n or digits power n so here there are they have given four numbers in the given digits so we have to use these four digits to calculate the number of numbers we could form possibly using the uh one digit or two digit and etcetera so to calculate one digit numbers four power one is four and to calculate two digit numbers four square is 16 and to calculate three digit numbers four cube and so on till how many digits we can possibly form for example if we have given thousand as the limit then we have to calculate four power three and add it to these numbers and if we have given ten thousand as the limit and it goes on and etcetera so these are the happy path yes that we can easily find these numbers and how many uh possible numbers you can form by using this digits so what if the numbers given are some 536 so in that case you can't simply just calculate four per yen and get the result so you have to or you can simply calculate 4 power 4 and do it and calculate because the number is somewhere in the middle so you have to really try to get the numbers that could possibly within the limit 536 so that is what making this problem little harder so let's understand how are we going to handle these kind of cases here so now consider the limit n is equal to 5 3 6 7 so in this case you first will find the limit from 1 to 100 with 4 power 1 and 4 power 2 and with the limit thousand you'll go for 4 power 3 but this is something from 1000 to 5367 so in this case how do you find it so first let us start with keeping one as a constant and the three numbers can be anything or repeat repetitive so in that case you again have four digits because one also can be repetitive and so for example if the number is one and the rest of the three digits are xx so in this case these x's can be any of these four given digits so again you have to form a three digit number and append it with one so keeping one is constant you would have four cube or four power n to construct the rest of the numbers so if we have to form a four digit number then one is constant we clearly know the first digit is always going to be one and the rest of the numbers you could possibly form would be four q so same goes with 2 keeping 2 is constant but the number 2 is not given so the next number is 3 so keeping 3 is constant then rest of the number x can be anything with 4 power 3. so the next number is 4 but we don't have 4 here so the next number is 5 so here we simply can't calculate keeping 5 as a constant and the rest of the numbers can be x because the limit is not 5 9 5999 but the limit is 5367 so you have to be very particular about fixing these digits so this can be handled by keeping 5 as constant and the first x could be less than what is there in the second place in this position so the position is having three so this second position would possibly have one or three because uh we are given only one and three which is less than or equal to this number so in this case again you can handle one very easily because the rest of the numbers are going to be two x's so this count will be given by four square or the number of digits given power n so here comes again three so you can't simply keep this the rest as xx because you have given only six and seven so again this third and fourth number will be fixed based on the values at that position so now the position is having 6 so the numbers which are equal or less than 6 could be added in this place so 5 3 what are the numbers that are there in the given digits which are less than or equal to 6 which are 1 so it would be 1 x and 5 3 5 x and the other number is 7 which is greater than 6 so we can't fix it so this x can be again four other digits one three five seven and this f x can be again four digits and this x can be again four digits so this will give you four and four so we have covered all the cases for this number so solution of this problem would be calculating the happy path numbers over one two and three till thousand and four from thousand to five thousand three hundred it will be four cube plus all this calculations so sum of all this would give you the results so this is pretty simple all you have to do is calculate the possible numbers you can form mathematically by keeping the numbers as constant and calculating the values for rest of the numbers and do an addition so we are going for a dp solution where we are going to maintain a dp array of number of digits given so there are four digits and will be having four cells from the last digit we are going to put the values and keep adding it to the previous cell and so these cells will be having the values of these kind of calculations that is the special cases and finally dp of 0 would be having all the addition plus these happy path values that is if we have to form a four digit number so we'd be calculating four power one four port two and four power three if we have to calculate a five digit number then simply will add all this plus four power four and that will be calculated and stored in dp of zero and this will be returned as our output so hope you're understanding this logic and this algorithm is going to work and big o of log n time because for each digit we are going to calculate the possible permutation of the count of numbers keeping the given digits are constant throughout the algorithm the constants can be omitted and log in time is because every time we are going to shorten the size of numbers we are going to calculate the size for because it is going to start with if it is a four digit number limit then it is going to start with three digits and then shorten to two digits and then shorten to one digit and etcetera so yes let's get into the code now so here is the code for this problem so first we are converting all the numbers to string because the given digits are in the form of string so if we convert the integer to string or the given digits through integer to keep everything in one form it will be easy for us to compare so we are first converting the given n to string and then we are taking case equal to string dot length but this k is nothing but uh the four we have used so this k is going to be the constant which we gonna use for our calculations in all the places and as i said we are going to have a dp array to store the calculations and calculate it and we are declaring dp of k is equal to 1 so which is nothing but we are going to start the very last position with the value 1 and we are iterating it from the reverse to handle the special cases first and then going forward for the happy path cases so first we are converting the given digits in n to integer so and we are taking the each digits to compare with that integer and calculate the special cases first to calculate the special cases we are comparing whether the value at d is less than the given digit in the n so which means if it is less than then we are going to keep that digit as constant and do uh digit.length digit.length digit.length power k minus i minus 1 this k minus i minus 1 is nothing but if we keep 4 uh some 5 is constant and the rest of the x is going to be total length minus i minus 1 so that is the rest of the characters we are going to calculate for that is 3 4 power 3 so yes otherwise if the digits are equal then we just have to take the previous calculated value and add it to the same value because we have calculated for that digit already so we are just simply taking that value and adding it to the next value and yeah that's it this is the simpler calculation for uh calculating if the digit are less and equal if the digits are more we are going to consider we are not going to consider that at all because uh as i said we have to have a digits only within the limit we cannot exceed the limit so we are not having a case for the value greater than the digit at all so once all that is done we are going to put a simple loop to calculate the happy path values which is nothing but the digit dot length comma i every time and we are finally going to return our result in dp of 0. so hope you're understanding this problem if not try it yourself or try to print the value and understand it so let's run and try yes so let's submit yes the solution has been accepted and runs in 0 milliseconds thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Numbers At Most N Given Digit Set
|
minimum-number-of-refueling-stops
|
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`.
Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`.
**Example 1:**
**Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100
**Output:** 20
**Explanation:**
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
**Example 2:**
**Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000
**Output:** 29523
**Explanation:**
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits array.
**Example 3:**
**Input:** digits = \[ "7 "\], n = 8
**Output:** 1
**Constraints:**
* `1 <= digits.length <= 9`
* `digits[i].length == 1`
* `digits[i]` is a digit from `'1'` to `'9'`.
* All the values in `digits` are **unique**.
* `digits` is sorted in **non-decreasing** order.
* `1 <= n <= 109`
| null |
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
|
Hard
| null |
1,004 |
Guy Hello you are doing 90 days software engineering prep with me this is 16 questions lead code is 75 overall question lead code is 1004 maximum code and this question represents a category which I call acquire release category ok sliding window only It happens from the acquire release, I give it a name, then tell me what is the question. Look, the question says that you have been given this saw, it has only one and zero, so it is said that you tell the biggest one's window, tell me the biggest one's window. Tell me in which it is said that you can make one by flipping the zeros of up to two zeros up to two, meaning basically you know what has been said. Tell me the biggest window of the forest in which the zeros of up to two are heard because it said. Gaya na you can flip at most K zeros so up to two K zeros will come inside it then there is no problem because by flipping them we can make one. Okay then see the question. I pick up a test case. Pick up this test case. Let me take the below test case, it looks like a good test case, it says 'th' after 'g', 'ch', 'ch' is ok, 'ka' is 10, we after 'g', 'ch', 'ch' is ok, 'ka' is 10, we after 'g', 'ch', 'ch' is ok, 'ka' is 10, we will see whatever it is, see this array is given, flipping up to three zeros is allowed, meaning. Whatever your saber has till three zeros, there is no problem. Fapping three zeros can make it ok, so what do you say, I keep J in this, I keep it on the mine, Aa, I keep it here, Aa, the job is to acquire J's. Your job is to release every moment. Your string should be valid. We will acquire where it is now. It has not been acquired yet. Wherever it is now, we will acquire it. It is also not acquired. Okay, I will repeat my point again. Look carefully, J has been placed on MIVE, Aa has been kept at zero, where it is now, it may not have been acquired. Where J is, it has been released. There is no one on MIVE, otherwise something. It has not been released yet, it is okay, where is your window from where does it reside? J Look at the release, always listen carefully to where the window will remain from. J If at some time, I was here and I was here, what would be the meaning of it, J has been released. It will be acquired, if it has not happened yet, then the window is this, you have this window, look carefully where it is, it has been released, i, wherever it is, it will be acquired, it will be in the next turn, then the window is i-1 from your source. then the window is i-1 from your source. then the window is i-1 from your source. How can you find out the size of j window? You can always find out its size. If you ask where is the window, then j + 1 ask where is the window, then j + 1 ask where is the window, then j + 1 is from i -1 and what is its size. i -1 is from i -1 and what is its size. i -1 is from i -1 and what is its size. i -1 - j is its size. Okay. Just see, - j is its size. Okay. Just see, - j is its size. Okay. Just see, if this is the zero index, this is one, this is two, this is three, then see this is at four and this is standing at zero, then what our formula is giving is 4 - 1 - then what our formula is giving is 4 - 1 - then what our formula is giving is 4 - 1 - 0 that is th. So actually at this time there are only three size windows, so keep this thing in mind, again I will express my point, where it is, it has been released, and where it is, it has been acquired. If it has not happened, then the window that will be relevant to us will be from j + 1 to that will be relevant to us will be from j + 1 to that will be relevant to us will be from j + 1 to i -1. This is the window. i -1. This is the window. i -1. This is the window. What is the size of this window. If you are ever given a l2r window, then know the size of your window. What is it? Is both inclusive, then r - l + 1, then inclusive, then r - l + 1, then inclusive, then r - l + 1, then I said that j has been released, i has not been acquired, then window e is j + 1 to not been acquired, then window e is j + 1 to not been acquired, then window e is j + 1 to i -1, both inclusive, then apply the formula, this one is i -1, both inclusive, then apply the formula, this one is i -1, both inclusive, then apply the formula, this one is r - l + 1. - j -1 + 1 then means r - l + 1. - j -1 + 1 then means r - l + 1. - j -1 + 1 then means r - r - r - l + 1 so look according to this formula then l + 1 so look according to this formula then l + 1 so look according to this formula then i-1 ma j will be the size of your window. Okay, if i-1 ma j will be the size of your window. Okay, if i-1 ma j will be the size of your window. Okay, if you have understood the basic things then see what to do every time. What to do? Aa will acquire and increase. We will think that our string has not become invalid. If it becomes invalid then J will acquire and release it and make it valid. After release, we will consider. Let me tell you the answer again. Aa, what will Aa do? We will acquire the element, we will acquire and increase a, now we will think whether this is a string, whether it is valid or not, is it valid, meaning it has more than one zero, if there are more than k zeros. So J will increase till the string becomes valid, it will keep releasing till it becomes valid, after that now J has increased after releasing and valid, we have got the string, we will consider the size of that string and see. Is that our answer or not? Now let's see, I run the algorithm, acquired the income where it was, and increased the income. Okay, it is k3 and k3, so when I queried, I saw how many of my counts became zero. How much should be the count of zero? Gaya has become one, K3 is loud, so what will I do? Look at the meaning of 'Quir'. I have considered this do? Look at the meaning of 'Quir'. I have considered this do? Look at the meaning of 'Quir'. I have considered this element, due to this, the count of I has become zero and I have increased 'Aa', ' of I has become zero and I have increased 'Aa', ' of I has become zero and I have increased 'Aa', ' Acquire, increase 'Aa', now think, Acquire, increase 'Aa', now think, Acquire, increase 'Aa', now think, is it valid? Yes. Valid is valid, why is it valid from Jp to Aa? There is no need to release, now it is standing here, acquired, so we have count two and increased the income, is there any need to release? No, there is no need to release, because till K3 is loud, three. There are only two zeros, so nothing is being released. If the size is two, then we have the longest number of two. How will it be considered? Because of this, it is of size three, will it have to be released? There is no need to do anything because you have got size three inside it, even when you increased it by doing this, the count of zeros remained two only. If there are only two between PW and AW, then there is no need to release it. Just consider it. If it is considered then the size has become four. Now when I acquired it and increased the income, the count has become three. Three is also allowed now. There is no need to release anything, even three are allowed. There is no need to release anything, so the count is done. This time, when we acquired and increased the income by acquiring, the count is done. Four, three, only zero are allowed. Only three, zero are allowed, so now. I would like to say one thing at this moment, the window of my computer has been damaged, it is four zeros, so now it will increase and release and will try to become valid, for how long will it increase till it becomes valid, then see what to do, what should we do now? Hey, it cannot be considered until there is no fear, unless J releases it, J increases, it is zero, so the count reduced and as the count became valid, J stopped, the count was lidded, okay yes J Pv se aa miv key is lit again. We have a string which is of size five which is not beating the previous size so that is our best string. Now the choir starts again. Acquired aa bada count three is valid so now we Our answer is now that we have acquired a string of 6 sizes. The count has been increased by acquiring only three. It is valid. There is no need to release anything. We have already got a string of 7 sizes. Look, the string of 7 sizes is already there. It is J, P is starting from here, J is behind it is starting ahead of A, it is ending before A, so it is 0 00 sa size, there are only three in it, G Ch E, OK, now after acquiring this also, A and move ahead, the count is the same three. There is no problem, if the count remains the same three then there is no need to release your string aa is 0 0100 ha ji is of eight size and this is valid from j p to a miv, only three zeros are fine in this now When it was acquired and increased, the count became four, now it cannot be considered, now it will be released first, before considering, how will it be released, it has moved forward, it has progressed to where it has reached, it will be released, if it is zero, then brother. Count to three and stop, it is valid, stop, now this string can be considered from J to i-1, string can be considered from J to i-1, string can be considered from J to i-1, this string can be considered as 00 and there are only three zeros in it, from J to A, this string can be considered as eight. The size is there but eight size is not better than the last time. Now after acquiring it has become a valid string. Now after acquiring it has grown and the valid stick has become 10. Now when it has acquired it and moved ahead, this count has become four. J is invalid now. We can't consider it. Before considering it, J will have to move ahead and leave something. But J did not leave anything after reaching here. Count three did not happen. J could not leave what he reached here. When J reached here, If you leave it and the count is three, then now the string has become valid. Again, now the string has become valid. This string of yours is now valid 011 0110, it has three zeros in it, whose size is 011 010, if it is not 10, then the answer is no. Okay, now it has been considered, again the count has become four. Can't concede. Ca n't concede. First jab will stop the count again. Count has become zero. Now we can consider it again. So 0 yes but yes, this is going on. Your aa ahead was 00 three zeros that 01 00 has three zeros which is ok now as soon as I acquired it and moved ahead the count became four again so now who will not let you live J will not let you live moved ahead three could not happen Could n't get three, couldn't get three, released it, so we got three, now the answer can be considered, but the string you have at this time, from J to i-1, is string you have at this time, from J to i-1, is string you have at this time, from J to i-1, is dip only. Which is of size five, which is not bigger than 10, so it did not matter, it was considered, here the count is only three, so we will consider it, but we could not beat the size six, but it reached here, it reached size seven, and reached last. Eight size, your answer remained only 10, which had come sometime in the middle, I think 10 had come near here, I think this was I am not shy. 00 This was our answer, had come in the middle, so let me process it again, please pay attention. Look carefully, let me process it once again, then I will code it. Remember the main things. The work of I is to queue, the work of J is to release. It is okay that where I is, it is not queried where J is. If it has been released then the income is being considered wherever it is. Okay, so what will we do first? Finally, query it and then think whether it is valid or if it is invalid. You will have to become valid after releasing. If you have become invalid, then release it, then consider the answer. Then come here. Considered, the count has become one. From zero, the count has become one but it is valid. Income has to be increased always. Again I say, look at my point, come here, what is the meaning of acquire, increased by acquiring, acquired means increased the count to one, you have seen that element, oh look, now we have number of zeros and one. From where are the number of j zeros and ones have come j+ 1 to i -1 so j+ 1 zeros and ones have come j+ 1 to i -1 so j+ 1 zeros and ones have come j+ 1 to i -1 so j+ 1 to i -1 window is also on this time, if j is to i -1 window is also on this time, if j is to i -1 window is also on this time, if j is standing here then j p 1 will start beyond this. Now only one zero is left inside the aa, it is perfect, now look at the next one, how am I doing considering? I increased the aa by considering, the count has become two, it is valid because the count has become three, the count has not become four, it has not become more than three. So there is no need to release, so at this time this string is being considered, so this string is the answer for us till now, this is the best string, this is considered and increased the count to two, so look at this window once to release. There is no need, look at the window, this is your window, it has only two zeros, up to two, up to three zeros also. Okay, so our answer is three. Considered and increased the income. Acquired. Basically, what is the need to release? There is a need to release j from p to i, no, there are only two zeros in it, our count is two, it is telling us that if we increase a by considering, then the count becomes three, but still there is no need to release j+ but still there is no need to release j+ but still there is no need to release j+ 1 to a - 1 if I think. j प 1 to आ - 1 to a - 1 if I think. j प 1 to आ - 1 to a - 1 if I think. j प 1 to आ - 1 think if there are five elements the answer is ours no need to release because if there are more than three then there is a problem now see after doing this when I moved forward by querying and increased the count became four now this window Look carefully at D 00 This window is not correct J Cannot use it What has to be done to use It Release first Who should release J Increase This is zero It has been released The window has become valid, now we can consider the answer. Since the size of the page is five, the answer of Pa was given before us, so the answer was not made. Now by considering this, we increased the income by acquiring. The count is still ours. Now the window is -1. There is Now the window is -1. There is Now the window is -1. There is no need to release because the count is only three, so the answer is 'g', this is increased. There so the answer is 'g', this is increased. There so the answer is 'g', this is increased. There is no need to release, the answer is 'g' seven, is no need to release, the answer is 'g' seven, is no need to release, the answer is 'g' seven, where from j + 1 to i - 1, the answer is ' where from j + 1 to i - 1, the answer is ' where from j + 1 to i - 1, the answer is ' seven', this increased the count is only three. It is going on, seven', this increased the count is only three. It is going on, seven', this increased the count is only three. It is going on, no need to release, the answer is eight, now when this was done, the count became four, now we have to release, so first released this, due to which the count went back to three, now the window we have is this window is 0010 which is eight. Our answer is going on, but now when I have acquired it and enlarged it by considering it, then our window will be of nine size. If we acquired it and enlarged it, the window will be of 10 size, so our answer has become 10. Now when I acquired it and enlarged it, So we will have four count zeros, so now j will have to be activated that man, no man, this is not right. In fact, look once before releasing, this window has become invalid, why are there two zeros and these two zeros four. There have been zeros, j from 1 to i-1 window sp is invalid, j from 1 to i-1 window sp is invalid, j from 1 to i-1 window sp is invalid, so j will have to be increased by validating it, how will it be increased, g is increased, I do n't have this zero, the count is still needed, there is no zero, now go and count. If you have done three, now you can consider this window. You can consider the window of the previous mine where the window of this one has come, then if you want to keep doing like this, then I will show you the code and write the code for it. I will write its code. It is necessary to write. Okay, so the answer has to be returned to you. I have placed A at zero and j at -1. Aa has not been placed A at zero and j at -1. Aa has not been placed A at zero and j at -1. Aa has not been acquired yet. Aa will be acquired. It has been released. Okay, so where is our window formed from? If it has been released, then it will come from j + 1 to i formed from? If it has been released, then it will come from j + 1 to i formed from? If it has been released, then it will come from j + 1 to i -1. Our window -1. Our window -1. Our window is from j + 1 to i -1 and that is from j + 1 to i -1 and that is from j + 1 to i -1 and that window. Do you know what is the size of L? Whenever L to A is inclusive, the size would be r - l+ 1, then you will see its size. If you will r - l+ 1, then you will see its size. If you will r - l+ 1, then you will see its size. If you will see the size according to r - l+ 1, then it will become i min see the size according to r - l+ 1, then it will become i min see the size according to r - l+ 1, then it will become i min a minus h, see a min a p. According to this, it is okay, the work will continue until the last item is queued, the work will continue till the last item is queued, so the window for release is small if the last item is queued. It will be only, it will not be big, we will take a long window, okay, so wall aa lesson, so I have a task, Aakh Mand Ke Choir, then release if invalid and when will you release till you are till again valid, if you have become invalid, if invalid release invalid again first. Acquire after that if invalid release till ants you have come after becoming valid consider the answer then what will be acquired is how easy it is look at the numbers of a look at the numbers of i j is zero what else is one what is ok then I keep a count I take the one who is counting zeros, count of zeros in window, what is the meaning of count of zeros in window, okay, so brother, what do I have to do if I get this cry? If row is found then increase the code. Count or zero window is increased. Our zero is found and after that it is considered. If it has to be increased then aa has been sorted. Now aa will go to the next element. The next one that is sorted aa remains ahead of it. Aa is on Va which we have not seen yet, then it will increase after seeing this Aa. So, without increasing Ko, Aa has increased. Okay, Aat element, we would not have made Aav Takwa. Now see what is the meaning of being invalid, if we mean Ko. Being invalid means that if cozy w is bigger than your k, that is, if you have collected a few zeros from k then you have become invalid. How long will you have to work, as long as cozy w is bigger than your k, you will be invalid. Till then, he will keep releasing it by murmuring, he is sitting on the mic, first he comes to a spot, he comes quickly, should I release it, yes, brother, release it, now what is the scene of releasing it has reached our spot. Let me release it. Okay, if the number of numbers is zero then releasing it will reduce our cozy noise, otherwise nothing else. If it is one then nothing will happen by releasing it. Else I don't want anything to do in this. To explain this, wherever we have come, there is zero, then mine has become minus, else nothing. How long will we do this, until the code is greater than k, will be equal to minus k, we will come out of this. Now if we cut it, then it will be the size. Size of Window: cut it, then it will be the size. Size of Window: cut it, then it will be the size. Size of Window: What is the size of the window? I told you that if the size of the window is i-1, then you will see it with r - ap1, if the size of the window is i-1, then you will see it with r - ap1, if the size of the window is i-1, then you will see it with r - ap1, then i-1 is my formula. then i-1 is my formula. then i-1 is my formula. If this size of window is bigger than your answer till date. If yes, then this is the answer. I know why I wrote it. There is no need to write each code. I wrote this code because if I explain it to you mathematically, you will understand the paper. If you do the code, you will still get stuck. There is a problem. Go boy, I get trapped in this, I don't know whether you get trapped or not, I get trapped, I will explain it in tie complexity, its O time complexity, explain it now, first hit submit, then it is good, beats %, by the way, the code is correct, there is then it is good, beats %, by the way, the code is correct, there is then it is good, beats %, by the way, the code is correct, there is no problem in it. Will beat more use? Yes, I have done it in this, I have beaten 73. The code is correct. How is this On Time Complexity? Look, if someone came ahead then he went ahead, sometimes I did not come back, even if he went ahead, both of them did the whole journey. Sometimes it increases, sometimes it increases, I don't understand its time velocity here, you will understand it well, see this time velocity, see every time, what is happening. Come also look at the time complexity, I know when it happens and when it happens, I tell you carefully, look like this is your thing, if it keeps increasing like this, but do you know what it does every time, it comes to zero and comes back to you again? When I come here, I travel this journey again, then I speak my words again. Look, if Aa and J sometimes look like a loop, then you will definitely see that there is only one wild loop. There a wall does not give proof of the key like i is here j came from zero to here then how much did j go in the beginning when i comes here if j goes this far then how much did j go then if i comes here then If all this goes, then how much is three, then J comes here, and J, if the whole area below goes, this area goes, then J goes four, and when Aa is here, and J, if this whole area goes, then that one goes, five, then this. You know the equation that it is n * n - 1/2 n, there is strength n * n - 1/2 n, there is strength n * n - 1/2 n, there is strength but nothing like this is happening here, it is not happening here, but if you look carefully, I don't know what is happening, see how it is. Every time aa grows, sometimes aa grows, then once aa stops, this time aa grows, then aa grows, again many times aa grows alone, again aa grows, sometimes It cannot cross I, nor will it cross, it will become zero before the code, so A has to do the entire journey, J has to follow it is not happening that J is going to A again and again, so this is not happening. If you look at the code, you will definitely see that there is a while in the while, but this n is not s, because in this one, its j sometimes comes a little further than a and it becomes n s. Submit the code. It is not possible, why is it not possible? The number of numbers is 10 5 n is 10's thing is not submitted, 10 is till 8, 10 is till 9, it is 10, so this is going on in O, the proof of which was 73 user beats. So that's it right, I hope you have understood that this question represents a category which is a very good category so this was the overall question 16 Lee within 9 days prep of 75 is okay so Lee Reached 16 questions in 75 minutes, good progress, got the questions in the morning, it is fun to teach at this pace, it's ok, see you soon.
|
Max Consecutive Ones III
|
least-operators-to-express-number
|
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length`
| null |
Math,Dynamic Programming
|
Hard
| null |
1,011 |
hello everyone let's try to be a cheat code ninja today in this problem we are going to see a very uncommon programming pattern in which we try to reverse fit some solutions and see if they are valid or not so let's begin with the problem statement we are given some packages and their weights and we have to load those packages on a ship in the given order it is also given that we cannot load any more weight than the capacity of the ship and finally we are also given the maximum number of days in which we can load all the packages onto the ship using all these values and conditions we have to find the least capacity of the ship such that we can load all these packages in the given time period let's try to understand this problem using the given example it's given in this problem that we have to load all these packages in at most five days it's also given in the problem that we have to load these packages in the order given hence we cannot be greedy and try to optimize the most number of packages for a particular day so for a particular day we can only choose packages that occur in order so when the ship's carrying capacity is 15 on the first day we can load these five packages the total weight will be 15 and we are not exceeding the carrying capacity of the ship on the second day we can choose only these two packages such that their weight is only 13. now on the third day we can choose only one package with its weight 8 and if we try to add 9 into it then the sum will be 17 which will exceed the carrying capacity of the ship similarly on the fourth day we can only choose one package with its weight as nine and again on the fifth day we can choose the last package with its way test then so we can see that if the ship's carrying capacity was 15 we could load all the packages in 5 days and you can try for other values and see that this will be the minimum weight that will allow all the packages to load in 5 days let's see the intuition and also the pattern to solve such a problem let's use the same example so guys whenever you see a problem in which you have to either maximize or minimize something there's one programming pattern that should always be on the back of your mind and that is binary search we have already covered some problems in the past that use this pattern and I would highly suggest you to look at those problems to get a better idea about this so guys let's see some conditions to determine if binary search will be allowed on a certain problem or not the very first thing that we'll need to determine is if we can find a range for the possible solutions for a problem let's see if we can find the range of the possible solutions for this problem let's first identify the minimum weight capacity of the ship for a valid solution so the best case scenario for us is that we have n packages and N days to load those onto the ship so in this scenario we just have to load one package per day and for this to be possible the minimum capacity of the ship must at least be 10. this is because the ship must be able to carry a weight of 10 which is the maximum of all the packages in general or minimum valid solution must be the maximum of all the packages because if it is lower than that we will not be able to carry the most heavy item similarly let's try to find the maximum valid carrying capacity of the ship this will happen when we have end packages and only one day to load all those packages since the ship has to carry all the items on one single day its carrying capacity should accommodate the sum of all these items in general this maximum value will be the sum of the weights of all these items so for this problem we were able to find the range of all the possible solutions so this is only the first condition to check if a binary search can be applied or not let's have a look at the second condition so for the second condition given a weight or in general a value we have to determine if we can even check if it's a valid solution or not so let's see if we can do that using a random weight of 12 from the given range so on the first day we can choose these four items and their sum will be only 10. on the second day we can only choose these two items and from the third day onwards since the items are heavier we can only load one package per day so this will take 6 days in total and will exceed the allowed time period of only 5 days so we were able to determine if a random value from the range is an invalid solution now let's check if we can determine if a value is a valid solution or not on the first day we can load these five packages and their sum will be only 15. similarly on the second day we'll load only these two packages and similarly on the third and the fourth day we'll load these packages so we can see that for a carrying capacity of 20 we could load all the packages in only 4 days this is less than the time period allowed of 5 days hence this will be a valid solution so guys now we have met both the conditions required to apply a binary search let's see this with a complete example our initial lower and the higher range of the binary search will be 10 and 45 and on the first iteration we'll take the middle of them and check if it is a valid solution or not we see that this is a valid solution where we could load the packages in only three days and since we have to find the minimum possible solution we'll try to look for a lower solution so we'll update our higher range to be one less than this value so the new value that we'll be checking for will be the middle of this range and now we can see that even this is a valid solution and so we will try to look for further lower values so our new upper range will be one less than this value the new value that we'll be checking for will be the middle of this range we can see that for a carrying capacity of 13 this will not be enough to load all the packages in 5 days since this is not valid any number lesser than 13 will also not be valid so now we should try to check for values which are more than 13. hence we'll update our lower range for a next middle value of 15 we know that it's already a valid solution so we'll update our upper range to look for values which are lower than 15. and now for our next middle value we can see that it is equal to both the lower and the upper range so this will be the last value that we'll be checking for this will take 6 days in total to load all the packages hence this will be invalid and out of all the valid Solutions 15 was the minimum so that will be your answer the time complexity of this would be our range of the binary search will be the sum of this array hence the binary search will take log of the sum and for each value in this range we have to check all the numbers in the array so the total time complexity would be and into the log of the sum for the space complexity it would be constant because we are only storing the lower and the upper range let's Implement a binary search solution the first thing that we'll need is to keep two variables for the lower and the upper range we know that the lower range will be the maximum of the array because our ship must be able to carry at least that much weight and for the upper range it will be the sum of the array we already know that if the carrying capacity of the ship will be the sum of the weights we could load all the items in only one day so we'll initialize our answer to be that and then try to minimize it now we'll Implement our binary search in a while loop and this search will only be valid till the lower range is less than or equal to the upper range we'll now check for the middle value for this range we can find that by adding the range and then integer dividing it by 2. and if this value is a valid solution in that case we'll update our answer and since we have to minimize our solution we'll try to look for lower valid Solutions hence will update our upper range of the binary search and if our middle value is not a valid solution that means any value lower than it can also not be a valid solution hence we'll update the lower range of the binary search to try for valid Solutions which are greater than or middle value and once we are done with the binary search or result variable will have the minimum possible answer and we can directly return it but before we complete our solution we have to implement our check function this functions checks if the total capacity for a ship will result in a valid solution or not we know that even if we load all the packages on a single day we'll still need at least one day now let's keep a variable to store the weight of all the items that we are going to load on a current day we'll initialize this to be zero now we'll go through the weights of all the items we can only load our current item if by adding it we are not exceeding the total capacity of the ship so the sum of its weight and the weight of all the items being loaded on the current day should not exceed the capacity and if it exceeds this that means we'll need an extra day to load this item so we'll increment the number of days needed by 1 and reset the weight for a current day to be 0. and finally let's not forget to add the weight of our current item to the total weight being loaded on this current day and finally when we have counted the total number of days needed to load all the items we'll check if the number of days required is less than or equal to the maximum days possible in that case this will be a valid solution we are now done with our solution I will suggest you to look at the binary search playlist to solve more such problems if you have any doubts concerns or feedback regarding this Solution please mention in the comments I always make sure to reply to each and every comment on this channel if you thought this video was helpful please leave a like And subscribe to this channel for more such content thanks for watching guys
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
107 |
alright so this lead code question is called binary tree level order traversal - it says given a binary tree return the - it says given a binary tree return the - it says given a binary tree return the bottom-up order traversal of its nodes bottom-up order traversal of its nodes bottom-up order traversal of its nodes values meaning from left to right level by level from leaf to root so for example this binary tree has a parent node of 3 with children 9 and 20 and then it's child 20 has the nodes 15 and 17 so when we return it's bottom-up 17 so when we return it's bottom-up 17 so when we return it's bottom-up level order traversal we'd return 15 and 17 and then 9 and 20 and then 3 and those are all wrapped in an array alright so how do we make our tree turn into an array of raised like this so if you notice the bottom row is only the number 5 we see that here then we have the next row we have the numbers 2 & 3 the next row we have the numbers 2 & 3 the next row we have the numbers 2 & 3 we see them here and then we have the number 1 and we see that here we can do this with the help of a queue so what we need to do is of course we need an array at the end so let's just create that and we also need for each row its own array so let's just put that down here alright so let's start with the first row you add whatever's in the first row to the queue once you're done adding everything to the queue you then hop off the first thing in that row into the array once you're done that you just add the children of the node that you just added to the array so you add those to the queue and once you're done that step you then add this array which we'll call the row array to the larger array all right so let's do that again what's in the queue it's the number two but first we have to create another row array all right so we add this to be row array now we need to add its children to the queue it has no children on the left but it does have the child five on the right so we'll add that to the queue all right so we're done doing what we need to do with the node two now we move over to the node three so we'll take it and we'll add it to the row array now we have to add any children of three but three doesn't have any children so we're done with this row array all right so now that we're done with that row we have to add it to the larger array but remember this has to be done backwards so we have to make sure that instead of being added to the end of the result array we add it to the front all right so now that we've done that we can move to the last row remember we always need a row array so we'll add whatever is in the queue to the row array then we'll add its children but it has no children so this row is done and then we just have to make sure that we add it again to the front of the result array and that's our final answer all right so let's get to the code what lead code has given us is a function called level order bottom which accepts a root and a root just means the entire binary tree so like I said before the first thing we have to do is hold our result our final results in an array and we'll just call that result next we'll check if the root is null because if it's null we'll just return the empty result array immediately so we'll say if root is null just return result next we'll have to create a queue javascript doesn't have any native queues but we can use its array as a way to emulate it and how we'll do that is we'll just push our results to the end of the array and we will unzip them from the front because remember with a queue whatever is added first gets removed first so we'll say let Q equal unto your a that'll look like this so BR Q and what we need to do is we need to push our root into the Q so Q dot push root that would look like this and this will be our final array right now it's just empty all right and whatever we're about to do we just have to make sure that our queue is not empty so we'll say while q dot length doesn't equal zero so all this outer while loop is gonna do is basically just add the rows are about to create to our final result array well now we need to do is we need to keep track of the number of nodes in the queue so let's say right now we have one node in the queue so we'll only pop that one node out and then add its children later on when we go to the children let's say there are two children per node this node count would be two and it just ensures that we stop after we do what we need to do to just those two child nodes so we'll say let node count equal Q dot length then for each row we need its own array so we'll say let row results equal an empty array that'll look like this alright now we need an inner while loop this while loop builds up the rover's alt array so we'll say well node count is greater than zero will create our row array alright so now we're gonna do is we're going to take this out of the queue and after we take it out of the queue we'll see if it has any children if it does we'll add those to the queue that'll look like this like current node equal Q dot shift in JavaScript shift just take something from the front of an array now we'll check it if it has children so we'll say if current node left doesn't equal null so if it has a left child we'll need to add that left child to the queue we queued up push current node dot left we'll also check if it has a right child we'll add back to the Q so if current node dot right doesn't equal null so if it has a right child then add that to the queue queued up push current node dot right so does the node with the value of one have any left children yes it does it's the number two so we'll add that to the queue does it have any right children yes it does they node with the value of three so we add that to the queue now since we're done adding its children we'll add the current node which is the node with the value of one to the row result array so we'll say row result dot push the value of the current node we don't want the entire node we just want it to value which will be the number one that'll look like this it's now added to the row result array and now we decrement the real count you remember the row count just takes a snapshot of how many nodes there were in the queue before we started this loop alright so now that we've decremented it row count is actually a zero because the node with the value of one was the only one in it at the beginning so now we have to add this row result array to the greater final array so we'll say result which is the final array dot unshifted shipped adds an element to the beginning of an array so add this row result array to the beginning of our final array so result of on shift row results that'll look like this let me just make this smaller so this is going to be added here alright so we'll just repeat that process until we're done traversing the entire binary tree and at the very end we'll just return the result so let's just walk through that real quick remember for every row we have to create its own array so we'll do that here the node count would be two because there are two elements in this queue we will shift this out of the queue we'll check if it is children does it have a left child no but it does have a right child which is the node with the value of five so we add that to the queue and now that we're done all that we move this into the row result array that's line 37 now we do the same thing to the next element that's the node with the value of three so the last node on the second row so we take it shift it out of the queue we check if it has children it doesn't so then we add this to the real result array so now that looks like this and the final thing we have to do with this row is added to the front of the final results array so that would go there and this would go here now we only have one row to go so the last element in the queue is the node with the value of five we check if it has children no it doesn't so we just add it to its row array and there are no other elements in that row so this is the entire row now we just have to add this to the front of the final result array so let me move everything over to make space alright that goes in the front and there we have it this is our result so all there's left to do is return this result so we'll just return result okay let's run the code see how we did looks good let's submit all right so our result was faster than about 77% of result was faster than about 77% of result was faster than about 77% of other JavaScript submissions as usual the code and written explanation or link down below if you liked the video give it a like and subscribe to the channel it helps out a lot see you next time
|
Binary Tree Level Order Traversal II
|
binary-tree-level-order-traversal-ii
|
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[15,7\],\[9,20\],\[3\]\]
**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]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102,637
|
1,032 |
Hello everyone welcome to family without forced engineering and tenth standard electronic subscribe to the Video then subscribe to subscribe our Channel subscribe Video 's Seams Characters List 122 Electronic Bulb Skin Subscribe Now Subscribe That Matchbox with Input Border Not the ID Key Handi Aapke Govinda Notification Aa 108 Dharamveer and Subscribe Complete Comes on I Want Her Will Make to Umpire Dabangg of Chief Another One of the Independence Subscribe Must Subscribe The Channel subscribe to subscribe our Main 10 Famous The Next 20 Years is Pending So Let's Get Started Will give oo from terminal station do subscribe unadhe subscribe to play list directly next back self please subscribe and ji hai to toh torhin boarding ki places pede liquid subscribe to ki dubai scene ther daughters day 9 half subscribe Video subscribe not subscribe to hai Ki Anal Ki Electronic Board The Best Wishes Subscribe Servi Na Subscribe Ke Numbers Question Khawar Produce Question Solved Video subscribe and subscribe the Channel Please subscribe this one Adhir and Hotspot Buildings Appoint Upper Lip Niyama Children Adhir with 6 Minutes Subscribe Button Havy Subscribe Button subscribe Video subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe Quest for Advice Subscribe Now Root Do Subscribe Liquid A Hard Grown Soft Peeth What Do We Get From Resident Evil Subscribe Used Oil Subscribe Don't forget to subscribe Thursday and Subscribe Thursday Subscribe Now 9th Main Chords Marks Domination of Words Will Put a Strict Subscribe Vivo y51 Subscribe Must Not Wash Hard Subscribe Toe's Numbers Interesting Fact Second Text and This Building Subscribe Suggestion subscribe The Channel Please subscribe and subscribe the Video then subscribe to The Amazing Hai A Lip Servi Noida Sacrifices for Lips Usse Zor Ki Abhi A Pendant Udhar Saree Vidyut Subscribe The Video then subscribe to the Page if you liked The Video then That Paschim Vihar Phase Ki 24 Hour No Deposit In Murdo Me Dont False Evidence of a New Delhi Highway Road Office Meeting Left from Route NodeJS VC School Drowned in Darkness Renod and Lakshmi Edison Middle-aged Node Subscribe Check the Mission President subscribe The Channel subscribe 220 Direction Veervikram Please Subscribe to the Limits Increase Size of The Grameen List Thursday Subscribe subscribe and subscribe the Channel Please subscribe and subscribe the Video then subscribe to the Page if you liked The Video then Tomorrow Morning Doing Wearing Basically Hydrating Over All the Word and Wearing Them One by One Internet Software IS Defined the New Attribute to Drut and Guide Update on Thursday Subscribe Must Children More Video Subscribe to Channel Now To Do Loot Liya Gondvi Up and New Cars in Kashmir Valley subscribe kare subscribe Video subscribe that accepted and effective work and during Video subscribe button
|
Stream of Characters
|
satisfiability-of-equality-equations
|
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`.
Implement the `StreamChecker` class:
* `StreamChecker(String[] words)` Initializes the object with the strings array `words`.
* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`.
**Example 1:**
**Input**
\[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\]
\[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\]
**Output**
\[null, false, false, false, true, false, true, false, false, false, false, false, true\]
**Explanation**
StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]);
streamChecker.query( "a "); // return False
streamChecker.query( "b "); // return False
streamChecker.query( "c "); // return False
streamChecker.query( "d "); // return True, because 'cd' is in the wordlist
streamChecker.query( "e "); // return False
streamChecker.query( "f "); // return True, because 'f' is in the wordlist
streamChecker.query( "g "); // return False
streamChecker.query( "h "); // return False
streamChecker.query( "i "); // return False
streamChecker.query( "j "); // return False
streamChecker.query( "k "); // return False
streamChecker.query( "l "); // return True, because 'kl' is in the wordlist
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 200`
* `words[i]` consists of lowercase English letters.
* `letter` is a lowercase English letter.
* At most `4 * 104` calls will be made to query.
| null |
Array,String,Union Find,Graph
|
Medium
| null |
11 |
water you're doing an integer array height of length n there are n vertical lines drawn such that the two endpoints of ith line are I zero and I height I find two lines that together with x-axis find two lines that together with x-axis find two lines that together with x-axis from a form a container such that the container contains the most water return the maximum amount of water a container can store notice that you are not going to be able to slant the container so for example we are given this input of 186254837 and our output is going to be 49. how do we come up with the output of 49 if we look at this container we find the minimum of this and this so the minimum of seven and eight is going to be seven and we multiply that by 7 minus one or in this case which is eight minus one which is seven and our output is going to be 49. let's look at it more visually so that it makes more sense so we are given this array one three two five one four and we have to find the maximum area of a container that can be found with this so in this case what are we going to do is we're going to set two pointers one right pointer pointing to the first element so we're gonna put the right pointer over here and we're going to left put the left pointer at the end of the array so to find the area we're going to do the minimum of the heights over here so to find the area what we're going to do the main off Heights and left and Heights at right and we're going to multiply that with the right minus left so initially what we're going to do is we're going to set our area that we're going to return that's going to be the max and we're going to set it equal to zero so we calculate the area over here our area over here is going to be minimum of one and five which is one and we're going to multiply it with 5 minus 0 which is five and our area becomes 5. and then we're going to compare the maximum of five and zero and our we're going to update our Max to whatever the maximum is so in this case this becomes five then we're gonna see which one of these is smaller so we're gonna see if the right one is smaller or the left one is greater we're going to try to keep the one that's greater so what we're going to do in this case is that we're gonna increment the right pointer since this is smaller and we're going to do the same thing again we're going to calculate the area over here our area over here is going to be the minimum of three and five which is gonna be three and we're going to multiply by left minus right minus left so right is going to be five and left is going to be one so five minus one is four times three is twelve now we're going to compare the maximum with the last maximum since our last maximum is five and twelve the maximum is going to become 12. then we're gonna see which one's smaller the smaller one we're going to increment it since right pointer smaller we're going to increment the right pointer and then we're going to do the same thing again so our mat our minimum of these two is going to be two and we're going to multiply that up by 5 minus 2 which is going to be 3. this is going to be six now we're going to compare the maximum with the current area and the current area is smaller so we're not going to update the max then we're going to increment the right pointer again and now we're gonna see that white is right is five and four so the minimum of five and four is going to be four and we're gonna multiply 5 minus three which is two so this becomes eight and then we're going to compare it with the maximum since it's not greater than maximum we're gonna keep the max at 12. then we're going to compare which one is smaller since left pointer is smaller it's four and this one's five we're going to decrement the left pointer now we're gonna again calculate the area our area this time is going to be the minimum of 1 and 5 which is one times four minus three which is one so this is going to be equal to one since this is smaller than the max we're not going to update Max again now let's quickly code this out and see how this works out for us so what are we going to do is that we're going to initialize two variables variable left which is going to set equal to zero and a variable right which we're going to set it equals to the last element of the rate we're gonna also have another variable called Max area I'm going to set it equal to zero while left is left and right we're going to calculate the area and we're gonna the area is going to be calculated by this formula and then we're going to calculate the max area by calculating the maximum of area and the max area and then we're going to check if Heights left is less than height right then we're going to increment the left pointer else we're gonna decrement the right pointer and in the end we're going to return the max area let's quickly run this of course we're gonna have compile time errors we cannot run away from this there you go let's quickly submit it's a pretty fast solution so this is a two pointer solution thank you for watching
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
68 |
Hello brother, your knowledge portal has again come to Delhi Late with the challenge and today's problem is a very interesting problem and a hard problem and in the top interviews this is basically asked today. What is our problem? Today's problem is that we have an array of strings, okay and what is we have been given a max with format, we have to do something like this, what we have to do is left two right. Justify is to be made, okay, we have to pack in the approach, like this, if the extra space goes back, like we have to form a line, then we do not have to give one extra space in each one, but apart from that, if we have extra space, then what should we do first? If it is possible, then give it. What do we have to do? Give more space on the right. Is it okay to sign on the left? What is left in the last line of text? What do we have to do? If we have to left justify it, then we have to do it. What do we have to do? Instead of inserting all the spaces in between, what do we have to do? We have to put one space between and leave all the spaces on the right. Okay, gas. So in this way, we have to do some word formation and return it to us. Now how will we do this, we have to understand this but before that I will tell you that it is okay to like the video and share it, so let's go. First of all, as you can see, the name of your problem is tax justification. Okay and whatever we are, what we will do, first of all we have to take Giridih approach in our greedy way for this question and what we have to do is we have to do our formation, how will we do it like I say brother, what have I done, I have given an example. Took this, okay, text justification, so this is what we have, this is our vector, so first of all, what we will do is, first of all, we will make 16 spaces 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Okay. So now what we have to do is one by one we have ours first of all ours so what we did we let it be okay now we let it be so what happened to ours first of all we have ours first of all let's look at the length of the words we entered we are this But this is you, this is this, you are okay 422 How much did it come Okay, so now we come If there is length, then how far back have our species gone? There is also a space in this line for one child because the max number was 16. Okay, so can there be even distribution? Yes yes, it is possible, so what will we do, we will distribute it evenly, we will have three, that is the number of words, so we will divide it by 'jo hai tu', four divide it by 'jo hai tu', four divide it by 'jo hai tu', four is ours, okay, so what will we do now, we will distribute it evenly, like this key What we have to do is P Ha I S One Tu Three Four Okay, in the same way we have to make the second line also, so friend, in this way we are going to do what we have, so for this, what do we know, what should we do? Firstly, whatever the story is, we will have to take the line length, we have done it is fine in the line and along with this, we have to check the condition for whether it is getting evenly distributed or not. How much space do we have to give in between and how much extra space is ours? Okay, so we will have to do all this stuff, so for that let us understand this with the court, how will we solve it, so first of all we will go to the court. So we saw that friend, we have to turn my vector of string into a vector of string, so we have made a vector of string gas. This means the size of the rectangle of the answer word, we have taken the length of the starting one, which is the line length of Pushkar, which we just We will move ahead, okay, that is, if I say in which way, as you are seeing here, okay, then if it has come here, then it will be ours, okay, and whatever we are, we will keep moving forward slowly. Okay, so we have to do something in this way, so I have taken the I Plus One, now first of all, how will we take which one, first of all, how will we take the last line, okay, first of all, how will we take that brother, if we have what we have. If we want to set the word, what will we do, so we simply first of all, we had our R inside, okay, so that's what we are going to do is line length which we made a variable plus word dot J dot size Okay, so K minus I if these three plus By doing this, let us say that whatever is there now is either equal or give us greater. What should we say that brother, line length is now flood power, big two is ok, example is ok, so what have we done to find the word number off, minus i is ok and number. How will we get the off space? Then the number of specials will also come out in the same way, we will get our Max with Minus. Now we will construct our line, so what will I take for this, I will take the string line. Okay and now we will handle our special first. What to do if our special how is what if special is how is the special how is the last night in which we have to leave from the right side okay so how to handle the special what will we do in the special how is the first of all brother if the number which The number of words is how many backs is it okay and whatever is in the line, run the words from I plus one onwards is okay, so this one in our last line is also the one in which we have to do even distribution, the ones in the middle are okay. And for the lines, so first of all it was necessary to handle how the last line is and hence for that we have seen first of all, so now what we have to do is now how correct is the word simply space between and what will we do for this, the name species which is our Number of special back has been divided by what we will do Name of word I take what I After taking I we have to run the form again similarly like we ran above I plus one and K plus then we will add in the line most First string of what is the string of space between which we calculated above, this one is fine, once it is called space between and we have put space along with it, next but it is simple, let's run the next word, gas, so this is our acceptance. As you can see, it submits and with this is our submission, so friend, have you seen the video, stay with us like this
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
252 |
how's it going everybody we're gonna sit down and solve question number 252 meeting rooms we're gonna read the question understand it and then I'm gonna walk you through how you can effectively come up with a solution go step by step I'm not just gonna jump into a solution that's not what this channel is all about I want to show you how we come up with a solution okay stay tuned alright let's read the question given an array of meeting time intervals consisting of start and end times where s1 represents II 1 or s1 is the start time II 1 is the end time of the first variable and so on and so forth determine if a person could attend all meetings now some of this sometimes you know people might be scared of looking at like these you know symbols and it's algebraic symbols but effectively all it's really telling you is like you're gonna be gaining an array of tuples right where for those who don't know what two poles are they're just basically the things to have two elements on it right so you're given an array of arrays and what you're trying to do is to see whether or not you can attend all these meetings right we're within that secondary array the first value is when you start and the last value is when you end right so another way to paraphrase this question is think about it as if you were to go to a conference right and you're given basically three time slots right and those three time slots you're gonna be asked the question hey can you attend all three conferences right as a person what would you do well I won't really answer to answer that question I'll forget to see if anything's overlap right so effectively this question has been turned around in a little bit and just we have to think about okay how can we find any of these overlapping instances right because the minute it overlaps that means we already answered the question which is no I cannot attend all meetings right I can only attend say two if I have one overlap if you're given three time slots right so on this question we have to come up in this think about okay how we find overlapping elements giving these ranges right don't think about time just thinking about like a little arrange you know so let's look at an example right the two examples that they give us so the first example it give us like from the range of 0 to 30 right from 0 to 30 that's cool that will set up I set a little bar for us right we could say like okay we start from 0 and we end at 30 right and then we look at the next element right so intuitively or very brute force see how would you solve this right a way to solve it is potentially compare the two elements right we're gonna see like hey the next element here is a 5 to 10 the range right in this case 5 to 10 is within the 0 to 30 range right so therefore by knowing that I already know that I can attend all the meetings I can just return false and get out right away right look at that let's look at that second case which is 7 10 & 2 & 4 all second case which is 7 10 & 2 & 4 all second case which is 7 10 & 2 & 4 all right so in this case we have to ask okay well my range is starting from 7 to 10 right and my next element is gonna be from 2 to 4 well from 7:00 to 10:00 and from 2 to 4 well from 7:00 to 10:00 and from 2 to 4 well from 7:00 to 10:00 and 2:00 to 4:00 they don't overlap one 2:00 to 4:00 they don't overlap one 2:00 to 4:00 they don't overlap one another right if you think about it on a ruler or something like that so in this case I can't attend all two meetings right so in this instance you're thinking about okay what can I do just solve this type of problem I mean I can intuitively think of a solution but how do I actually solve it right so instead of like the front when we think about the algorithm earlier you know we're effectively comparing the two start times in the two end times but that's kind of troublesome right if you wanted to compare the two start times and to end times for every single element right so maybe in these type of questions we have to think about all right so because there's basically two things you do to a question right you get a you know use the existing data structure right or B you could manipulate the existing data structure right or and then you can apply a certain custom algorithm right well don't be scared by algorithm algorithms effectively just any one plus one can be an algorithm it's just a something does the problem right and the data structure is literally just how you store things right it's funny how this industry comes up with like fancy words for some simple stuff like that but back to the question so what can we do to erase that we know that can help us so we don't have to always compare your start and end elements for every single element think about it right so all right what we can do you know we can't assume when things come in you know it's all in the right order can help us solve some of these questions so when you think about it all we're really concerned if things are for example if they were sorted you know by the start times then effectively all we have to worry about is whether or not our end times will ever overlap the next you know start time but that's pretty much it right so by sorting things you already have that attribute like your first element has always going to be of lesser or equal to the previous element right that's one of the key things of sorting by knowing this l but this key attribute then all we need to do right now it's just maintain where my current end time is and then when I look at my next element just compare if to see if my next elements of start time crosses and that's it right so this seems like a relatively simple problem so let's try solving this first of all I'm gonna adjust this a little bit because I like writing my functions this way cool so Before we jump into any question two we have to ask ourselves are there any special notes here given to us are there any assumptions given to us there's none right so we can't assume that a rate input array is sorted and you can't assume the input array is also perfect either right so what I like to do sometimes in an actual interview is ask the question the interviewer you know hey can I get an empty array or hey can I get something with just only one slot if that is the case I'm gonna coat it here if intervals dot length is less than two elements right I'm gonna return true as it of default so if I have one slot I'm consuming that I could go to it even if has nothing I'm assuming that yeah I can't go to nothing that's perfectly valid right so what's the nothing next thing we had to do so the next thing we have to do is enter Valls dot sort right and you want it to sort the elements here whoops okay sort okay turn I'm gonna go your eighth element okay - my be at position eighth element okay - my be at position eighth element okay - my be at position zero when you say eight at position zero that refers to this element right your starting point okay for those who don't know the story function I highly recommend just google it and you'll find out what it why this works the way it does but that pretty much gives us from like you know ascending order great now we have that's cool now the next thing to do is to keep track of our end times right so let n equal to interval dot at the first one we'll just say hard code this into like okay your first element because we already captured a case of if it's only one element then we already returned out of it so we can actually do this particular phrase which is I'm just gonna assign my first end interval to be the first elements and interval right double it up and then now all I need to do is write D I equals two now the first element right or the second element it's gonna be less than intervals dot length right and I'm gonna be I plus alright so we're gonna go through it and do stuff to it right all we have to really check is if my and is you know greater than intervals at my current position in my start time right here's my end gonna be it's greater than my start if it is then just return false right and if it doesn't well and it's less than intervals at I and I have one so I'm gonna check whether or not my current and interval is you know less than the next new and interval if it's less then we probably should update that number right and keep the maximum of it so interval at I and one all right cool otherwise all we need to do is return true right and that should solve our problem so let's submit it and check it out great we got 90% not bad so yeah that's great we got 90% not bad so yeah that's great we got 90% not bad so yeah that's pretty much it that solves the problem if you like these type of questions I go through it as much as I can next video is gonna be the next harder version of this problem and then by doing this first rate question first I think will be very helpful to move to the next one okay stay tuned if you like this please hit the subscribe button and their belt so you get notified when the next video is updated and I hope you guys have a great time Lee coding see ya
|
Meeting Rooms
|
meeting-rooms
|
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106`
| null |
Array,Sorting
|
Easy
|
56,253
|
174 |
or friends to the list of dungeon game this problem basically means we start from the left point and we try to reach the right bottom point and at the beginning we have an initial health point and we can either go right or go down and at each cell it has a integer and the weekend either increase our health point or decrease our point health point but the condition is that at each cell our health point will at least be one so the question is what's the minimum initial health point okay how do you think about this problem actually wash one thing for sure is that at the bottom right point our health point can only be one right I mean in the end up Oh our health point be one that's enough so that's the minimum so we can use that to calculate its previous States and we know that the minimal health point edge at this cell is not a dependent by its previous States and it's depended by the future States because we already know the final States so we should think in a reverse way and we can also treat this problem as a dynamic programming problem so now let's think about the algorithm we will new a DP array and its size equal to M plus 1 times n plus 1 why we need a plus one really that if we do not use the plus one we use the same size in the dungeon then if we add to the last row of the last column we needed to specify these cases but if we use the one more we do not need to sink in that specific cases we just need a general formula so that's it that's a reason okay then we know in the end it can be one right so we just initialize this DP Rho into G max value except these two points this Q point will be 1 and then we choose the minimum actually the SM is 1 right so at this place our health point will decrease by 5 so we can that means we need a fine more so we just surplus this 5 then we get a 6 that means the in order to reach that point our health point should at least be 6 because 6 minus 5 equal to 1 we are self okay use the same idea we try to calculator is laughter meaning my health point in this place we choose the because we can either go right or down right so in this place my minimal health point is depended by the right and the done minimum health point then we can its minimum which is 6 and the 6 and at this place my Health's point will be increased by 30 so I will minus 30 and then I get a negative number which is negative 24 but my health pointer can never be less than 1 so I just put a 1 here okay how about this place its dependent always the cell down in the cell oh it's right so I pick the minima which is 6 and this place I just will increase by one so I - this one this is the minimum one so I - this one this is the minimum one so I - this one this is the minimum health pointer I needed to reach here so I read five let's see this example well I also choose the minima from its below and it's right I get a five in his place is apology three so I can just a - the is apology three so I can just a - the is apology three so I can just a - the strip because we're rich here I will my health pointer will be increased by three so I do not need it these three so I - it so I get so - so on so forth so I - it so I get so - so on so forth so I - it so I get so - so on so forth so you will know the formula is that DP IJ it represents a minima health point I need either to reach the position I J and it's equal to the minimum it's right in the cells below minimum - the dong in the cells below minimum - the dong in the cells below minimum - the dong zhuo IJ o kzc the formula mass minimum tip here I plus 1 J this is the next row and this is the next column it's minimum - the dungeon I J - the dungeon I J - the dungeon I J and once this actually this is not T P IJ this is the minimum tip him if this minimum DB is less than 1 I pull out this place equal to 1 otherwise I just keep the value okay so finally we just return DP 0 let's write the code now we first get and which is down gender lens and am sorry this M this is a dungeon zero tolerance and we need a deep here array it's a represents the minimal health point we need to reach high J and we do some initialization I plus so just fail all the value to DPI tutor integer max value but we have two cells which is the M minus 1 equal to 1 and the deep him M minus 1 also yeah minus 1 and n equal to 1 and then I will start from M minus 1 I plus greater than 0 I plus oh I - - and the 4 than 0 I plus oh I - - and the 4 than 0 I plus oh I - - and the 4 into j equal to a minus 1 j quit or equals n 0 j minus - we first try to get equals n 0 j minus - we first try to get equals n 0 j minus - we first try to get a minimal HP which you caught you mass minimum tipsy I plus 1 J and the deep here I J plus 1 we - the dongjun IJ and here I J plus 1 we - the dongjun IJ and here I J plus 1 we - the dongjun IJ and if minimum HP is less than 1 where's less than 1 that means there may be the dungeon IJ is a larger positive integer so we should at least give me the equal to 1 so dvi-i j will you go through one to 1 so dvi-i j will you go through one to 1 so dvi-i j will you go through one else DPI J will just a bit minimal HP so finally we return DP 0 this place is this true place is the last row and this is the last color okay thank you watching see you next time
|
Dungeon Game
|
dungeon-game
|
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.
Return _the knight's minimum initial health so that he can rescue the princess_.
**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
**Example 1:**
**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
**Example 2:**
**Input:** dungeon = \[\[0\]\]
**Output:** 1
**Constraints:**
* `m == dungeon.length`
* `n == dungeon[i].length`
* `1 <= m, n <= 200`
* `-1000 <= dungeon[i][j] <= 1000`
| null |
Array,Dynamic Programming,Matrix
|
Hard
|
62,64,741,2354
|
304 |
hey guys i'm solving this question today uh from late code challenges so the question is given a 2d matrix handle multiple queries of the following type calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner row one comma column one and lower right corner column so what's what we are given is that we are given a matrix and we have to calculate the sum of elements from the index let's say we are given index one comma one and two comma and then we will calculate the sum in that region so the matrix is given like this above and the queries are like two one four three two comma one is so 2 comma 1 is this 2 and 4 comma 3 is this cell is 4 comma 3 so we have to calculate all the item elements from we have to calculate the sum of all the items in this range so what's the answer here the 2 0 1 that is 3 plus 1 4 plus 1 5 and 3 8 so see if we see the answer at first we will be printing null for initializing a matrix and then calculating the region sum that is eight here and then in the next input what we are doing is we are calculating from 1 comma 1 to 2 comma 2 so this is the one that i discussed before 6 3 that is 9 and then 2 11 so our answer is that's how we have to do it now let's talk about the boring part but before that first you should try at your own so you can stop this video once and try it out yourself the approach is very simple what we can do is at first let's consider a variable matrix given this a b c e f g h so what we can do is uh at first we can make a prefix array that will store the sum of uh elements up till i comma j index let's say i want to calculate a sum of till b so that will give me a plus b if i want to calculate the sum up till f so i'll get a plus b plus e plus f if i want to calculate sum octave g i will get a plus b plus c plus e plus f plus g okay so how do we calculate this prefix array yeah for the first row and first column it's very easy to calculate we can calculate easily so what about if we calculate about four one comma one index so what we can see is we are using the set operations here just say we are ready sorry minus sum up till a so that will give us f plus a plus b plus a plus c minus a that is uh we will get f plus a plus b plus e and that is the prefix sum up till f okay so likewise we will be able to calculate all the um prefix sum of any okay now the second thing is once we make our prefix how will we calculate a sum from index i comma j to i to comma j so that's also very simple let's suppose we want to calculate some the now we can see that we are subtracting a two times so what we are doing is i my i1 minus 1 this row and j2 is this column so fro up tills uh sum up till c okay and subtracting again i 2 comma j 1 minus one and this is what is uh this is i two and j one minus one is this thing so sum up till m okay so we are uh taking the sum up till this then subtracting sum up till this now subtracting some octal m and adding sum up till a so that will give our answer okay so now let's discuss the coding part so here i okay so now is what we are doing is we have already assigned matrix zero to vector zero okay so uh for the next elements we will just uh take the matrix value plus uh that vector previous value that will give us the prefix sum of this row okay now we will take the column sum okay so we are doing the same way vector i zero is equal to matrix i zero plus the previous row okay that is it now what we have to do in the uh two iterations see we are iterating one for minus one minus vector i minus one j minus one yeah this is the same i told you in the next so initially our answer will be 0 we are calculating the answer plus equal to vector so row 2 comma column 2 we did the formula okay so in the explanation part what i told you was we have to just first take the answer uh from the prefix sum uh up till row two comma column two then subtracting see i have taken this uh just condition if uh row one given is just in the first row so that we cannot subtract row one minus one from there so let's see it carefully if rho 1 minus 1 is greater than equal to 0 then only we will apply this condition that answer minus equal to vector rho 1 minus 1 column 2 okay and if column 1 minus one is greater than equal to zero we will what we will do is we will uh subtract answer minus equals to uh vector row two column one minus one okay and at last what we'll have to do is we will just add written you
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
201 |
hello guys welcome to my channel and I'm gonna solve the bitwise end of numbers range which is number 201 in lick codes so we're given the range from end to end where m and n is bigger than 0 and smaller than the maximum value of integer so we have to return the bitwise ends of all numbers in this range inclusive so let's see an example we have two numbers which is rip which is expressed as by new number so and repression and oppression is compared to number which is zero in one if the 1 and 1 becomes 1 and 0 1 becomes 0 and 1 and 0 becomes 0 so if I use end oppression for those two numbers becomes 0 in this case okay so then let's see another case we have 1 0 1 and 0 which is 0 as integer number if I use n 2 operation for those two numbers I can get it's a 0 because whatever the number of comparing is if that number meets zero it becomes always zero so we can get the first rule from this case so any number and zero becomes always zero right I just enumerate all numbers from 1 to 15 so that corresponding the binary number to each integer number then I'm gonna find the simple rule with two numbers so if you see one in two I will show you more examples then you can find the rule between two numbers why I just used red rectangles between those two numbers okay so 1 & 2 3 & 4 7 & 8 two numbers okay so 1 & 2 3 & 4 7 & 8 two numbers okay so 1 & 2 3 & 4 7 & 8 and 15 and 16 do you get what why I used why I highlighted those two numbers let's see from the first one into the one has just one as a significant digit but 2 has two teachers as a significant digits right and let's see 3 or 4 3 has 2 in for as 3 & 7 has 3 but 8 has 4 in 2 in for as 3 & 7 has 3 but 8 has 4 in 2 in for as 3 & 7 has 3 but 8 has 4 in 15 has 4 and 16 has 5 what does a mean is that if you use end operation between those two numbers you can get always 0 because the digit is not same so the border of those range becomes always 0 so 1 in 1 0 will become 0 & 1 & 1 0 become 0 because if you 0 & 1 & 1 0 become 0 because if you 0 & 1 & 1 0 become 0 because if you see the 3 it is smaller than 4 which is the three digits smallest three digits number but it is smaller thing though smaller than 4 is minus 4 minus 1 so it must be the biggest number which has two significant digits and 7 is also the biggest number in the in which has 3 significant digits but if you see if you meet 8 those three digits becomes all 0 and it increases the 1 digits in the first stage it becomes 1 so anytime you when use end operation between two numbers you can get always 0 so it means that number of significant digits in start is not equal to number of significant digit in end it the result becomes 0 so if you see the 7 & 8 the number of digit if you see the 7 & 8 the number of digit if you see the 7 & 8 the number of digit of the number of significant digit in 7 is 3 in 8 is 4 so it does not same it is not same so if the range includes those borderline the result would be always 0 because any number would and 0 become 0 so if you include at least one 0 the result will be always 0 okay so then now we can get is that how they help out we don't include the range of the border like this example so from 8 to 15 those are the those range does not include the border line so let's say the start number is 9 and end numbers is 14 if is if you see this numbers all we can get is if I use end operation among those two numbers what I can get is there the first digit sow all one so I can get at lists one at least a list 8 because the first digit in the one in four numbers because it becomes 8 right so now you can compare the rest of digits in those numbers as you can see those three digits you can see another pattern as you saw before so if you see the first line and you can find the borderline of those two numbers 11 and 12 if you see the second digit of those numbers you can see the first digit is 0 and second digit first the 1111 of first digit is 0 and 12 this first it is as it becomes 1 so what I can get is those number becomes 0 right as this way you can calculate the all rest of digit if this number does not include the borderline all right then let's dive into the cold right now I'm gonna use the weights it's wise and function which is getting parameter and so first time first I'm gonna compare those two numbers because if the two numbers are same no I'm gonna return just number itself because if the num is five and five same number becomes five because the one zero consists of those numbers all are same the older are the same and all number of ones and all numbers you are same so it's gonna return the number itself M or n so I just I'm gonna just use M for this case and I need variables which is start with M and end range which is n for this case and what I'm gonna do is I need to count variable count one just zero and count to it to 0 also and what I'm gonna do is I'm gonna divide those numbers by two ends I'm gonna find what those numbers are in which scope so if the number is in this line or that line I have to find if the significant digits of starting number and n number and I have to compare them and if it is that same it gonna be always 0 for the results so I have to find what the number is in which scope so until in smaller than 0 and I'm gonna no sorry it's not in this its I'm gonna divide by 2 and I'm gonna count it and also until it's I'm gonna divide by 2 counting those numbers so I can compare those two numbers counting 1 and counting - if it numbers counting 1 and counting - if it numbers counting 1 and counting - if it is not same it means that the range include ranges include including the borderlines so what did I say they if the range includes borderline it is gonna be always 0 in that case and if it is not I have to get the first digits of those two numbers because if the scope is same the first digit would be always 1 so I can get those 1 from that number so hmm so that numbers would be leftmost number it becomes the power of 2 in the count - it becomes the power of 2 in the count - it becomes the power of 2 in the count - 1 this number is our important number we can add those number into our array so and I'm gonna return it with lm+ return it with lm+ return it with lm+ and it's wise end and mmm again a minus Ellen and anyway miss Ellen because I have to subtract the Ellen from the start range end and the end range so through this way I'm gonna calculate the calculate these significant digits recursively so if I use this algorithm I can get the result of all numbers in the range so I have to return it twice end and then passing the parameter same and end all right so let's submit this algorithm Oh what is this problem Ziggler C&T it's not all I'm sorry says Ziggler C&T it's not all I'm sorry says Ziggler C&T it's not all I'm sorry says so because C 1 and C 2 are same whatever you use I'm just I go to st. you one so sorry for a mistake yeah it works perfectly okay so thank you for to watch this video and see you next time bye you
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
45 |
welcome to mazelico challenge today's problem is jump game two given an array of non-negative integers nums an array of non-negative integers nums an array of non-negative integers nums you are initially put positioned at the first index of the array each element in either ray represents your maximum jump length at that position now your goal is to reach the last index and the minimum number of jumps so that's what we want to minimize the number of jumps now you can assume that you can always reach the last index so it's a little bit different from jump game one where we're trying to see if we can hit the last index here we can assume that we always can it's the number of jumps that we're trying to minimize so obviously first impression here you could write something recursive right you can start at the first position and recursively call each one of the paths that we can take and count the number of jumps that we can get until we hit the last index and return that and then get the minimum one out of all our recursions but that's going to be exponential time complexity it'll end up being n factorial so we're not going to even bother with that um we know that's not going to be up um accepted so what we can do of course you can use memoization and that would actually probably work but we don't really want to over complicate here what we can do is create a dp array and all these will be starting with zero actually they'll all be infinites except for the very first position and because the very first position we know we can get there that's like the base condition uh that requires no jumps right so we start with zero what we'll do is start the first index and iterate down the number of jumps that we can take so here we know we can move to index one and index two and what we'll do is take the minimum between whatever's here and uh whatever the dp array of that position is plus one so here's zero plus one equals one so that's gonna be one and same with here all these are gonna be one and that makes sense right because at these two indexes we know we can get there in one jump now we'll move to the next index number and this is three first we'll check here we'll take the minimum of whatever's here or one right here at this first index plus one that's two right but that's less or less greater than what we have already here so we keep one here though this is going to be infinite so we start with two same with here two and then we just move on continually with this algorithm and what we'll find is at the very end this index number is going to be the minimum number of jumps that we could have taken to get there so hopefully that makes sense let's go ahead and go that out we'll first initialize n and we want to create a dp array with float infinites for blank and range of n now the very first position we know we want that to equal zero so now we just need to write in this different for loop for i and range of n and for j which is going to be a number of indexes we can move forward in range of nums i but uh we don't want to count the zero we don't care about that and we also want to make sure that we actually move this many positions so that's gonna be plus one here now if i plus j is in bounds it's less than n well then let's update our dp array for i plus j to equal the minimum between dp i plus j or dpi plus one now at the very end we just want to return whatever is at last in our dp so see if this works okay that looks like it's working so let's submit it and there you go accepted so that surprises me that this gets accepted time complexity wise it's n squared as well as of n space but as we were coding this out you might kind of realize that it's kind of pointless doing this whole minimum looking backward thing like once we update this dpi plus j it's like we already know that's that like we don't really ever need to update it again um so really you don't actually even need to do this nested for loop we can do this in a greedy approach what we could do as long as we keep track of all the important variables we can start with keeping track of what our max position that we can reach is as well as the max position that we kind of reached before uh so what i mean by that is say we start with here starting with zero how far can we go we know we can get all the way up here right so great now we'll move forward and we'll find that at three well we can actually move all the way up to the end here but we're going to keep track of that in a different some different um variable this is going to be the max that we can reach and this is going to be the last max that we could have reached and up and only until we hit as we iterate down that we hit this that's when we'll increase the number of jumps so here like starting with here we increase jump to one and then we find that once we hit one we've hit this part and we want to um see if we'll update this last position all the way up to the max one that we could hit so far we'll increase our jump and we'll just keep continuing that way and we'll find out we're not going to increase jump anymore we'll be up to two jumps at that point and then we'll stop well one thing to note is we'll stop right here we don't need to count at the very last index all right so um hopefully that makes sense what we'll start by initializing some variables that we need the i uh to iterate down our array number of jumps that we've taken the minimum number of jumps as well as the last position the max that we kind of hit like at one point as well as keeping track of the real max position that we can get that we can hit so all of these will be zero here so while i is less than n minus one what we'll do is uh first calculate our max position the max position is going to be the max of max position and it will be i right this index plus nums i now if last i equals our last position that we could hit so far it starts with zero but we're going to update this to be the max position that we've calculated and this is where we're going to increase our jump plus one and here we always need to increase our eye and at the very end jump should be minimized um that'll be the middle number of jumps that we could have taken to hit the last position so it's kind of like this little flip-flop here with this last position flip-flop here with this last position flip-flop here with this last position in the max position let's see that equals two let's go ahead and submit it and there we go so this is actually all end time and we use constant well no we start this dp array so uh it's still all of in space but still oven time complexity is way better than o of n squared so i would say this is the best solution uh let's see oh wait i don't need this i don't know what i'm talking about yeah that's silly me we don't even need that so it's all one space right let's make sure it works yeah so it's all one space okay great i think uh that explains it thanks for watching my channel remember do not trust me i know nothing
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
1,855 |
alright guys welcome back to study plan binary search day 11 the first problem for today the maximum distance between a pair of values so you are given through non-increasing so you are given through non-increasing so you are given through non-increasing zero indexed integer arrays number one and then a pair of additions e and g where e is between zero and the length of number one and g between zero and the length of numbers two is valid if both e is smaller day g and numbs one of e is smaller than number two of g the distance of the pair is g minus e we return the maximum distance of any valid pair e and g and there are no valid pairs we return zero so an r array r is no longer seen if r e minus g is bigger than r of a for every e between one and r a little plate so for the example one this is our amplitude and output is true because the valid pairs are 0 etc the maximum distance is 2 with pair of 4 my 4 and so 4 minus 3 is 2 and it's the biggest one okay let's see how we can solve this one let's make answer equal to 0 first it is the max distance between valid percent and now let's say let's make okay let's make a linear scan through the shortest array so for e in range okay now let's check if lump's e is bigger than numbs2 of g okay if it's easy we continue now let's first in the first one the first value of the pair should be equal to num s1 e and now let's make binary search so the left side should be e and the right should be the length of lambstone minus one now while our left is more equal than our right in this case g should be equal to the left plus or rise divide by two and we check if the first one is smaller or equal than numbers to of g if it is we update the left will be equal to g plus one and otherwise we update the rates okay now let's calculate the answer let's update the answer so the answer should be equal to the box of answer and the new pair which is n minus e okay i guess that's it finally let's just return our answer so the space complexes of this algorithm is constant so here the space complexity is constant and the sum complexity is unlocked then okay something came along let me check i don't have any ideas wrong so here i just make a typo mistake the return should be outside of our booklet okay let's submit and yeah so it's all fine i hope this video was useful for you i'll see you soon
|
Maximum Distance Between a Pair of Values
|
maximum-distance-between-a-pair-of-values
|
You are given two **non-increasing 0-indexed** integer arrays `nums1` and `nums2`.
A pair of indices `(i, j)`, where `0 <= i < nums1.length` and `0 <= j < nums2.length`, is **valid** if both `i <= j` and `nums1[i] <= nums2[j]`. The **distance** of the pair is `j - i`.
Return _the **maximum distance** of any **valid** pair_ `(i, j)`_. If there are no valid pairs, return_ `0`.
An array `arr` is **non-increasing** if `arr[i-1] >= arr[i]` for every `1 <= i < arr.length`.
**Example 1:**
**Input:** nums1 = \[55,30,5,4,2\], nums2 = \[100,20,10,10,5\]
**Output:** 2
**Explanation:** The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).
**Example 2:**
**Input:** nums1 = \[2,2,2\], nums2 = \[10,10,1\]
**Output:** 1
**Explanation:** The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).
**Example 3:**
**Input:** nums1 = \[30,29,19,5\], nums2 = \[25,25,25,25,25\]
**Output:** 2
**Explanation:** The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[j] <= 105`
* Both `nums1` and `nums2` are **non-increasing**.
| null | null |
Medium
| null |
63 |
in this video we're going to take a look at a legal problem called unique path number two so this question is very similar to unique paths number one i think you if you get that question you probably should be able to understand how to solve this problem so same thing here so the robot locates at the top left and everything looks fine but the thing is that we're given an obstacle right in this case you can see we're given an obstacle we want to find totally unique path for uh if we're starting at the top left right so in this case you can see that an obstacle and space is marked as one and zero respectively so if i have obstacle i that means is one right there's a one there and that means that for this position to reach the bottom right is going to be zero right there is going to be zero path to reach the bottom right so you can see here for this uh in this case for this example there are two way you can do it this way or you can go to down right so there's only two paths because there's an obstacle so how can we solve this problem well in this case same thing just like how we did it in unique path number one for each and every single cell we had to go to the right to figure out how many unique path if we go to the right plus the total unit path if we go down right so you can see here that uh if there is a obstacle if the current cell is one then we can just return zero because there's no unique path to reach the bottom right there's obstacle right and then same thing on the right the same thing for the current cell right in this case we're starting at um the top left and if there's a situation where top left or the current cell is there's obstacle and same thing there's no way there's zero ways that we can reach the bottom right either so let's just jump straight into the code and if you're confused i highly recommend to check out the unique path number one before checking out this video so basically the idea is that we're just going to have a integer array set as a global variable so we're going to have a grid let's just call it grid so this dot grid is equal to obstacle grid so what we're going to do is we're going to have a helper function and we're going to start at zero right so basically for this function what it does it will return the total unique path for this given coordinate right so in this case we're gonna have a method called helper which takes a row the current row that we're on and the current column that we're on so then we're going to do is we first check to see if uh if the current coordinate is out of bound right so just like the unique path number one we can either go right or go to go down so what we have to do is we check to see if row is actually bigger than or equal to grid.length or equal to grid.length or equal to grid.length or if column right is actually bigger than or equal to grid at zero that length if that's the case then we can just return zero because they're total uni uh if we're out of bound they're pretty much there no way that we can go to the bottom right so then we're going to do is we're going to see if the current element is actually a in this case is a obstacle right if it's obstacle then we can just return 0 as well so if grid at row at column is equal to one then we can just return zero because this is the obstacle we there is no way that we can reach the bottom right okay so now we know that the code that we're gonna right now is gonna be very similar to unique path number one so basically the idea is that uh we're gonna go down right so if i go down for total unique path uh if i go down it's gonna be row plus one and the column is to be the same and if i go to the right in this case is going to be row and the column is going to be column plus one and then what we're going to do is we're going to return total unique ways right total unique ways if i go down plus total unique ways if i go to the right and this will give us total unique ways to go to the bottom right for this current position one thing that i forgot to do is if the current position right is equal to the last element right in this case the grid or the bottom right then we can just return one because we found one way right so if grid at row or i should say if row is equal to grid dot length minus one and column is equal to grid at zero dot life minus one then we can just return one because we found one way now if we were to run our code you can see we have our success so you might be asking like okay what if the last position in the 2d array or the grid is a obstacle like if this element is a one like what they're like can we still go there in this case we can't because there's an obstacle then there's zero way to reach the bottom right so what we can do here is we can that's why what we did here is like we first check to see if the current position is a one if is one we can just return zero because there's zero way to return to the bottom right and then we check to see if the current position is a bottom right position right so basically what i mean what i'm trying to say is that if the out last element in the grid is a obstacle then we can that means there is no way that we can be able to reach there right so if i were to set this like set this zero to one you can see we still have succeed okay so what we can do here is we can check to see if the starting point and the endpoint is uh is one right if it is a one then we can just return 0 because there's no way that we can reach the bottom right so what we can say is this we can say if grid at 0 right is equal to 1 or if a grid at um integer m is equal to grid dot length and n is equal to grid at zero dot length so if grid at m at n is equal to one as well we can just return zero because there is no way that we can reach there right so now if we were to run you can see okay well let's see it's gonna be m minus one and n minus one sorry so if we were to run the code you can see we have our success but this will give us a time complexity of exponential so we're going to uh use a 2d cache array to store the precomputed value so what we're going to do is that if this condition didn't really satisfy we're going to define cache is equal to new integer with the size of m times n so what we're going to do is that if this position is already being pre-computed before so if pre-computed before so if pre-computed before so if cash at row at column does not equal to null we can just return cash at row at column and then same thing here what we're going to do is that we're going to cache this and save this data onto our cache right so cache at row is equal to this and we're just going to return a cache row at column okay so this will basically bring the time complexity from exponential to a m times n where n is number of rows we have and n is number of columns that we have so now let's try to submit our code and you can see we have our success and now let's take a look at how we can be able to do this using a bottom-up be able to do this using a bottom-up be able to do this using a bottom-up approach so to solve this problem using a bottom-up approach basically what a bottom-up approach basically what a bottom-up approach basically what we're going to do is that we're going to have each and every single cell uh computed based on the bottom cell right and the right cell right just like how we did it in the unique path number one the bottom up approach for each and every single cell if we want to know the um the you total unique path for this position to reach the bottom right in this case it's just going to be one because in this case this current position is going to be a bottom right position and we're just going to return one where we're going to set the cell to be one because there's only one path and if i'm here then in this case the there's total of one right because in this case we only have one unique path to go to the bottom right in this case just go down right if we go right and then there's out of bounds so we can't have that and if we have an obstacle if the current cell is the obstacle then what we're going to do is we're going to set the current cell right the total unique path for current cell to reach the bottom right it's just going to be one uh sorry zero because there's no way that we can do reach the bottom right so we're going to do that right and that's the main difference between this problem and the other problem the unique problem path number one is that we have an obstacle and if we have an obstacle we can just set it to zero if it's not optical we can just basically uh computed based on the bottom cell right based on the bottom cell plus the right cell that was pre-computed the right cell that was pre-computed the right cell that was pre-computed before okay so now let's take a look how we can do this in code so first i'm gonna rename this right you we're gonna use a grid instead of a obstacle grid so it's equal to obstacle grid okay so then we're going to do is we're going to have our m which is equal to grid dot length and we also have n which is equal to grid at zero that length now in this case we're going to have our create our cache array and the cache here is we're gonna have a cache array with the size of m plus one and n plus one and the reason why we have n plus one and n plus one is kinda like a temporary row and temporary column that we're probably never gonna use i mean we're not going to like overwrite it but we're just going to use it to compute the last row and the last column in our current grid it's kind of like this where we have a last call a temporary a cash array with the extra column and extra row and then to compute this value we're just gonna you know check the right and check the bottom right in this case the bottom has a zero by default every single elements in the cache is zero so in this case this is a zero this is zero so the total unique path to reach it here is just going to be uh zero plus one because in this case this is the last element in the grid so we're just gonna set it to one but if it's here we're just gonna look at the right look at the bottom here this is a this is one and this is zero one plus zero in this case we have one way one unique path to reach the bottom right and if this is the obstacle then right away we're gonna set it to zero right so this is what we're gonna do is we're gonna start we're gonna have an eye pointer which is start at m plus one oh sorry uh m minus one uh the reason why we do m minus one here is because if you notice we're going to have an extra column an extra row so where do we start in this case where you we're starting at the second last column and second last row right so in this case we're going to have i is equal to m minus 1 and for each and every single iteration while i is bigger than or equal to 0 i minus right we're also going to have our inner for loop which is j is starting at n minus one and while j is bigger than or equal to zero as well so j minus okay so what we're going to do is that for each and every single iteration first what we're going to do is we're going to check to see if the current position is a one right if it's an obstacle then uh what we're gonna do is we're gonna just go into uh set work or i should say continue because by default the integer 2d array cache array is going to be zero so what we're going to do is for grid at i at j right if grid at i of j is equal to one that we can just continue right because we know that okay at this current position is a obstacle right and then we're gonna do is that if uh if the current position right if uh i is equal to m minus one and j is equal to n minus one right we're at the last or the bottom element then we can just set this position in cache at i at j to be uh to be one because we know there's one path to reach the bottom right which is the current cell otherwise if it's not the bottom right what we're going to do is we're going to say cash at i at j right is equal to the total unique path for the bottom cell and total unique path for the right cell right so bottom is equal to cash at i plus one and j right and we also have the right which is equal to cash at i at j plus one so this will give us the right the total unique path for the right so for this current position is gonna be bottom plus the right will give us the total unique path for the current cell right and at the end we're just going to return the cache as zero okay at zero so the top element right here so we want to know total unique path for this position right so the top left so if we were to run our code you can see we have our success right so if we were submit you can see we have our success and this will give us a time complexity of m times n and space complexity of m times n as well
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot 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.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
350 |
cool 350 intersection of two arrays to coming to a waist right and then write a function to compute the intersection and you have some bunch of examples are you share them in the associative search when you know the ya thinks going to follow up do we have to worry about them we still come in any order okay I mean I think this is just like a little bit of an extension of the set intersection which you can calculate with a hash table so I think that's what I'm going to do yeah but dictionary I guess in Python and then you could kind of just print out and there are constraints and then after that I guess we'll look for the follow-up oh and yeah we'll look for the follow-up oh and yeah we'll look for the follow-up oh and yeah I will go over the complexity in a second sure and now we just in Oh oh and using different languages I'm not quite sure if I think this you're working a goddess oh god I mean I guess that's correct ish little orders not mine we've test some empty case maybe just in canyons showers like a passive metal going down okay cool yeah so this is words I'll be straightforward and to analyze this is linear time and in your space know just the size of hash table and there anytime plus we just go from oh and plus M where n is the number of numbers in numbers 1 and M is the number synonyms - yeah this relatively straightforward - yeah this relatively straightforward - yeah this relatively straightforward and usage of hash tables I don't think you should trip you up if it does you need to practice up like this is very fundamental I finger on them as an interviewee this should be straightforward as I mentioned and kind of yeah I mean it should not charge you as an individual I probably don't think I would give just this problem or just this as a poem as an interviewer I would expect you to maybe in the incorporate this problem into part of a bigger part maybe there's some or the statistics thing where like your accounting like accentuated like you have to spawn but one more layer of abstraction so that you're doing something with this output right so i layer it that way if I was doing interview but uh where otherwise well is a straightforward form Oh let's check the follow-ups where they Oh let's check the follow-ups where they Oh let's check the follow-ups where they come in a way so I saw how would you optimize at my algorithm if the way it's already sorted we can actually use to the two-finger algorithm so you have a the two-finger algorithm so you have a the two-finger algorithm so you have a pointer on the first away and the point of on the right away and then kind of just moved him in tantrum it's still linear time but you know space will become constant so that is you know better what is number size one is smaller sighs - which arguments better I think sighs - which arguments better I think sighs - which arguments better I think well I mean it doesn't really matter I mean I per se again I mean you want constant space that's obviously slightly better but you can actually do things like I was really worried about memory usage I would do maybe instead of just generic like here we always put the numbers of num1 numbers one into the hash table but really we just do a small if statement like a if there are more numbers and numbers one then you use the other thing to put in your hash table and then just go through the other away linearly I mean they're minor optimizations which I guess an integral term I asked but I shouldn't be a paid to ioi what if the elements are numbers - I stored on disk and the memory is to - I stored on disk and the memory is to - I stored on disk and the memory is to me so that you can download or elements into the memory at once that it may be interesting I think it's - sorted you interesting I think it's - sorted you interesting I think it's - sorted you know I think they're probably the substandard ish albums for kind of funny things in the memory so maybe they said to write and conquer algorithm here it is that will help and it depends I have to really think about this in a bit more maybe uh but at worst case you could do a sort of merge sort which allows you to kind of it's more optimized for storing things in from distant memory and that allows you to use the two-finger allows you to use the two-finger allows you to use the two-finger algorithm a little better yeah okay yeah
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
111 |
hey guys likes to let's look at this 101 minimum depth of binary tree it's easy give it a binary tree find its minimum depth the minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node given a binary tree like this the returnees minimum depth is to number of nodes along the shortest path from the root node down to the nearest leaf node what does it mean so we have to value so this value is the shortest right so this is 2 hmm I think so let's do it this should be masking DFS depth-first this should be masking DFS depth-first this should be masking DFS depth-first search I think what we find one every time we've found a leaf node we calculate did the path it will shortest or not and they have the shortest we update the node okay let mean distance equals number infinite here is the infinite right in faith positive infinite okay positive infinity of the infinity ah God okay let taps ring depths that zero so we will sum up who will use DFS to sum up what sum up over sum up the distance and once we met - once we met the leaf and once we met - once we met the leaf and once we met - once we met the leaf we updated I wish you'd do the DFS will use recursion right if we use recursion you okay Chris create let's create a water walk yeah how can we update the main distance walk aha okay let's say we cost a walk no total distance cost this tense past distance gasps distance if note okay distance is personal cost plus node bow if note left if not left then where then we will work if now the left is new and right the school then we say we met leaf node and then we were just F distance is the distance is smaller than in distance mean taps past depth it was past EPS asked if note left walk note left past distance past the distance is a business as that's plus one if note right walk note right distance past that's plus 1 if we can walk so we'll all walk routes pass distance one I don't know it's a zero pass attempts this one and then we return mean distance monokote wrong I'll push 12 ah sorry oye it seems that you're getting right run time error cannot really probably involve more what is that input is empty so mm if root is smooth returning taps the edge cases Oh since I'm wrong about this one okay so nice a two-way usually Travis I'm not sure what does in Maine is shortest path so if the tree there is a number white what does it matter that you don't check the sound I don't check that what number what does the number mean that's the case we don't think a best case we don't check this one if path miss is X like this we don't pass in distance this past one ready yes three long title a success - why is you it's from zero Oh God here I mean this should be number positive infinity hmm then what's the meaning of this wait recursion yeah we crucial DFS strategy they have to do we turn to one main math name complexity will visit each node we revisit nothing here and then we walk so it's not exact once actually there will be no cost Act so we're creating a walker DFS iteration while we create a stack uh-huh yeah cool back to the ISA were uh-huh yeah cool back to the ISA were uh-huh yeah cool back to the ISA were using a walker actually yes yeah we ride just walk the curve into wood would be also recursion it's not very good because every time we yeah because we use recursion we will be a stack keeping the call stack we need to rewrite it to DFS situation so I try rewrite it into the DFS situation so different iteration is very DFS is uh yes it's reasonable I think the defense is just using a stack and for DFS of the FS we would just use Q yeah the solution says also if you use this one DFS yeah okay let's rewrite into DFS situation it's very important that I think they will be highly possible that is problems we are being asked in the interview so the Ning depths I think it could be keep kept the same this could be also kept the same so let's current stack which is a way to say it had to be as it's that the first thing is should be using root should be in it and then wow the current stack is not empty we popped first the course current stack so when we pop this I have to keep track of the depth that is a cool how can I track exactly for you if you eye DFS uh-huh we can use the dead stack no you uh-huh we can use the dead stack no you uh-huh we can use the dead stack no you can also use a DEP stack equals zero one so the pop cost depth equals Deb sack if note left and load right are both empty we say then this is a left this is a leaf then if depth is small damming depths mean depth equal steps if you'll note left really just we first push to wrap put push the right one and car and staff push note tap step push that plus 1 also we do the same to left not great no dot lat and finally we return mean depth and we should be solving the problem contacts not defined calling mr. curling cool let's submit hmm but actually it's not fast I don't know why we use two sacks so that is not optimal let's say this is here it is the link list Oh image we don't use to array or maybe just pop push into the number together which is a one so we can use that note and dead like this pop for once and the dead load yeah and then we just push note right and that plus one left right there's what's one or really faster hmm faster but not fast as fast enough anyway this is the practice of our transformation from recursion to operation the next one we just try to use BFS okay BFS will use a queue but we use a queue and when you use a queue it's also like this we just push the first in it one thing is that we don't pop at we don't see a stack cuz we use first in first out so that we can always Travis all the parent node in the same level so no step is this is not part but shift we get the first node and then check if we this right if this and we can break just return main depths return depth we don't need to keep track of the mean depth right yeah my friend if we can find the first one just return the depth okay so if the note left there is we push the node left and tap and right we push by tactic and then finally a we only there will always will be a return so we're gonna coat currents that are there's no current sky sorry it is cute EQ mmm still not that fast anyway let's take a look at all these and time and space complexity the first one is uh said it's with Christian the kirshen yeah recursion we actually did you use recursion as the first approach time complex they actually for it for case days out and notes the recursion first we just actually Travis on each node for only one time so it should be OH and space time is o n space we keep track of the call stack just a depth actually the average the I think it should be log n right worst case is I went here first is o DFS iteration time also its Oh n because for each node we only Traverse once a space we use a stack the Maxima stack will be Maximus stack will be also the same so actually the space will also be a little Aborigine stupid law and worst oh and pumpkin sinks the oil yeah worst case and yeah but for BFS iteration time times so these I don't know so these averagely I think if we think that it might be ended it's fast and in the well so you stink Oh log and now average I think we can and -2 divided by 2 half of them so the and -2 divided by 2 half of them so the and -2 divided by 2 half of them so the time completely is the same space we use it Q to track to keep track every level so averagely so worst case it won't keep Oh first it should be oh and space is also oh and actually I think the worst case we should be the longest one so the space will teach it to n averagely Aborigine I think if he's a complete tree but if out averagely and I don't know the worst case for balance tree we need to visit all notes level by level up to the tree height that includes the botton in the level only this way we visit yeah time complexity is o n space complexity it's the same I think it would be uh yeah okay so that's the end for these 101 thanks for listening - see you soon
|
Minimum Depth of Binary Tree
|
minimum-depth-of-binary-tree
|
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102,104
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.