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
130
hello and welcome to my channel so today let's look at the today's daily challenge question lead code 130 surrounding the regions given m times n matrix board containing x and all oh capture all regions that are four surrounded by x origin is captured by flipping all o's into x and in that surrounding the region so example is a first example uh this grader after the flip only the first the middle trick oh get uh converted to x so uh the old in the border will not be converted so um yeah it's also like a you uh it's decided by four connect four directions so this oh and this so you should uh if you count the diagonal is kinetic but they are not considered connected so for this example uh we can actually start the start from the border and find the find the o in the border um do bfs to find the order connected oh and fill and replace with a different value we replace those cells for example with the f the third step is uh to first bub is a for the rest of all you actually can replace those odds uh to x and the last step is uh then you can replace uh f cells with f to um to o again so let's finish the um the process so yeah let me give this example i can we can give given some example we can actually um show you how to do that so like for example there is o in the border and there is o here and also the o is connected to the but it's only connected to one this and then this one may be not connected so and maybe we can give another o and then and also there is o in the middle like uh this one so uh so we can firstly we find all the o's in the uh in the queue like in the border and now we put them in we put them into the queue and then we find that with that we started expanding so we uh we expanded to then we go to the four direction and they expanded to the oh inside the because these two is connected so during the process we just change it to like f and uh so this will be f and then we scan the border again then we change order o which would not have to x so the last step is we scan the border again and then we change those values back to all so after the this process it will be uh the board when we want okay so let's start the writing the code so uh we can actually have the uh we have the queue defined so we can actually add all the we can add all the coordinate of border roles to the queue also we want to define as usual for the grid we want to define a direction vector and also we want to get m and n as a global variable yeah and uh now we can go scan into the border so there are only four borders like we can firstly we scan the direction of other column so if board or border n minus one this is one first column and the last column is a is o uh now we need to add them to the actually we need to split this to two um yeah and also similarly we want to do the same for the row direction so we that is we can um actually we don't know how to do this i think we can do another is we can do the bfs we can create another function called bfs and because this there is a like a disadvantage of doing this way is uh maybe two cells are connected on the border so you actually add them both to the queue um so i think that yeah we can uh do the bfs so that uh it will we just do the bfs on invest in a separate function um yeah so here we just need to do bfs r0 like board but we don't add to the queue um yeah and uh um yes actually here it should be a man as well yeah and then in the board also we want to define another function called uh maybe in area this is checking if the coordinator is valid okay so let's add this uh on the c to the um and also we need to as i mentioned that we need to change it to f then we can do the bffs to expand using our loop so we do yeah and also we can now using the four direction uh the array we uh define the directory and then we get a the next node like the next cell coordinate for expansion so that here if this node is uh if it's not an area then it's uh another valid coordinate continue if it is in area then we can add it to the queue i think we also if it's not in if it's not uh if it's not at all we actually also continue so then it means it's ro and then we can ch also change it to f and then we added to the queue so until the this bfs is uh completed we added the connected cells to the and also we changed it to f so after this four so the border has been checked then we can do a loop and change all the o's to 2x yeah actually also we can do the same thing the same uh like the logic we mentioned that we want to change all the f to o yeah and then after this is done it should be oh it should be done so another the time complexity is a time is over and as the elements in the grid yeah that's actually the time of we generally get when doing the dfs also the space maybe uh the worst case is also old so um yeah so it's the first example correct the second example okay yeah so this concludes today's session uh so thank you for watching see you next time
Surrounded Regions
surrounded-regions
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. **Example 1:** **Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Explanation:** Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. **Example 2:** **Input:** board = \[\[ "X "\]\] **Output:** \[\[ "X "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is `'X'` or `'O'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,286
141
hello everyone this is leak code 141 link list cycle um given head which is the head of a link list determine if the link list has a cycle in it um there's a cycle in a link list if there's some node in the list that can be reached Again by continuously foll the next pointer so um yeah we follow the next pointer for a specific note and eventually if there is a cycle in the link list uh at one point one of the nodes uh next pointer will bring us back to a node we've already visited so in that case there is a cycle uh and basically to approach this problem we're going to use the tortois and hair algorithm which is a pointer algorithm on more rly it's just a cycle detection algorithm um which makes use of two pointer so uh basically we're going to have a pointer at the start well two pointers both they both point at the to the Head note at first and um one of them is going to be a slow pointer and one is a fast pointer the slow pointer is going to basically move um to the next node and then the fast pointer is going to move to the next node and then the next node right and so basically one pointer is going to be the slow pointer which just moves you know uh one node it traverses one node and then the pointer traverses two node um every you know uh quote unquote turn and So eventually if there is a link if there's a cycle in the link list these two pointers the slow pointer and the fast pointer they will meet at some point if there is a uh cycle now if there's not a cycle what's going to happen well if there's not a cycle then the fast pointer eventually is going to reach the end of the link list right so we're going to get we're going to reach a point eventually where um there's no nodes that we can uh Traverse any F we can't Traverse any further in the link list at some point uh if there is no cycle and that's how we can basically find if there's a cycle or not is either these two nodes are going to are these two pointers I should say are going to meet eventually or they are going to um or the fast pointer eventually is going to reach the end of the link list okay so we'll initialize our uh slow and fast point winner both to the Head node and then essentially what we're going to say is while there is a fast node while the fast node uh um exists or uh fast. next exists we are going to essentially first of all let's move the slow pointer um so slow pointer is going to go to the next pointer and again the fast pointer is going to Traverse down two nodes okay um and at some point if they are equal we have to check right if they're equal right if they meet then we return true cuz um there's a cycle in the list now if we exit this y Loop by the way sorry I have to move this here so we're still in the Y Loop um and if we exit the Y Loop that means we didn't return true so we that would be a case where we Traverse um through the link list and there's actually not a cycle in which case we just return false okay yeah uh pretty simple uh this like algorithm this toris and hair algorithm it shows up on a few problems um uh there's more problems that deal with cycles and linkless and or deals with just with link lless problems um and you're gonna have to use uh this algorithm so yeah I hope this helps um I don't think this problem's too bad it especially it's kind of hard to come up with uh I think intuitively if it's your first time you've come across this algorithm but um eventually you are going to run into problems where you have to use this again and um you know as long as you uh are aware of it now um shouldn't be uh shouldn't be too hard to come up with a solution next time you see a like a harder problem that has to use a cycle or where you have to find a cycle in a link list for whatever reason okay anyways that's it and uh I hope this helped
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
1,347
Hello everyone welcome to my channel code sir with mike so today we are going to do video number 32 of our strings playlist ok and link number 1 47 this is a question of medium easy range ok it is not very tough no g asked this question Now see what is the question, it says the name of the question is Minimum Number of Steps to Make Two Strings Anna Gram You are given two strings must be given, one S and one T, like look here, T is given, the length of both is the same, okay In one step you can choose any character of t and replace it with another character What it is saying is that in one step you can pick any character of t and replace it with another character Return the minimum number Of the steps to make an anagrammer, let me tell you what the meaning of an anagrammer is. An anagrammer contains the same characters with a different ordering. The count of characters will be exactly the same. Only the ordering is different. You have succeeded. It goes like look at B.A.B.A.B like look at B.A.B.A.B like look at B.A.B.A.B is the anagram of A.B.B. What else is the anagram of A.B.B. What else is the anagram of A.B.B. What else can it be? B.B.A is not A. It can be anything can it be? B.B.A is not A. It can be anything can it be? B.B.A is not A. It can be anything but the number of characters should be same and the same characters should be present in it. Right, it has just been shuffled, so look here at T which is there. Now look at the anagrammar. If you look at A, then B which is there has come twice and A which is there has come once but look here at T which is B. A has come only once and A has come twice so the agram is there now otherwise you Y is saying that in how many minimum steps can you make T an agram of A then why is the answer one because if you Pay attention, what can you do in one step? You can convert A into B. It takes one step, this is your answer. Look, if you convert A into B, what does it become? A B. Look, this is its agram, because Look in this, the B which is there has come twice, A has come once and B has come once, in this also now B has come twice and A has come once. Okay, so you have made t an agram of s and you have taken one step. Okay, like this. Here, to convert the lead code into practice, it will take us five steps to make the agram of S lead code from practice. Look here, like here this character of 'P' and 'A' is not there. Okay, so character of 'P' and 'A' is not there. Okay, so character of 'P' and 'A' is not there. Okay, so what should I convert to 'P'? Let me convert it into L what should I convert to 'P'? Let me convert it into L what should I convert to 'P'? Let me convert it into L because L is not even here, right, whatever r is not in s, so I convert r also. What should I convert r into? I convert it into d. Whatever is there is in s, no, okay, so let's convert a into something, let's do it in o, okay, c is here, okay, a t, whatever t is, aa is not above, right? If aa is converted into e then s is ready. If both of them match then there is one extra c here then convert it into e and if this e is ready then see a letters and write the rest as l double e. T C O D E is the lead code, so it takes a total of five steps to convert it into its agram, so the answer is five. Okay, so let's see what is Intu is quite simple, but before that, once I Let me clear again what agram means. Agram means that let's say there is an s1, okay let's assume s or t. This is my a first string s is the second string t as given here. Whatever characters are there in s and the number of times those characters appear should be same in t. Whatever characters are there in s should be in t and as many times as they are in s, they should also be in t. This is clear. Only he can be successful, he must have been successful only then he is clear even in anagrammar. Now coming to our entry part, look at this first small example and one or two more examples and we will see so that there is more clarity, then see what is the problem. The question is, what is the meaning of ' see what is the problem. The question is, what is the meaning of ' see what is the problem. The question is, what is the meaning of ' s' to the kitty? s' to the kitty? s' to the kitty? So for Anagu, I had said that the characters in both should be exactly the same. It is not a problem if there is a fruitful result, so first of all I find out how many characters are there in 's'. What is there in 's' is how many characters are there in 's'. What is there in 's' is how many characters are there in 's'. What is there in 's' is not 'B' which is 'A', first let's write ' not 'B' which is 'A', first let's write ' not 'B' which is 'A', first let's write ' A' which is there in 's' and has come once and 'B' which is there and which has A' which is there in 's' and has come once and 'B' which is there and which has A' which is there in 's' and has come once and 'B' which is there and which has come twice, both are fine and if I talk about 't' then look at 't' The one which is A has if I talk about 't' then look at 't' The one which is A has if I talk about 't' then look at 't' The one which is A has come twice, okay and the one who is B, has come once, okay, so we have stored which one has come how many times, okay, now look, pay attention, I come to T because look, T. I have to make the agram of A, so I came to T and asked T, which characters do you have? T said, I have A, but A has two, so I will see how much A should be there in AS. A is saying that I should have only one A will match this and what else and this one A will be converted into something else and what will be converted later Ok but right now T is not worried because he wanted an A, right, there is at least one A. So it's okay so there is no tension because at least one is there, what I am saying is that the frequency of A is more in N or it is either equal or the frequency of A is there in A No tension because the frequency required should be at least that much, if it is more then it is a good thing, but this means that if it is more then it is a good thing, it should not be less, if it is less then we will have problems, so here is the solution. Having two is a good thing, okay, so A is happy right now but B, but if I came, B said, brother, I have only one B, but A also needs two, okay, A also needs two. Meaning, how much operation will have to be flipped, now from where to get that flip done, look, here I write that it has two A's and it has one B, what is here, one A and two B's, so as soon as I came to B, I You see, okay B is one but I also want two, okay, that means how many flips will have to be done, two means, one flip will have to be done, I will have to hold one of the characters and convert it into B so that here also two can come, okay, but you have to. Meaning, your tension is with whom will you have to flip and how much will you have to flip? Forget about whom you will have to flip. He is not asking you a bit. You were just asked, brother, how much will you have to flip and how much will you have to replace the character? I know from here. Well, look, he had one B but we need two B, so one extra B would be needed, otherwise I have removed the same thing from here, what did I do, find out the difference between the two, how many B are there in s, two, he has only one. If there is one B and extra, that means one more flip is needed, that means we will have to do minimum one flip, we will have to do one flip, then who will you do one flip, that is not your tension in this t string, it will happen somewhere. No, if you look further, whom will you do this, he had two A's, so I converted this A into B, okay, there were two A's, one A was converted into B, that is your tension, no, you don't even have to see that. Okay, all you have to do is see how much B would need. There is only one B. But one more B would be needed. One more B would be needed. Okay, so we looked at both the characters and we found out that one extra flip would be needed. So the answer is that it was one, it is clear, this is my only tension, how many flips will t need, here there was only one b, one more is needed, because t also has two, so 2 - 1 a I will catch any one character has two, so 2 - 1 a I will catch any one character has two, so 2 - 1 a I will catch any one character and flip him. Who will I catch? That is not my tension. It is clear here but in this I am 100% sure that a in this I am 100% sure that a in this I am 100% sure that a counter question will definitely come in your mind. Do you know what I just said here? There was a and there was one more, this poor guy wanted one more, so I said, ok, I want one more, no, I just want one more, neither is that one, I will try to flip some other character and I will do it, then you will say that Well, here we have found a character which can be flipped. Let's assume that it is not there, so that means you are saying that here it is not one, that is, there is only one A. Well, if there is only one A, then brother, this is not an agram at all. How many characters does it have in total? Three, its total characters are two. It is not an agram, so don't worry about it. And this counter question is a good question. You can ask it in the interview. Okay, so what have I written here? How many A's does it have? There are two A's, right A and A. If one had to flip this one to make B, then he would make it. Someone here has got A, this would become B. Okay, so I have cleared that counter question for you here too, which is important. This point may come in the interview. Okay, so let's dry run one more example. Then the code is nothing, it is a simple code, so let's see this example. Now you have understood the main thing that any such character. Whose frequency is more in s and less in t, then it is messed up, that is why it is messed up because look, here there were two, here there was one, so 2 - one extra, this one needs one extra and that was one, so 2 - one extra, this one needs one extra and that was one, so 2 - one extra, this one needs one extra and that was my answer here only. The same thing has to be done like look here A which is L, isn't it? Do you see L here? Yes, it is true that I found a character in S whose frequency is more than T. Here the frequency of L is one and here But the frequency of L is zero, okay, that means I will have to flip one character, who has to do it in T, don't take tension, I already told you, okay, so I added one in the answer because of this L, because the frequency of l here. It is zero, okay, now look at e here, its frequency is three, here its frequency is only one, so this guy will need two more, right, e means 3 -1, that is two more, right, e means 3 -1, that is two more, right, e means 3 -1, that is two more, so one here, two will be added here. After that look at t, here t is 1, here also t is 1, nothing is needed, both are equal, what is fine, look at c, here is c1, here is c2, see, pay attention, here c is one and here c is two, you should not take tension because Here the frequency is more this time, is n't it? Here there are two frequencies, two C's and here there is only one C, so no problem, one and this one will match both and the remaining C of this one will convert into some other. Where we needed it is okay then CC is also fine isn't it because it is more in t, just less if the frequency of t is, then the frequency of the character in t will be less, only then we have to take tension like o here is one here. o It is not there, so 1 - 0 One more must be required not there, so 1 - 0 One more must be required not there, so 1 - 0 One more must be required D Here there is one D here There is no D Okay so here one more must be required D Okay so see how much is done Na Plustwo means th is done The answer is no, so ultimately what is the frequency of a character in s, which is if it is greater than the frequency of character in t, then the difference will be the amount we need in t, then the result is okay. What will we add in result plus e is equal to frequency of that character in a s p Whatever frequency is there we will subtract the frequency of that character in t Just keep adding in the result s Simple as that is quite simple and given in the question that It is lower case English letters only, so we can use map to count the frequency but I will simply use an array of integers. Rows of size 26 to 25. What was this zero for? A is for B. Remember, whatever character was there, if you minus it from A, its correct index would come out, like what would be the index of A, my A is zero, so this is the a of B. What will be the index b my a that is w so this is b and so on i have already told you so i will use 26 size hey i will not use map till now so story to code is very simple what did i say First of all we have to store the frequency, either first we will store the frequency of all the characters of A, we will take a map, or we will take a vector of A, what is its name of size 26, what should I give the count, I will give the count under A, meaning all the characters of A. The frequency of the characters is stored in it, then for T we will take another one of size 26 which will have the frequency of all the characters of T. Okay, nothing to do after that, we just have to see that if the frequency of any character in A If it is greater than height, here I told you here, then we just have to subtract and add to the result. Okay, so for both are of 26 size. Na frequency a is both of 26 size. Then aa = 0 aa len 26 aa plus. Ps size. Then aa = 0 aa len 26 aa plus. Ps size. Then aa = 0 aa len 26 aa plus. Ps Okay, just what we had to see is that if the count under score a of aa, whichever character is there, its frequency in this eye will be greater than the frequency of the count under scotty in jo i, okay, then how much extra will we need to t for both of them. Minus 2. Whatever value is there in count under s. Minus whatever value is in cow scotty. A simple at is exactly the same as told. Okay, that's the first way to code. Okay, now ultimately see what you had to do. Ultimately you have to The difference has to be found for a given character. What did you do? The frequency of that character in A is equal to the frequency of that character in T, so you are finding the difference of both, right. So what will I do? No, you do not need to make two different maps, just make one map, no, I am saying make only one map of size 26 and store the difference in it, okay and how will they do that? Now let me show you a dry run, so see what example I have taken here, like look in A, if there is two B, then there is B, then you can correspond to B. Simply, if there is B in A, then do plus and then there is B in A. If it comes then do one more float, then it is okay, then if there is an A in S, then do a plus and here, this is okay for A. After that, if A comes in t, then make it minus, the difference will keep coming out, and what else in t, there will be a B. If Y comes then make it ' else in t, there will be a B. If Y comes then make it ' M' then one more The M' then one more The M' then one more The rest are all zeros. Now look here, pay attention, what does -1 mean? It must have been what does -1 mean? It must have been what does -1 mean? It must have been less in S and more in T, so we did not have to consider that case. I told you that if the frequency in S is If it is more than T and less than T means the frequency from T to T, that is why we were adding it in the result. Here what negative means is that for sure its frequency in A must have been less, so we do not have to consider that case. So we will not consider the negative one whose difference is positive, nor will we consider only that one and why it came positive because the frequency of B must have been more in A and we would need extra B in t, how much would be needed, we would need one, this was the answer, our negative. We will not add the positive ones only, that is, we will add only the positive ones, if it is clear, then just try coding in both the ways in Cps and Java code, you will get exactly the exact similar code. My Git Hub link will go in the description. Okay, so let's code quickly, first of all, we will do it with our first approach in which we will have taken two maps. Okay, first of all, let's find the length, then let's take the first map. Map underscore is A26 size okay. What will happen in A? The frequency of the characters in A will be ap and t. What will happen in this? What will be the frequency of the characters in T? Okay, so let's fill the frequency of all i 0 Aa Le A Aa P Okay then M P Under We will put the frequency of the character of A in A. Plus plus done but to access the index we are doing minus A. Okay A atty t of Aa's plus done. To access the frequency index we did minus. You will know all this ready okay int Result E 0 Now look pay attention for int A E 0 A Lesson 206 A P Okay now see I told you that if character's if app under s is any character its frequency s is if greater than that comes out i app under t means whatever was its frequency at t, then what I did was result plus e is equal to two, I took out the difference of the frequencies of these two, minus t is clear till now, just what we have to do in the last is to return the result and let's see after running. We should be to close the cases, let's submit the IDs and see, after this we will try to solve it with a single map. Actually yes, we have solved it's okay. Now let's come to the one map approach, I mean what I said. That you have to extract only the difference, so take one map and store the difference in it, okay, that means remove this entire map, just take one map, int mp is of 26 size, put zero in it, ok and look in the app. What did off aa do in MP? Why is it doing minus so that the difference keeps coming out simultaneously? Is n't it the difference that keeps coming out simultaneously? Okay, now see, now you don't need to check now. All you have to do is add if m p of a if greater than zero then add the result plus e m of a that is datchi and what is the time complex t. What is the time complex t of n because we visit all the characters only once. Are doing and space is complicated it would be rage in the comment section try to help out see you go in next video thank you
Minimum Number of Steps to Make Two Strings Anagram
distance-to-a-cycle-in-undirected-graph
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Example 1:** **Input:** s = "bab ", t = "aba " **Output:** 1 **Explanation:** Replace the first 'a' in t with b, t = "bba " which is anagram of s. **Example 2:** **Input:** s = "leetcode ", t = "practice " **Output:** 5 **Explanation:** Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. **Example 3:** **Input:** s = "anagram ", t = "mangaar " **Output:** 0 **Explanation:** "anagram " and "mangaar " are anagrams. **Constraints:** * `1 <= s.length <= 5 * 104` * `s.length == t.length` * `s` and `t` consist of lowercase English letters only.
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the node that was seen twice and all the nodes that we visited in between. Now that we know which nodes are part of the cycle, how can we find the distances? We can run a multi-source BFS starting from the nodes in the cycle and expanding outward.
Depth-First Search,Breadth-First Search,Union Find,Graph
Hard
2218
290
Hello Jai Hind today we will do a question the number of lit code is 290 the name is bud pattern ok so in this question we have been given a pattern the pattern is a b a after that a string has been given me ok the string contains dog cat Cat is Dog. Okay, so we have to find out whether this string Dog Cat Dog is following this pattern or not. If it is following this pattern then we have to return true. If it is not following then we have to return true. We will return false, okay, so now how do we know whether it is following the pattern or not, so look at whatever value is at the first position, here is A or if whatever means whatever value is at the first position of the pattern. If so, look carefully to see that there is the same value at the fourth position. Okay, so whatever value is there at the first position in the string should be the same at the fourth position. Okay, only then the pattern is matching. What we are doing is that we need the pattern. A B A pattern is required, it means whatever is on the first position should be on the fourth position because there is A on the fourth position and A on the first position. Okay, so now let's look at the second example, it has B A but look here at the first position. There is a dog but there is no dog on the fourth position, then it is not matching, it will return false. Okay, so now let's see its time complexity. Before doing any question, what is the time complexity? So the time given by it is 300, that is, our The length of the pattern is only 300, i.e. 300, so now we can is only 300, i.e. 300, so now we can is only 300, i.e. 300, so now we can apply any formula, that is, write any code, n square n, n4 n5, everything will work fine, but now we are explaining this question for interview purpose, if we assume If it is not 300 but less than equal to two, then how do we make it 6 to the power of 10, because if this lane of the pattern gives 6 to the power of 10, then we have to make it only in the big of n. Okay, we only have to make it in the big of a. It will take 10 to the power of 6. The lesson is equal to 10 to the power of 6. So we need the solution of Big of A. We need the approach of Big of A. So now first of all let us tell you how we will make it normal. What will be our approach? What will be the normal of this question? According to this, if a question is asked in an interview, if it is asked in an interview, it will not be easy, but it is easy, but it will not be easy, it will be of medium level, make sense of saying it is of medium level, pattern it and put it to the power of 10. If F is added then A SQUA will not work. If F is to the power of 10 then A SQUA will work. If F is to the power of 10 then F is greater than F then only Big of A solution will work, not A SQUA. It will work okay, so first of all we are applying the approach, normal approach, brute force approach, so what we will do in the brute force approach is that this is a, we will map it to dog, a is equal to two, we do not write it here, okay, we write it here. No problem, we will map A to dog, okay, and B will be mapped to cat, we will run a loop, and while running the loop, what we will do is to match all the values, all the patterns, with this value, with the value of the string. We will enter the key values ​​in pairs. enter the key values ​​in pairs. enter the key values ​​in pairs. Here is our key and here is our value. Okay, then we will run another form, after that we will check what values ​​we have given for each key in the map. check what values ​​we have given for each key in the map. Were given two, so is there a dog here in our string or not? Assume that right now we have the position of our aa is ro, so when ro comes, then ro pe, we will first check what is ro pe a, then we In the map, we will check whether we have assigned a to our a, then we checked, we found out that for a, we have assigned a dog. When a is assigned to dog, then now we will match in the string. Whether there is a dog in our string or not, we can create it in this way at the first position, so we are creating it by brute force approach, so first of all I need a map, so first let's create a map for the character and string, we need Okay, new is map, okay and what will we do with this string, we will convert this string into So the array of strings I need is string id trm dot split space on y We need Okay our array is done now what we will do is we will run a for loop why will we run a for loop we will run because we will run which is the value of a For that, we can assign Dog for A, we can assign Cat for B. Okay, so we have to map, a equals dog, b equals cat, so now what do we do here to map it? We will run the loop f int aa e 0 aa lesson pattern dot length ok a aa plus ps we will check then we will check first what we do is we take out the character so that we do not have any issue so that we do not have to write again and again pattern dot this t so we Directly first let's find out the pattern daughter at aa meaning which character at aa position now aa e g aa position what is which character so i position p aa is character then what will be the value of character c equal to c ea will be Okay, after that what we will do is we will also take out the string, let's take the string 1 equal to a aa whatever is the value now we will check if map dot contains content key what key of content do I want character key Hey character Why do we need the key Y? We need the character A in the map. We are giving A as the key. Neither is C equal to two. Now what is A? So whether we have A in the map or not, they will check the content of E. If it is there then do nothing. If it is there then do n't do anything. If it is not there then we will have to give a note. If it is not there then what do we have to do? Map Dot Put will the conductor go? Okay, this is our mapping done. If I print it and show it then the system will do it. And let's write something so that we can know our map. Now our map is ready. Look, we have given dog for A and cat for B. Okay, it is done. Now we will run a loop. Will there be any problem in this? Don't do it, what we have simply done is that we have run four loops from zero to zero, which means left to right, I have run OK and have made the zero position match with this, A is equal to B, A is equal to dog, we have mapped I had previously checked if map data content is there in the map, if we have a key named vector, see, let's get it drained once, first there is our map, which is nothing right now, it is empty, okay, here our key will be here our value will be. So we will say that when A was equal to 0, it is now zero, I have zero, then it was zero, even then we were checking that the character is equal to C, we have put it in C, what have we put in C, we have put A in C, now we have put A in C. Given because what are you writing pattern Dt K aa whatever character is there on our zero, put it in C, then put A in C. Okay, if we have put A in C, then in the string, we take a string and in which we put this value. Removing the dog this dog so I'm keeping the dog here okay so right now we have nothing in the map when a e was 0 so we check if map d content key c now what is character c Is equal to two, so should we check here whether we have a character in the map or not? Our map is not empty now, then a false will come here. If a false comes, then we should reverse the false because we are using the ternary operator of A note. Okay. If the false co will become true i.e. when the if false co will become true i.e. when the if false co will become true i.e. when the if condition is true then the entry will be done under and what will it do in the map. What will put do to c and s1? What is our c and what is ave? Dog is equal to map to dog. Will do the same thing on Y. A E dog is doing Y. Then A will be equal. Now our A E dog has started. Now A will be one. If I will be one then pattern dot caret I will work. So what is the character at the first position. A now One has happened, now after that pattern D aa is at the first position, what is B, then instead of A, C will become B. C is equal to B character, C is equal to B and what will we do on aa, what is array at aa array, what is cat at first position p? We are seeing that the first position is P CAT so we will write Y P CAT so we need P CAT here. Okay, now we have checked, now we have to loop check whether the map contains the content or not, if the character B is in the map, then the map. I have only A character, B character is not there, it is not there, so put this and make it MAC in the key value pair, okay, this is our brute force, okay, now we have mapped it, now what to do after this. What we have to do is matching means we have to check whether our pattern and string are matching otherwise we have to run the loop again so to run the loop again we have to write Y again pattern dat length end i plus now we again We are bringing this thing from Control C Control and Okay, now we will check that if the array at i is our i position at our array's i position p then let me write dot equal and y then the pattern will not work here, there is no i either. It will run on Y, it will run on map data gate character and we need ternary operator, we will tell that we are using ternary operator and here we will make false, okay, we will return tr on Y. Now look, first of all, we have understood what the first foreloop is doing. It is simply mapping, okay, now the second fural, what are we doing, we are going from zero to four, okay, so from zero, what is A, what is B is A and what's in sting is dog is cat is dog okay so now we are checking first I took out the character here what is the character is A so I put A in C Okay now what I'm doing is that in the string we mapped the value which value went to A Which value went to A I'm extracting the value So when we mapped A For B, we have kept dog and for B, we have kept cat. Okay, keep cat for B, so now what are we doing from here. Map D, get C, what is the value of C. If it is A, then get the value of character A from the map, then it will come here. But two will come, okay, I understand that first of all we have to take the character from here, which character is it, then we have to extract the value of that character from the map, what value do we have for that character? Now we will check that our array. In this array, the string of the array which we had converted into an array, then the dog at the ith position of this array, whatever value we extracted is matching with the map or not, where is s1, where is the map extracted from? If you had extracted the value from then whatever the value of the map is that value matching or not? If it is matching then do nothing. If it is not matching then return false. Okay, that's why we have used this pattern operator to see that if we do dot equals true then it will give true then we don't have to do anything. Return Falls are done in Return Falls or Else, but we need the work of only one, right, I don't think we can do the work of only one with Ton Rater, so we have put a note that when this fall comes, please give us True when True. r then make it false if it is matching if it is coming true then make it false so that it does not enter in f again f if we talk about done then like let us assume that right now the value of i is zero aa ect is zero and character is equal to a and string aa is equal to dog okay now let us check what is the array i array at aa array at zero position what is the value of i what is the value of zero aa what is zero aa zero position What is dog rate zero? What is dog at zero position? Which dot is equal and what is the value of this also? Both dogs are equal. Yes true. When this is true then convert it to false. Operator this is true. Just came here dog and dog got from here. Map Dot Get Character If one or both dog matches then it will be true. When the value will be true, what will this ternary operator do? What will this ternary operator do? It will convert true to false. Simple thing, understand that true is false. This loop will not run if this loop will not run or if condition will not run again it has come back up again it has come up then what will happen aa plus then aa Now the value of Aa will become one. Now for Aa we will define the character. First what is the pattern dictor Aa Aaav position. By removing the A we will make B and by removing the dog. We will do CAT because if you do map dot get c then CAT will come then we will check whether the ID S1 is matching with our name or not. If it is matching then nothing, go ahead, not matching, do it first and last. Suppose at any time all matches are made, that is, from left to right from zero index to fourth index, if all is matched, it will be true every time, this is just an operation. If it is converted to false, then if the condition is not executed even once, then return will not do anything. Return will not do anything, that is, it is matching all of us. When it is matching all of us, then what did we do in the end, we made it return true. Because he is matching us all the time, if you don't match us then he will immediately return false saying that he is not matching us, so now we will run it and see. Okay, let us run it and see, so our three tests have been successful, but now. When we submit, look at this, an issue will come. Now tell me what issue has come. Look, tell me the issue that has come is that when we had assigned A to Dog, when we had assigned A to D, then why for B? Assigning back to two, what we are just doing is checking whether B is in the map of map dot content, if B is not in the map, then what to put in the map, put C, put character B, and Dr. I put B and DR. Hey, look at both the second positions. Just look at B and Dog. We are matching only one condition here, not if map contains C. If map contains B. Is it true or not, if there is no B in the map, then put Dg in the map and put B, but this is not possible, according to our question, a key can have only one value, a value can have only one key, a key can have only one key. One value and one key, so A for dog and B for dog, both are not possible, so we have to write a condition here. We have to write a condition that end map dot contains value C and Y. Now we will Submitting it, let's try it and see if it is working or not. Do all the three things. Now look, there will be another issue here, there is still one issue, you guys quickly guess what could be the issue. Okay, now check your back. What is the issue? Now I am telling you the issue is that look at this, it is stuck in this, end and not of mapped content value is fine, it is good, why will we take character in value, we will not take character in value. We will take the string, we are still stuck in this, so now see what new problem will come, it will be successful, it has been successful, now we have another issue that the length of the pattern is only three and the length of the string is four, said four. So one, two, three, four, this also has to be written for the edge case. If pattern dot length is not equal to array dot length, we will have to simply return false when it is not there, otherwise we will return it, then this is our brute force, okay. It is accepted, our brute force is done, our brute force approach is done, this is what you are showing us, so we made this with brute force approach, okay, we made this with brute force approach, now we want, we are wondering where our If our number is 300 less than equating 10 to the power of 6 then this brute force is not going to work because 2n loops will run and will give a time limit in some cases. It is confirmed that the time limit is Given to the power of 10, given to the power of 10, 8, then will the time limit So why don't we check it right now, we will check what we will do, we will update it, we will remove it from map dot get character, we are doing this thing, we are doing the same thing, exactly the same thing, don't do anything different. Right here, we are going to put this in Else. Okay, nothing is wrong, in this we will put Else part of Else in this. What, what is going on, it is of no use to us, we are working in the same loop, first I will run it once and see if it is correct or not, so there should be no problem here, it is fine. going on accepted okay what's the evidence where's the question where's the quen look here what we're doing is when A is B is A is dog for Dog Cat Cut Dog Okay, so when we are going left to right while running four loops, we did not have A in the map, if A was not there, then put A, give a value to A, dog, then the value of A is one. See, B is not there in our map. If B is not there, then enter B, put the value for it. Now we move ahead, when it happens, we check whether it is there in the map or not and see if it is correct. If it is, then it will come directly in the form of ELSE. What we will do by coming in the form of S is that we will directly extract from the map which character for B we have given earlier, we will first see that earlier we have given C, we will see earlier we have given cat for B and we are matching right now. Everything is matching for Aa E3. What did we do till Aa Ictu? Till Aa E2 we inserted B E V C to B E V Cat. When A E 3 came then we checked whether the map dot content is B or not. The map already has For B, we are checking here that our new string is coming here. For E3, whether it is the same value or not, we are checking here whether it is the same value. Or not, what we have entered, let's check here whether it is the same value or not, if we check from the map, then we have done all the work here, so our work is going on in the same loop, that's it, thank you code. If you want to copy then see yours but do the dragon once yourself, this type of question can come in the interview, ok then thank you so much, ok bye Tata.
Word Pattern
word-pattern
Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pattern = "abba ", s = "dog cat cat dog " **Output:** true **Example 2:** **Input:** pattern = "abba ", s = "dog cat cat fish " **Output:** false **Example 3:** **Input:** pattern = "aaaa ", s = "dog cat cat dog " **Output:** false **Constraints:** * `1 <= pattern.length <= 300` * `pattern` contains only lower-case English letters. * `1 <= s.length <= 3000` * `s` contains only lowercase English letters and spaces `' '`. * `s` **does not contain** any leading or trailing spaces. * All the words in `s` are separated by a **single space**.
null
Hash Table,String
Easy
205,291
211
hey guys welcome back to another video and today we're going to be solving the lead code question add and search word data structure design okay so we need to design a data structure which supports the following operations we need to be able to add a word and we need to be able to search for a word and return a boolean value of whether the word exists or not so search word can search a literal word or a regular expression so let's say we have a dot right so what that means is that it can represent any letter so if you have a dot we first need to have a and then any other letter so let's look at this example real quick so we added the word bad then we added dad and then we have mad whatever data structure we have contains these three words and now we're gonna search whether these words exist or not so pad does not exist bad does exist and dot a d also exists and what that means is some letter followed by a d in this case we have dad we have bad and matt they all follow that and same for b dot we have b and then two other letters we don't care what those other letters are okay and you may assume that all words are consists of lowercase letters a through c okay so in order to solve this question we're going to be using a data structure called a try so before we go ahead uh let's try to explain what a try is and how we can use this in this situation all right so we have a try which is t-r-i-e not so we have a try which is t-r-i-e not so we have a try which is t-r-i-e not t-r-y t-r-y t-r-y so it's a tree-based data structure so it's a tree-based data structure so it's a tree-based data structure which is the most efficient way in order to store strings and it has a lookup time so if you want to look for a word it's going to be big o of l where l stands for the maximum length of the string right so it's the most efficient structure we can use to solve this question so in order to understand how this works let's look at a quick example by adding a few words so i'm just going to write a few words and we're going to add that to our try okay so over here i have five words one two three four yeah so i have them the boy back and stop okay so let's see how we can add this in a data structure so for every try we're going to have something which kind of represents a master root so this root is not going to hold any value but it's just kind of there as a place we're going to think of it as a master root which holds everything so now what we're going to do is let's say we want to add the first word which is them we're going to break it up into its letters so first we're going to add t then we're going to add h and we're going to add e and we're going to add m and each node in a try it's going to have a boolean value attached to it and this boolean value is going to say whether it's an end of the word or not so what i mean by that is so we have t over here it's going to have a boolean value of false because it's not the end of the word yet h is going to be false e is going to be false but once we reach to m we're going to have a value of true what that means is the word is just what that signifies is that the word ends at the letter m so now we have the letter so we have the word them in our try so now let's try to add the word the so in order to do that the first step is we're going to go to our master root and see if any of its children have t and t already exists then we want to see if it has an h also exists and it also has e so we already have the over here so in order to so we could do one of two things we could make another tree all together but that's just going to take up extra unnecessary space so all we're going to do is this over here has a boolean value of false instead now we're going to change that to true and what that means is we have a word which is t h e the and we also have a word t h e m them so we considered both the words in this case so now let's do the word boy so we're gonna make a new uh branch so it's gonna have the child b and we're gonna have o and then we're gonna have y so we have boy and now we want to add the word back so we're going to go to a master root we already have b but b does not have a child node of a so we're going to add that node so we're going to add a over here then we're going to add a c then we're going to add a k and again i forgot to write it but at the ending so these two are going to have the boolean value of true to signify that's the end of the word and finally we want to add the word stop so we're going to add a child node over here and then you get the point s-t-o-n-p the point s-t-o-n-p the point s-t-o-n-p so pretty simple and this is going to be the data structure that we want to implement and we're going to do so by using the python dictionary and now let's just quickly go over how will we search for an element and it's pretty simple let's say we want to look for the element stop we're going to go to a master root we're going to check if any of his children have the first letter of the word so if there's the s we're gonna go so then we're gonna change our root note to s so now our root note is s now we're gonna look for the next letter we're gonna look for t and then we're gonna go to t but so now let's just take an example let's say we're looking for the word back right we already have it so we're going to go to the b becomes our root note but like we saw in our example there can be regular expressions used so let's say we have b dot c k so that means we can have b anything and then c k so what we're going to do is we're going to go to b and since there's a dot it can represent any letter so we're going to add a and o as our parent nodes so first let's say we go to o then we're going to check for a c which does not exist so we're going to cross this out and then we're going to go back to our a and a c exists and so does a k so when we have a dot we're going to include all of its children nodes and we're going to use a stack in order to do that all right so let's take a look at the code and see how that looks like so i'm just going to go over and explain the code instead of writing it line by line since it's a little long okay so first what i did is i created a class called the trinode and this is going to be used to represent our try node and we're going to initialize it with self.children self.children self.children and this is going to be an empty dictionary which is going to hold its children notes then we're going to have a boolean value for is end and it's going to be set to false but if the it is the ending of a word we're going to change this value to true so now let's go into our word dictionary class and we're going to initialize it by calling our root so self.root and by calling our root so self.root and by calling our root so self.root and it's going to be a trinode object okay and now let's go to our add root method so over here we're going to have a node and think of this as our current node so we're going to start off at the root at our master root that's going to be our current starting point so that's going to be the node and now we're going to iterate through each of the letters or characters inside of our word so we're going to do that with the for loop and now we're going to check if that character already exists as a children node as a child node inside of whatever our root node is so if it does exist so in this case it does exist we're going to make that node as our current node but if it does not exist what we're going to do is we're first going to add that character as one of the children and then we're going to make it our current node okay and then this is going to keep going into our for loop and once we reach the last character and we're done with our for loop we're going to make whatever that last node is we're going to make its is end value to be true because that the last letter is the ending of the word okay so now let's go into our search method so over here we need to remember that return of the word is in a data structure a word could so we could have a dot character which represents any letter so in order to do this we're going to have a stack and in our stack we're going to initialize it with the tuple value and which is going to first hold the node so in this case we're going to start off with our root node as usual we're starting off with our root node and then we're going to give it the word and we get the word from the function over here okay and now we're going to go inside of a while loop and we're going gonna stay inside of this while loop until our we have something in our stack until our stack is not empty and each time we iterate through this loop we're gonna pop out whatever we have inside there so we're gonna do stack dot pop and over here we're gonna get the node so the first thing is the node over here and then we're gonna get the word that we're looking for so i'll just skip this part over here and we'll come back to it so now let's go to this statement here over here we're looking at the first letter of our note and we're checking if that exists in as one of our children notes so if word at whatever is at the zeroth element the first letter is in node.children then in that case is in node.children then in that case is in node.children then in that case we're going to take a temporary variable and we're going to set it equal to that node right and we're going to then add that to our stack so we're going to be adding a tuple value we're going to be adding the temporary variable and we're going to add the word now we've already found the first letter so we're going to add everything from the first index to the ending so to be more clear we found the zeroth index and now we're going to take everything from the first index and all the way to the ending okay and now we have one more statement which checks if we have a dot and in the case that we have a dot we're going to add all of the children notes and this is what the for loop does it iterates through all of its children notes and it keeps adding them to the stack so we're going to add all of the children notes to the stack and we're going to keep popping them out and keep checking for them now let's go back to this if statement that we had in the beginning so over here we're checking if the word even exists and the reason for that is each time we go into either of these loops we're going to come to a point where we're going to have less and less letters and at a point we're going to only return the last letter or we're going to come to a point where we do not return anything because each time we're looking at the zeroth index and once we reach the ending we're not going to return anything and in that case that means that we've reached the ending of our word and that could and now we need to check if that is actually the ending of the word that we're looking for and the way we can check that is we can look for its is and boolean value and if that value is true we know that it's the ending of the word so if no dot is n and in that case we're going to return true and if none of these case so if we do not end up going inside of this if statement or even if we do and it is not node.send not node.send not node.send then in that case that means that we did not find the word and then we're going to return false outside of our while loop so let's submit this real quick and as you can see our code did get accepted and finally do let me know if you have any questions or if you have any better solution to solve this and thanks a lot for watching guys and do let me know what you thought about the video thank you bye
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
174
The festival, today we will solve the question, the name of that question is Indian game, chicken animals, it is a very interesting question and very meaningful question, it is captured and imprisoned in the photo of the subscribe, so here we put it in the form of one and this position is last. Wally here the princess is cut and placed here and Williams Knight was initially in position in the top left room and must fight this book through turns into rescuers princess and which is our new take which is our new taste pie is standing here and He wants to save this princess, it is okay that such a team has played a lot of night shelter in this edition, this point is represented by positive and when you see now in any game, we go, we get nice lines, first of all, your husband is in life and you are in the game. We may get power off in between also or our fiber may be less and you should have at least one match with us so that you can save whoever you want to save, so the same is given here also. This soldier who is standing here, always keep some initial life in mind and you have to save the princess located on it, I have one at any point, health points 220 and absolutely digest instantly. Now look at any point at any digest instantly. Now look at any point. People playing games, you are gone, if you die, then Ajay has the sea. Room Guide Pediment Represented by Negative Anti. Surely, some people look at you like this. These negative numbers were telling that the demon here is fine even now. If he wants to then he will have to fight with Hindi MNS and then move ahead, so it is quite interesting, no question exam, as yes means we have to start from here, then save the prince and interesting tears, Nike shoes health upon entering, should I enter another room? Here MP and contain magic off but increase the white health and going to the room of tongue will either be empty or there will be some power off in them which will either increase our health and then you will get power. Chunri Spring Sad is the previous one. Possible, now what you have to do is to reach the princess as quickly as possible. The chicken may decide to move only the light board and download these inches of tape because the prince has one side so small, okay, only to the right and will only go downwards and I will not stay anywhere minimum means there is a need to start from here so that here 250 hours and room temperature means if you can get it in some form then I can be a little or can you get anyone that means subscribe then it will be a question statement piece jewellery. If the example explains, then we are the givers here. Okay, this is the exam on pimples which was given to us on the lift, here is the smooth one and the answer to it is our seventh. Now how can you see, I am here, my soldier, who has to be saved, we are standing here. Our princess captured here in this channel is fine, now save some minimum health extension health of this soldier, meaning he should be here. Hey Jab, I gave you a game, right, meaning you have this school, 9 inches and one Here this is a princess and you have to save the prince, so at least how many can you save in this, there is one in this, you can save, so I accepted that by the time we come here, Chunat's life is like a bird, so now we can at least Value, as it grows, it got it first in power, got it, so it had power in it, out of that - 1, so now it can be said from here, look, if he decided, then he can do it in height, so he can do it down. If I can get up, then I got him more rights, then he got more kudis, here his power has reduced by another - 3, here his power has reduced by another - 3, here his power has reduced by another - 3, of course, then I moved him further right, so see, now his power has increased and here he But there must have been some music which increased its power. Okay, now I took it further down and its power increased further. Okay, now finally I reached the place where the princess is imprisoned, it is called our princess and here. So if he is slow then he will have to fight, if he has to fight, then his power will be many - he fight, then his power will be many - he fight, then his power will be many - he has become white and if I total all these then Yoga - Pick. Okay, now what will happen now, Yoga - Pick. Okay, now what will happen now, Yoga - Pick. Okay, now what will happen now, wherever the soldier has reached here, he will have to give this princess. If you want to save the Prince, then at least he should have an oven, if not an oven, there should be work in Indian Health. So let's say that the knight had gone out with some extension health. Okay, on the way he also got power off. I found something in my mind due to which. Whatever power she had, it has been bought to some extent, that means look here, whatever by-power she has, she means look here, whatever by-power she has, she means look here, whatever by-power she has, she can also get it and from the power she has left, it can be long and how much should be left in the end, at least the power of Cheetah or that princess. It should be safe and sound, okay, so this mark here is laxative a six - what is six here - a six - what is six here - a six - what is six here - this is the power that has been spent because it has been spent in reaching from this year to this year, chicken and Rather, we have at least some health here, which is that at the end of this night, how much will this one chicken be consumed, it is absolutely true that it is 9:00 in the morning, right, we have at it is 9:00 in the morning, right, we have at it is 9:00 in the morning, right, we have at least a second to it. He needs at least seven initial health so that he can save this princess and secondly he can also have infinity. If he goes with these final powers then he will save her. Okay, so I thought that the question statement is a layer here, I am trying to explain it once more. I would like to say that Monsoon, we have only one salary and there is some tan stop in it. Okay, so here this is our soldier and here is our princess pier. Okay, so you here is the mark of leg set and save this prince. For this, at least how much health does she need? Now as if there is an entry in her room, what can happen to her, either she can have a power game or she can go crazy, so see here her power has been launched, there is tension and this. What happened and here we made it equal to one because at least whatever power is required, whatever power should be left, how many policies should be made to save the princess, then what is the minimum initial requirement, what is the level, it is definitely there, so this is ours. This was our problem statement. Okay, now we will see how to do it and I will share one more thing before explaining the problem. Suppose here it is called princess and here we have power stop we have Munchkin Knight okay so now you You will say that I said that Because here what will happen is that its bake power will increase. Okay, so in this case you will mix one ray, why at least how much of it is needed so that you can save. Okay, so these were our new ones and they have some ex. He has minimum health, okay, so he started walking, so now he will start from this year, okay, he will be here, so he started walking, now give him a pass from here, either he is walking here or he should walk below. Okay, so we are going towards the right first. Okay, now we have reached here, so from here, he should either go this way or where is he going to go down, so we just went to the night, okay now here. If we go outside this prison, we have reached here, we have reached outside the prison, here we have moved ahead, then we will do something very big from here, now you will say that this above means that we have accepted that Some at least if he has one at this point then he should have a lot of help only then he will be able to save the princess oh when he is so you are okay and you had sons okay and you have anything that you have money How much money will you need, you will need more money than Dada, so why is it that whenever it is night, he came out of our tandem and he does not even know his destination, then how much minimum energy will he need, maximum energy? There will be a need, so we have made the maximum return here, it is okay, it has happened, now look at the chickpeas from here to there, if you put it from here, now it is his, what option does he have, now he only has the option of going down, so down. Okay, now where will he go from here, he would go to the right, but what is our turn here, life is not the only thing, Warden will go outside since birth, so here he will need maximum initial help. Okay, now where should we go from here? He can go further down and what has he got, he has got a princess here, he has a princess here, okay, I am a princess here and if we accept that your problems are only this much, okay here we have a princess. And you have to save this prince, okay, at least how high is your health, your minimum health should be one, okay, so I have accepted here, on this channel, I have seen that whichever knight has at least this or that health. Torch should be switched off and should be avoided absolutely and that we had accepted the uniform policy of our night's nation help, so one by one Aplus that by equal to one will be I 1 teaspoon note granite's initial help denotes Roy's deleting this Hey bye this is 24 oil from this Luck only note side and see previous answer Here friend you can be power or what can happen can be oppression Okay so now here I have given us what I have given 1 given Scorpio And at least below how much health should his bandh be saved, only then he can save the principal or it is activated or fixed with us, okay, so here, how many units should be there for his pension help? Hey, when we have so much This is the problem, there is so much problem and if the knight has to save the springs sitting here then at least he will have six health but he will go so that he can save this prince properly, so what is our education knowledge required here that Abu from here So I had vitamin Ajay and how much health did he return with, 6 health but it was okay that he returned, now look at us at least the value of our thinking means when we are on this channel, when we reached on this channel, then of our thinking. Value is education and bike, from here we mean skin problem, if this problem has happened then tell Ajay that this problem has become only this much, it is okay and this will take some health of our night, so at least how much help will he get from here. Since Yogi is in this world, he would need at least five health so that he can save the one who is a princess here. Okay, so see, if we take him from there to here, he got the power of power, then five plus one for him here. But how much did it become, she became alert and when she freed herself from it, she got life, then she used only this pipe in her power, ten-five, ten-five, ten-five, what did she do with the power she had, from her health, she took this initiative. Used it to take away life and in the end, how much help does it have, child mind, child, why did I arrest the princess? Okay, so our initial help here is how many wars are there now, what will we do for amazing positive, let's see now see. Now what do we go back from here we got five and from here we have increased the maximum volume, so this message has been minimized, out of this, we have hit the minimum file, that is, where whatever help he has given to many celebs of the child, how much will be the smoothness of the files. So now we are one Nepal so Will give, absolutely good, okay, now he can't go down from here, so who will go down even once, okay, so he went down from here, now from here it can be said, from here, he can go right, of course, but look, this is two in a year. We have already gone and we know that to go to this cell, if we go to this oil, then we will need at least five initial helps, then we will simply return the face here. Absolutely, see the world. All these problems also came in the map and then now we went below, if from here we can go here, we can go right, but we know about this, here the prince should go and how many initials do we have to go here to save the princess. We need help, we need six, so what did we take from here to tell the answer, here we need city for six, we went below A and checked because there was a call left below it, so it was on the floor. The outer came out and what happens when it comes out we need maximum hills okay so now look you need at least initial help so on one side is coming here maximum and on one side chittiyan now you are here You will need at least this much help. Let's say if your problem was not only that here is sour food and power and here is the princess and you are miles tow and you are taking something obscene then what is the value of your Essex? It should be stopped, it should be made, because look here, what is the condition of our power of military and whatever help we have, how much is it, you are a doctor of one night, how much is it? Ours will be - 54, we should have at how much is it? Ours will be - 54, we should have at how much is it? Ours will be - 54, we should have at least minimum initial health to save the knight's prince - save the knight's prince - 1304, then my note will die, so I - 1304, then my note will die, so I - 1304, then my note will die, so I - can you take it, can't you at all, so why am I here? I will say, Om Shaam, when my problem is only this much, then what should be my one, take at least one question about the health of the state, that means it should be okay, then I will do it from here, okay, now see. On one side we need white heads, ok, and on one side we have one and here is our dimple, so out of these two, we will fry. Now you will say why are we taking minimum here, then see the problem like this. This is our bread, it's okay, now we are leaving from here and like this, go here to the prince, promote it, something of yours and a sensor update is being detected in it is okay and you are leaving from here, go here and save the princess. Yes, there seems to be some help here, okay, now I am saying that you need at least minimum health one to save this princess, okay, and whatever action of ours is smaller than a mobile, you and I are one. The advice is small, now you will say that why are we taking the minimum here? When we have reached here in about one and we have reached here in one too, then what is the meaning of taking the minimum here? If you see, if we cow Even in India, we are not able to access these air services and if I start my point here then see if despite this virus, we are able to reach there at least in health and in this too, at least X-ray is also available. in this too, at least X-ray is also available. in this too, at least X-ray is also available. Where are we able to reach with less health then X is equal by but here it is not so and we need at least one health to save this princess so what will we take, we will take this very path here. From where we need minimum hairs, from where we need minimum initial health milk, so we have taken one, it is making here, so we have taken one, so Express 8 - Tass is equal to one neck oil introduction, neither 8 - Tass is equal to one neck oil introduction, neither 8 - Tass is equal to one neck oil introduction, neither all the p Energy is one of his salary messages, whatever amount of energy he can take from power off or whatever amount of energy he can access, if we look at all of them, his pension should be health 11:00, we look at all of them, his pension should be health 11:00, we look at all of them, his pension should be health 11:00, medical here, so what have we given it from here, label Returned, okay, now look at this point, hmm, okay, at this point, when we went to the right, how much energy did we have left, you got saved and when we went down, how much energy did we have, the level is fine. So here we are, at least among these two, where are you in health? So, accessibility has been achieved, that is, if I am on this channel, then I will need at least five help. Five will be needed so that I can save the princess. Okay, now we're here on Spain okay so from here I've always got five got that if I go to the right you're my five energy that baby if I go to the right and if I go down If I go then let's see how much we will save, so we went here, okay, from here, we went like this, from here, we got into the forest, from here, we went further down, when we went to the right, from here we always got monkeys, okay, When we give it, then from here we have got the maximum, so one. Now let me explain back to the point, here we have a power and it should be used to save this earth because it should be minimum so that is why we have here. But got 4 returns returned and from here also we will disconnect it. It is okay that the power it is getting here is okay and at least how much health should have been saved, fish is needed. Okay, so where should a Meera phone go, that means nation help. At least how much forest can be there, only then we can save the princess, what have we got from here, we have got it, of course, now look what is here, 8 - the pipe is fine and with its help, how much should have been 8 - the pipe is fine and with its help, how much should have been 8 - the pipe is fine and with its help, how much should have been saved from here, forest fish and If he gets help, then from here you can see me here, when I want to be on the two, I am on this one, it's okay, I know if I go down, what time will my life come, A six will be left, it's okay if I go to the right. If I go there, I will have five lives, so if I start from here, then here - that is the minimum which if I take, then I will go here, nor if I see that when he starts moving from here with Civil Lines, then neither Look - if his life gets reduced here, neither Look - if his life gets reduced here, neither Look - if his life gets reduced here, then how much life is left for him? If he goes to this group, then how much will his life be? When he goes here, he will lose his power. Fifth, when he goes here, He will get power off, his life will be this much, it will be fine and when he goes here, he will have to fight with the domain, so out of the total energy he has spent at least five energies and at the end he has one energy left. It is necessary so that he remains alive so here the minimum initial laugh from our consumption went and tell me that you I think you must have understood here that I have kissed health equal to 16 121 here maximum curator Ok, this expression will be shared in many stoves. Now let us look at it. Before looking at one more thing, here the date of our 'A' overlapped, all these problems also came due to which date of our 'A' overlapped, all these problems also came due to which date of our 'A' overlapped, all these problems also came due to which we can cook potatoes. If we have already visited, then look at it again as secure and if our parameters are changing, then here we are changing only the columns to move ahead and if we are not changing anything else, then we can tell the things here. What will our DP become here? Here we Ritu Dipper said whatever changing parameters according to the changes parameters and whatever we have in the column is okay, now we look at its boot so I said that here these Rohit 120 for these Qualified heroine or set a meaning of stupidity and banani. See, I have made a to-do list for you. See, I have made a to-do list for you. See, I have made a to-do list for you. I have made it a friend's digest of the mind and a share digest. Why have I made this because at the most, that night should be kept till the last moments. If we have to reach then we are fools, how much contract do we have with the laborers of the districts, it is clear that we have to do it, okay, I am India and where I called a rescue function in which I sent what I sent to our Qureshi Arup, gave the volume again and daughter. So now look where we can go, if we can go to the right, then I have created one of these websites and have called the reception. To go to the right, what will happen to the right? Our call will be made to Laxman, okay. And sent to the duty, it is okay that now it may be moving in chloride and may not even come out at our destination then how should we see it. If my room has become greater than the physical two-year dot size, is it okay become greater than the physical two-year dot size, is it okay become greater than the physical two-year dot size, is it okay or is our fall great reluctant? Fair of parent size became that last week here when camor came out of our ton, what does he need, he wants more and more energy, so I returned from here, he came on the road, it is fine and this hair is now zero. Only and apart from that, it can be said that it can go down, okay, so now I have called the rescue function, we will take another 1 inch extra here and this will get minimum ho the right for download with four days note is available. Pull this one and delete it, which follows the minimum balance which will go down in that knight's place or we may have cases, meaning that witch lord is a block of plots, that idiot will go up the mountain with the clock, meaning with Lock and look here also, go here and look and on both sides, he needed so much help, he needed to play with the bunny, okay, that's why I wrote it here, then we will put it here, we will fold it like this, it means that here if She is and here is the princess. At least she needs a like so that she can be a I can save the princess okay and if it is not so then what can you do now *Let's make the result what can you do now *Let's make the result what can you do now *Let's make the result okay President Minor Why not, we will make this corner from inch, we will make initial health and initial equal to how much it will say, whatever is our HI, from the lock which is presented, how much energy will it get there or how much energy will be consumed by it - we will do it only how much energy will be consumed by it - we will do it only how much energy will be consumed by it - we will do it only then our Animation health will come here, so whom does this expression delete, so now what can happen is that now whatever his initial health effects will get inclined towards me, what will happen in negative, will he be able to kill, so at least how much help will this mark give him? We need a ribbon, it is ok, otherwise what can happen, the more successful it is, and if we have any problem, it is already calculated, a little more probe, hall notice will be Tweet - 6, then from there hall notice will be Tweet - 6, then from there hall notice will be Tweet - 6, then from there we will return the BP off. Rok and flowers are the only place where Ma'am is a slice old above Hanif Road ki Bollywood It happened that our answer is coming right then it was from simple comfort that this Manjan Giver is not a difficult thing which we only had to see that if it is in this Some animation on the blog wants health, so now we just had to see that if he wants to save this princess, at least his health should be 1954 so that he can save the prince, which of these we used and If you understand the question players, if you have any doubt related to this question, please write in the comment section, we will definitely answer. Thank you so much and if you liked the video. So please like and share this video and do n't forget to subscribe. Thank you so much.
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
1,996
hi everyone my name is course again today i'm trying to solve the uh september liquid challenge well now the problem is number we character in the game so basically what is that you are playing a game that contain multiple character and each character has a two properties that is attack and defense so you are given the two integer added properties for properties i there is a two component that is attack and the defense it represent the add character of that value so a character is said to be weak if any other character has both attack and the defense value is strictly greater than the other character attacks and difference value so more formally that when the attacks of attack value of j is greater than attack value of i and the defense value of j is greater than uh defense value of i in that case that will be the weak character in this game so we'll have to return the number of character has been present in that total game so fast i'll dry run on the then after i'll try to make that coding interpretation so first i will try to check that 1 5 10 4 and 4 3 1 5 10 4 and so basically what i'll do that i will make a custom shot basically custom sort because uh there will be two cases here basically uh basically there is the this is the attack condition uh attack value and this is the uh difference volume that is there so when that is the i is greater than j in that case there is also i and that is suppose that j so if there is a greater than that so in that case that will be uh computed as the uh weak character so that is why we will have to check that uh making a custom shape so cast in the custom shot basically i will run there basically according to the greater value of the attack character that is 10 4 and 4 3 and 1 and 5. so what happened that so basically if i'll do that there will be no required to check that will be the automatically because that is the greater value there that is the greater value in each case when i have been going to the down case basically from the height i have been iterating to the end so at that condition we'll have to check that i am taking a variable that is supposed as a temp so that is minus infinity so when the value has been passing through there when there is a that is the value will be passing through that in that case it means that when the value is the if temporary value is greater than the current value that's the pointer so what is that the properties of i and the there is a one basically so what happened that in that case whatever that will be that uh the minus that is also taking as an account basically in that case basically when that is the value will be the greater than that in that case the value will be updated into there but otherwise case when the that value is greater than that is the condition where it's fulfilling the i is greater than that attack of i is greater than attack of j and the difference of i is greater than a difference of j so in that case i will update it or increment the answer value by 1 and after that when the traversal has been all or completed then after that i will return that answer so basically there's the custom short function there will be required to do that so in that case i do the custom short so in that case the time complexity will be order of n log n where n is the uh length of that total array and the space complexity will be i'm not taking any extra space so basically the order of one is the space complexity for that case and time complexity here for the n log n and this is the order of one case so uh first of all i'll have to repeat that condition one more time 10 4 3 and 1 5 what happened that basically that is the decreasing order so attack is already greater than the previous one i mean that next value not previous so when there is a column here the already previous one is greater than that if the previous value if the minimum condition value minimum value what the minimum value will be updated there if the minimum value is greater than the current the defense value greater than the divisible it means that is fulfilling the criteria of the weak character so in that case i have been increasing the uh the answer variable there and otherwise case that will be updated into the temp variable so that is how i am trying to implement my logic so right now i am trying to implement my logic as a coding interpretation so basically first i'm making the custom shot so static integer and percent and percentage and first we'll have to check that the logic if um if a of 0 is equals to b of 0 in that case i will return the a of 1 less than b of 1 that will be the shorting order right and checking there that is what is happening that is not uh to be the mentioning there so what is happening that after that i will return there as a i of 0 is greater than b of 0 so that will be the upgrading as a the greater format yeah so first i'll short that area basically properties begin properties obtained and the cmp now my sorting will be done i'll have to check that as in the temporary variable what is that is mean infinity i mean that mean inch sorry forgot there that's now completing this so for auto p of the properties that will return the vector basically part is so after that if my p now i mean that uh the temporary variable is i mean hold on uh what's the logic there basically what is the value yeah that's the logic behind hold on i'm updating that if that value temporary is there okay yeah got it when tmp is greater than i mean that less than sorry not greater than so p of 1 and after that is a temporary variable will be become p1 otherwise case that the answer value will be incrementing there okay i'll have to also initialize the value there and after that all the traversal has been done then after that i would return the answer so let me check that my logic is correct or not okay when that is goes to there is basically that will have to do that it is going on that is when a both of them has been fulfilling their criteria when there is a fulfilling of that criteria it means that is the a1 and the b1 and otherwise case that will be the age 0 and the greater than b0 okay that has been already fulfilling and then after that properties begin properties in an integer mean and the answer will be there and after that the when the first wallet check that suppose both case the properties are there that the value will be so let me check that and that is accepted there but what happened let me check that it's giving me one more than that okay first we'll have to check that which is the value has been greater than there suppose we'll have to check that the reverse logic there greater than that if that is a greater the value has been less than that in that case i will be the updating there and otherwise case that will be updating into their temporary is equal to p of 1 so that will be the case for there so let me check that i think that will be the correct for there that is accepting for this so right now i'm trying to submit yeah it's got accepted thank you so much you
The Number of Weak Characters in the Game
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`. Return _the number of **weak** characters_. **Example 1:** **Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\] **Output:** 0 **Explanation:** No character has strictly greater attack and defense than the other. **Example 2:** **Input:** properties = \[\[2,2\],\[3,3\]\] **Output:** 1 **Explanation:** The first character is weak because the second character has a strictly greater attack and defense. **Example 3:** **Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\] **Output:** 1 **Explanation:** The third character is weak because the second character has a strictly greater attack and defense. **Constraints:** * `2 <= properties.length <= 105` * `properties[i].length == 2` * `1 <= attacki, defensei <= 105`
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Math,Dynamic Programming,Combinatorics
Hard
null
1,851
hey what's up guys uh this is sean here so this time uh lead code 1851 minimum interval to include each query all right so this one is another query problem right okay so you're given this time you're given like a 2d integer array intervals you know where the intervals have like has a left and right and describing the starting point and the ending point and the size of the interval is it's of course is the is this and then you're also given like integer array of you're given like a k queries right and for each query there's only one element right which means that you know we want to find the smallest interval such that you know the query number is inside that interval if there's no such interval exist and we simply set the answer to -1 set the answer to -1 set the answer to -1 right so for example we have this four intervals we have one this four and then the queries we have is two four two three four five so for query two here right how many uh candidates how many intervals available candidates we have here we have two right we have this one four and it's two four and among those kind of two intervals uh we choose the one who has the uh the smallest intervals which is this two four because this one four minus one plus one is four right this one is three that's why you know this one is also four this one is one right this is the size that's why we have three and then for three same thing since three are also inside these two intervals and we also get three here and then for four right uh so four okay so four is also in uh so now it's four is as you guys can see four is inside all four intervals and this one is the smallest one that's why we return one here and for but in terms of five right when it comes to five actually only uh in uh is in this one interval which is three to six that's why we only have four here so that's the description for this problem you know again right for this kind of query problems you know and usually the constraints is of a pre-standard 10 to the power of five pre-standard 10 to the power of five pre-standard 10 to the power of five which means that we cannot for each of the queries we cannot have that luxury you know to scan all the intervals right because that will obviously be a n square time complexity and which will lead a tle that's why for this kind of like k query problems we always need to sort this query one way or the other and then we also gonna have to sort the source data here so that we don't have to consider basically check the same element repeatedly for the same for different queries here okay and for this problem i for this problem actually is even simpler because you know first the queries only has one element which means that we there's we only have one options we either we just sorted right and then we have to consider right how can we uh code make uh write the code so that we don't have to these intervals multiple times right so for this problem you know i think it's also kind of straightforward you know uh we see we just also need to sort these intervals by its starting time okay which is the natural sorting order here and if we do that okay so every time you know we have like intervals you know let's say we have a query and we have intervals let's say we have intervals like 1 to 4 right and this is a sorting order basically and we have one at this interval and the query is two so the query is two and we just need to check if this connect if this uh starting time is either equal smaller than 2. if that's the case we know okay so this interval might i mean not necessarily right might include this query here okay so that we can uh check this interval right and if this one doesn't satisfy this these two can do doesn't include this courage we can simply ignore this one and we don't have to uh consider this one again when we process another query let's say for example three or four or five and why is that because since the later since the rise of queries are all bigger big a greater than two right so which means that you know if this interval doesn't include will not include two which means that you know uh the only if this one doesn't include two maybe it means that you know this one uh probably it's gonna be a uh one right or zero one right this is the only two options that will not include this one since are using this kind of like starting time right to include at starting time to sort these intervals and if this intervals cannot include two here we can we don't we will we're not going to check that for the 3 because 3 is greater than 2. if it cannot include 2 it would not if they would definitely not won't include 3. that's why you know by doing this the sorting here you know for each of the intervals we only need to check them once okay so that's the first step and the second step is that is this you know since we're only checking the left here you know there's also a right and for right i think it's pretty straightforward you know every time you know we also check if the right is like is greater equal greater than this two if it is and then we know okay so this intervals can cover the current query right and but that's not the end of the story because since we're removing this kind of a queries uh one by one you know the candidates right the candidates might change because by moving into three or five or four you know the sum of the candidates intervals could be uh could become invalid because it could be moved outside it could be can it may not be able to include this current query here right and the last thing is that no even all the candidates are valid candidates we still want to find smallest intervals among all those kind of candidates right so that's why you know after we're figuring out these sortings we need a second we need another solution to efficiently to uh to remove the invalid candidates from the candidates list and to also uh quickly get the smallest intervals right among the valid candidates right so that we need like a data structure because we simply cannot do like a linear scan because that's what that beats the entire like purpose of this sorting and then it will go back to this n square time complexity so what we can do in python is that you know we can use a priority queue and why is that so first this priority queue can always give us like the smallest intervals in all one time right basically the main reason we should we choose the priority queue is that if we put the first element in this particular to be the size of the valid uh intervals right and then this particular will naturally give us the smallest interval right and okay so this then the smallest interval problem is solved the second one is the last problem we want to solve is that how can we remove the uh the invalid intervals once we move to a new query right and how can we solve that this one is a little bit tricky actually so what we can do is that you know in the product queue right when we insert these candidates into the priority queue besides the size itself we can also insert this right into the right value along with the size and the reason being is that you know if we have this right value along with the candidate the intervals you know every time when we have like a new queries here we can always check if the priority queue 0 1 this one is smaller than this query number remember this product q zero is always pointing to the smallest intervals at the moment and we only care about the smallest intervals and if this one is smaller than the numbers here you know it means that you know okay so the current smallest intervals becomes invalid so that we have to pop we have to do a hip-hop hip-hop hip-hop for the current priority and if the card so if this one if the smallest one is still within the range of numbers then we know okay so the current smallest intervals doesn't change you know even though in the product queue you know there are like some direct sum like intervals have already uh become invalid but since it will not affect the current the smallest intervals we don't care all we care is that you know if the current smallest one the current smallest interval will be affected by uh by having this kind of like interval the sorry but having the car a new query cool yeah and that's all the uh the things we need to be cons to consider here and then we can start coding them right so again for this course right since we're going to get the answers for the queries we always need to add the uh the index onto the index along with the under the number itself right for i uh dot number in the enumerate uh course right and then we sort right sort second one we also store the intervals right by the starting time and we have n gonna be the length of intervals right and then we have the answer it's going to be the uh starting with minus one and then the size is the length of the course okay and then we have the j equals to zero like which is pointing to the unprocessed right i'm processing intervals and then we have a product q right to store the uh available right no to give us the smallest uh as small as the size smallest interval size right okay so now for the nums and in i increase right all right so this i'm not using enumerate so this is like original index right so first we check right while j smaller than n and the intervals right intervals of j 0 which is the starting time of the current intervals is within the nums this means that you know the current one the current interval could be at a candidate right could be a might include the card number so this one i'll just do this one since the intervals it's pretty long here you know so we have left and right for the current one and if the r is either equal it's greater than the number then we know okay so this intervals this interval will include the current number that's why we simply push it into the product queue right that's because that's going to be our candidates and like i said the key the element we're pushing in into it the main key is like the size of the intervals and we also need like the uh the right the r the right value to help us to remove the invalid ones right and then we of course we do a j plus one right basically we check if interval j right can include right num right all right so here you know if j okay so i'll leave it here so what i'm trying to say is that you know so we only need to check this j once right only need to check intervals j once right because it can it will either include or not include right because the uh you know the current the number is always increasing and you know if the current intervals will not include this number you know a bigger number would definitely not be included in the same interval right that's why we can always increasing this j here and cool so and after that you know we will you know remove right the intervals the invalid intervals right which will affect the smallest size right that's why we do product queue and the priority q.0.1 right and the priority q.0.1 right and the priority q.0.1 right is smaller than number which means that okay so this one the card number will affect our smallest value that's when we need to pop right prodigy okay and after that you know we simply update the answer right if the product q is not empty right then we know okay we have at least some smallest size for us for this current query which is the particular.0.0 okay which is the particular.0.0 okay which is the particular.0.0 okay and then we simply return the answer in the end that's it so accept it and run the code okay there you go right so it passed and so time complexity right um there are they're both like uh same like cons number of uh not like same like 10 to the power of five that's why we have um unlock n right to sort and then here is also like n and this is one and then we have like priority q push and pop this is also only push and pop once yeah so here's also unlocked yeah so yeah basically this is the unlock and solution here yeah and space complexity of course is n right so we only have like queries and the answers and also the priority queue space time um yeah i think that's it right i mean another query k queries problems you know i think we have already find like a pattern for this one uh we always sort both the queries and the source one way or the other so that we only need for each of the source uh item we only need to consider them once okay and after that uh based on for this one you know based on the requirements we have to somehow to find use another data structure to help us achieve both uh achieve to find the smallest size of intervals and to remove the invalid intervals efficiently that's why we use the priority queue here because particular will give us 01 time of the smallest size to find the smallest size and then the log n time to remove the invalid intervals i think that's pretty much it is right and cool thank you for watching this video guys and stay tuned see you guys soon bye
Minimum Interval to Include Each Query
maximum-number-of-events-that-can-be-attended-ii
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Array,Binary Search,Dynamic Programming
Hard
1478,2118,2164
76
hey guys welcome today we're going to be taking a look at the minimum Windows substring question on lead code now this question consists of taking two strings one called s and one called T and trying to find the minimum window in s the minimum substring in s that contains all of the letters in t and if we can't find any such window any such substring that contains all of the letters in t we're just going to return an empty string uh the one interesting point that's highlighted in bold here is that the T can include duplicates so if there are multiple repeating characters inside T we have to find the same number of characters in s before we can consider it a valid window now let's take a look at a couple of examples what I would like to mention before we do that is that this is a perfect candidate for the sliding window technique which I'll get into in a bit but essentially if we're trying to look at the input set and we're trying to optimize a sub range in the input set just like we are with s we're trying to optimize the sub-range in X then the optimize the sub-range in X then the optimize the sub-range in X then the sliding window technique might be something that could be helpful uh and what we're going to do first however is just take a look at a couple of examples so here we have S is equal to one a b one two three and c and we have t equals one two three now this one is pretty straightforward we can see that T can be found in s right here as it looks like in T it's found directly in s same order plopped it right in the middle but we should also note that there are other substrings that contain all of the letters in t but some other characters for example b123 b123c you get the idea there are a few more than a few substrings that contain all of the letters in t with an S but what's so special about that first one that we highlighted is that it's the smallest one and there can't be a smaller one than that because that is the number of the characters that are in t are uh three we can't get smaller than that without losing one so that's what we're looking for we're looking uh for the smallest that we can possibly make it uh substring an s that contains all of the letters in t taking a look at a bit more complicated of an example we have one two three again as T and then a as sorry s is a bit more complicated it has a 1 b 2 c 3 d 1 2 and you can see that one two three is spread out in a couple of different variations inside s but we can still spot sort of pretty easily that there's a one two three here all right and now there's actually another one here two three one remember it doesn't have to be in the exact same order that it shows up in t for it to be valid are there any other oh there's one more there's three one two here um now there are other substrings in s that contain all of the letters in t but they're bigger than the ones that I've highlighted here so I won't uh I won't look at those uh and out of the ones that I've highlighted the purple one is the smallest 3D one two with four characters and then the other two both have five characters so this might give you a clearer picture of what we're looking for maybe some of the complexities in the problem um where T can be found in a different order spanned across other characters that aren't in T and there can be a couple different variations of it that are found what we're and out of those very out of all the ones that we find we're looking for the one that is the minimum now let's take a look at a final example here let's say t is one two three four and S is a b one two three c d e f uh now we can see that there's a four in t but there's no four in s and so right away we know that this pattern T can never be found in s and so here we would just return an empty string all right so out of the examples that we saw let's try to come up with a Brute Force approach that gets Us close to an efficient algorithm uh and we can always start with Brute Force and optimize later this is a well tested battle tested strategy for programming interviews if an efficient solution isn't immediately clear to you always think about what could be the Brute Force approach so what is the Brute Force approach that returns us the minimum window substring in s that has all the letters in t namely in this example it would return 3D one two and in the example above it would return one two three so take a minute pause the video try to come up with an algorithm a series of steps uh maybe some code or thoughts of a Brute Force approach it doesn't have to be optimized a Brute Force approach that returns us the minimum window substring in s that contains all the letters in t all right welcome back now let's think about what the problem is asking so the problem is asking us for the minimum window substring it's asking for a substring in s so our solution is one of the substrings of s a truly Brute Force approach would be to generate all of the substrings of s and narrow it down filter those until we get our solution the one that fits our criteria of being the minimum window substring of s that contains all the letters of a t how would that look like let's take a look at an example where s is equal to a b one two three C and T is equal to one two three so if we generate all of the substrings of a b one two three C it would look a little something like this and out of these substrings we want to narrow it down so we identify the minimum window substring of s that contains all the letters in t so first off let's just identify the ones that have all the letters in t of T in s in these substrings so the ones that have one two three within them just go ahead and mark them with a thumbs up and the rest enough so out of the ones that we marked with a thumbs up we only want one and that is the one that is at the minimum and so we can see that this is the minimum one here one two three so that is the Brute Force approach where we generate all the possible solutions all the substrate all the possible substrings and out of those substrings we try to narrow down until we get one solution um that fits and matches our criteria um and so this works but it's quite inefficient we'll get into why in a bit let's come up with a time complexity here the time complexity is dominated by the search for substrings the computation of substrings fs and I say the length of s is n then it would be o of N squared and this is because the computation of substrings takes about uh the sum of want and the natural sum that's how long it takes to compute the number of all of the substrings of a given string um it would and that gives us a Big O worst case time complexity of O of N squared why is this inefficient what is the Brute Force approach doing that is over computing well it's searching substrings that could never be a valid substring it could never be the minimum window substring for example here we see that it continues generating substrings after eight it sees that ab12 is a substring that goes ab1 a b a and then a but it should have stopped at ab12 because anything any substring of ab12 will never be valid it can never contain something it doesn't already have it can't find that three so that will never be valid so what we want to do is look through the substrings the windows in s in a way that we're not over Computing we're not Computing substrings we're not Computing windows that can never be valid and this is where the sliding window approach comes in all right so the sliding window technique is useful when we have a question that's asking for an optimal sub range and in the input set and in this question the input set we have is s and we're looking for the optimal sub ranges and the minimum window substring that matches our constraints of having all the letters in t so the sliding window technique is a good candidate for a template problem solving uh technique here um what it'll involve is we'll keep track of a window using a left and a right pointer a left pointer pointing to the beginning of the window and a right pointer pointing to the end of the window go through an example to work it all out so let's say a I'm sorry s is a 1 b 2 c 3 D1 2 and T is one two three uh then let's create a window on it and let's say that it initially the window is initialized where both the left and the right Point are pointing at the same thing the same element uh which is the first element a what we want to do is we want to expand the right pointer up by one until this window contains all of the letters from C until this window is valid according to our constraints so it previously was a now it's A1 we've expanded the right corner up by one we're going to do that again because it's still not valid so we have a1b and again once more because it's still not valid A1 B2 and so on until the window becomes valid and that'll happen here so we have A1 B2 C3 we've expanded the right pointer until the window has become valid and when we get to a valid window every time we want to check the length of it to see if it is below our candidate for the minimum window so the length of this is six and this is the minimum that we've seen so far so we'll record that and as you can see here in the next step we contract the window so when we have an invalid window we expand the window by moving the right pointer up by one but once we have a valid window we contract it by moving the left pointer up by one and so the window becomes smaller and the reason we do that is so we can find the minimum window we keep Contracting the left pointer and we keep moving the left pointer up by one and Contracting the window until the window no longer is valid according to our constraint until it no longer has all of the letters from c letters from T contained within it doesn't have one two three so uh if we move the left pointer up by one initially it's still valid and we since it's valid we record the length of the valid window it's five it's less than our current one so this becomes our new candidate for the minimum window substring that contains all the letters from T and we contract one more time moving the left pointer up by one and we can see that it's not valid anymore it doesn't have a one in it anymore and so it doesn't have all the letters from T within it uh what does that mean for us in our algorithm using the sliding window Technique we expand the window expanding the window means moving the right pointer up by one so we do that now it contains d still not valid because it's still missing that one and if we move it to the right one more time we can see that it has now become valid and so we record the length it's six and since it's a valid window we contract it by moving the left pointer up by one and so the left pointer moves up by one and we get another valid window um this window has five as the length it's uh the same size the last minimum candidate so we don't it doesn't really help us um we continue by Contracting the window one more time by moving the left pointer up at one and we can see that it no longer is valid it doesn't have two within it's missing the two so uh since it's invalid we'll expand the right pointer up by one when the right pointer is expanded by one uh we see that it has become valid it contains all the letters from T three D one two we record the length here it's four oh this is our new minimum so our new minimum window um and since it's valid we want to contract the window by moving the left pointer up by one moving that up it because it no longer is valid and uh we are done at this point because we can't move the right pointer up by one and moving the left pointer up by one uh would decrease the window size so that it is smaller than our desired length therefore uh we can exit the algorithm and look at our candidates and pick the minimum one which is four in return and so at the minimum candidate and at the minimum window substring is three D one two and that's what we return using the sliding window technique so hey guys let's get into the coding portion of this algorithm that we just saw and initially what we want to do is just break out the cases where s is empty or t is empty so we get that out of the way and we only have to deal with the non-empty cases uh what happens if s is non-empty cases uh what happens if s is non-empty cases uh what happens if s is empty not s and python well then we won't be able to find any uh pattern T within it so we would return empty in that case but we'd also return empty and when T is empty because then by default we find it in NES so we'd always return the empty string when either as or t or empty so that gets the empty cases out of the way now we can move on to the actual sliding window technique and for that we have to define a couple of variables first if I'm being frequency of T freak T and freak T will use the counter class in Python to generate an object that has the unique characters of T map to the frequency of their occurrences so if there are three characters for example uh Three A's in t then this object would be a mapped to three and so on and so forth for all the other unique characters another variable that we'd like to keep track of that will help us implement the sliding window algorithm will be the frequency of the characters in Windows long name but this it also tracks frequency of characters but it's only the frequency of the characters that are in our window and this will be an ongoing count that will subtract and add to when the window increases in size and contracts in size remember the sliding window technique has a left and right pointer that keeps track of a window that we use essentially to search the input string and find our optimal uh set or answer the minimum window substring and in order to do that in order to find the answer we need to keep track of another variable and this one will be called num underscore missing and this will be equal to the frequency of the characters of T it's this the num missing is the number of characters that we currently are missing from our window for uh and when numb missing is zero we are missing zero characters from our current window um and so our window is valid so the importance of this variable is that it helps us keep track of whether or not we have a valid window okay moving on another variable that we'd like to keep track of is obviously our answer variable will be a tuple it'll hold two values one being the left so you can say initially this is negative infinity and the right which is positive Infinity foreign will return s at answer zero to answer one and it's only if we're able to find a minimum window so if answer is negative infinity or Infinity for any one of those two values then we'd actually have we haven't found a valid window and also would return uh empty in that case and in order to do that we'll just do a check above if answer at zero and equals foreign so now we have all of the variables defined to run sliding window and the main bits of sliding window rely on two pointers a left pointer that will initialize to zero and a right pointer that will actually use a for Loop to increment and it'll start at zero and go to the length of s we'll keep track of a variable called character that is equal to what's inside s at right and we also want to update this frequency of characters that it's in our current window so characters in our current window we want to update the frequency of character by one to do that we can just do a frequency.get character and give it a frequency.get character and give it a frequency.get character and give it a default value of zero and add one what this allows us to do is to check well we first check if the character is interesting to us and it's interesting if it occurs in T So character is in frequency of t then we want to do another check on it we want to check if we've encountered this character the number of times that it occurs in t if we've encountered this character in our current window if we've encountered the encounter this character um the amount of times that it occurs in t then that then we don't have to look for this character anymore then we can decrement that numb missing variable by one because we have one less character to look for remember that starts at the number of unique characters in T and when that reaches zero that means that we have found the required number of characters for all of the unique characters in t when them missing a zero and that means we have a valid window so that's why that variable is important and that's why we have these other variables that are keeping track of the frequencies occurrences in our current window and their total occurrences so if the frequency of the characters in the current one if the frequency of the character in the current window is equal to the frequency that occurs in t and we can decrement the num missing by one and while num missing is zero so if the window is valid that's why I'm not missing a zero and the left is still less than or equal to right because we're going to want to increment left here because we're Contracting so since the window is valid uh we want to contract the window but before we can track the window we're going to need to check if the current valid window is a little less in length than the window that we have in our answer variable so if I say right it's track left is less than answer one subtract answer at zero then we can say answer is equal to left right the length of the current valid window is less then the answer that we've been keeping track of so far and initially any length will be any length of any valid window will be greater it would be less than we want to update our answer and after we've updated our answer we want to contract the window and uh see if we still have a valid window if not missing is still zero and that can if we do we keep on doing that until we've minimized the current window and so we get the minimum version of this valid window to check our answer against until the window is no longer valid at which point we'll continue looking for a valid window um so we have other very another character that is we're going to check if it's interesting to us it's character at left currently so we'll check at the left and if the we well first we want to decrement the frequency of the occurrences of this character by one and then we want to check again if this character is interesting to us it's interesting if it occurs in t great and if the frequency of occurrences of this character is less than the number of times that it occurs in t 2 add 1 to them missing because now we have less than number of required characters for this particular character we have less than the number we need for us to Encompass all of the occurrences that it has in T and so our missing no missing variable goes up by one um it is no longer a valid window and we also move left up by one and that's it so this covers all of our cases let's try hitting submit boom we have an accepted answer thank you for watching guys hit like And subscribe if you learned anything from the material please give a comment if you have any feedback thanks and have a wonderful day
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
997
hello guys I hope you are all doing well and this video we'll be solving the lead code problem find the town judge so let's get started so the problem is that you have a list of people in the town and the task is that you need to find out who is the judge in this town so before we solve this problem let's break this problem into pieces so we can quickly solve it using only the details that they give us the first information that we have is the town judge is someone who trusts nobody and is trusted by everyone else the second affirmation that they give us is that we have earned people in the town and the third information is that we have a list of trust relationship and this list represents a pair of integers the first integer is the one who trusts the second integer represents the person who is trust so to solve this problem we're going to use just a simple accounting algorithm we're going to create an array to keep track of the number of persons who trusts and the number of person who is trusted by others and one of the key to solve this problem is that inside all those people and we need to find that at the end the numbers of people who trust the town judge must be equal to n minus 1 means the end people -1 and the minus one represent the one -1 and the minus one represent the one -1 and the minus one represent the one who is trusted by people means the town judge so let's say we have three people and this input list of trust first we create an array that have the same length of n people and set his value to be zero then we need to Traverse the list of tourists relationship and for each pair integer we decrease the trust count of the first person by one and increase the trust count of the second person by one for example for the first integer inside the list is one which represents the person who trusts so we're gonna decrease his value by one inside the array that we created before then the second integer is the person who other trusts so we're gonna add one to it inside the array then we move to the next pair of integers the first integer is two so we put minus one inside the array and a new index because it's a new person and the second person is the same person who people trust so we increase his value as inside the array by one so after the loop finishes we Loop another chime over the end people and we use the index of this current Loop to Traverse the array that we made before and as I explained to you guys before that the key to solve this problem is that we need to find that at the end the numbers must be equal to the town judge so that's why we Traverse the array to find any element whose value is equal to n minus one I mean this person is trusted by n people minus the town judge so if there is a no such person will return -1 so there is other test case for -1 so there is other test case for -1 so there is other test case for example where the person one trust person two and person two trusts nobody so here the person too is the judge also when there is only one person and he trusts nobody so we can say that he's the judge and the output should be one so you can create as many as you can to test the age cases that's it guys so let's jump at code in the solution first we initialize an array trust counter of size n and we set his value to be zero then we Loop over the trust array and for each list software integer we decrease the trust sculpture of the first person by one and we increase the trust counter of the second person by one then we initialize another for Loop that Loop over the end person and we use his index to Traverse the truss counter to check if one of its value are equal to n minus one if true we return the index plus 1 which represents the person who is trusted by n minus 1 people and trust nobody finally we'll return -1 if there nobody finally we'll return -1 if there nobody finally we'll return -1 if there is no such person who can be trusted so the time complexity for the solution is oftenware n is the number of people in the town or we can say because we are iterating throughout the trust sculpture that have the size of N and the space complexity is often because we're great in our rate there are structures to keep track of each person inside the list that's it guys thanks for watching see you in the next video
Find the Town Judge
find-the-town-judge
In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: 1. The town judge trusts nobody. 2. Everybody (except for the town judge) trusts the town judge. 3. There is exactly one person that satisfies properties **1** and **2**. You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist. Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_. **Example 1:** **Input:** n = 2, trust = \[\[1,2\]\] **Output:** 2 **Example 2:** **Input:** n = 3, trust = \[\[1,3\],\[2,3\]\] **Output:** 3 **Example 3:** **Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\] **Output:** -1 **Constraints:** * `1 <= n <= 1000` * `0 <= trust.length <= 104` * `trust[i].length == 2` * All the pairs of `trust` are **unique**. * `ai != bi` * `1 <= ai, bi <= n`
null
null
Easy
null
331
welcome to august 26th leco challenge verify pre-order serialization of binary verify pre-order serialization of binary verify pre-order serialization of binary tree one way to sterilize bearing binary trees to use pre-order traversal when we trees to use pre-order traversal when we trees to use pre-order traversal when we encounter a non-none node encounter a non-none node encounter a non-none node we record a node's value if a null node if it's an all node we record a sentence value such as the string pound so for example this binary uh tree here um of the bubble binder should be serialized as the following string so notice the strings uh comma separated value and we have pound signs and numbers in there as well but they're all strings where a pound represents the null node given the string of comma separate value pre-order string of comma separate value pre-order string of comma separate value pre-order return true if it is a correct pre-order return true if it is a correct pre-order return true if it is a correct pre-order traversal serialization of the binary tree it was guaranteed that each comma separate value in a string must be either an integer or the character pound or hash represent the null pointer representing the null pointer you may assume that the input format is always valid for example it can never contain two concept commas such as comma no you're not allowed to reconstruct the tree so uh we're given this pre-order uh so uh we're given this pre-order uh so uh we're given this pre-order uh string array and it returns true because that's the tree that up here that we're given so that is in um pre-order traversal so it is the pre-order traversal so it is the pre-order traversal so it is the serialization of that binary tree however this is false it's pretty obvious because uh you can't have one then no that's not a pre-order traversal binary tree pre-order traversal binary tree pre-order traversal binary tree and likewise you have nine fold by no null one that's not pre-ordered null one that's not pre-ordered null one that's not pre-ordered traversal trading so the pre-order length so the pre-order length so the pre-order length is one to that and four pre-order is one to that and four pre-order is one to that and four pre-order consists of energy between zero to hundred and except by a comma and it has hash signs in it so basically um you just given a string and you want to verify whether it's a serialization or pre-order binary tree that's pretty much pre-order binary tree that's pretty much pre-order binary tree that's pretty much it so pre-order traversal meaning that it so pre-order traversal meaning that it so pre-order traversal meaning that um you would keep track of the numbers uh traveling like that so if it's a period traversal you would count the numbers first it'll be nine three four followed by one four by two and followed by 6 and the pound sign represents a null node so for instance um 9 3 4 and then the house it's supposed to have two more null nodes at the bottom but those are not so every pound going all the way to one pound going to two pound six pound and that's it so that's the um that's how we do pro traversal so starting from this you count the number first and then you go down then you count the null nodes as well so in order to do this i'm gonna do a um what you could do is actually a reverse traversal so just go backwards and kind of analyze whether it's uh it's valid or not and using a stack to keep track of the uh the string so let's do that let's see if that works so stack i'm going to make that empty make a stack and then now we are going to parse up the pre-order string because we don't the pre-order string because we don't the pre-order string because we don't want this just comma separated value we just want the number of values in there so it's going to be pre um we're going to reassign it actually just called pre-order pre-order pre-order dot split via the comma all right that seems like sentence and then we'll do a for loop in there to iterate through each element inside the uh the values inside the pre-order the pre-order the pre-order split value so for uh each index in the range of the length of pre-order uh you want minus one we want to reverse traverse it in reverse go backwards by one and then if the pre-order and then if the pre-order and then if the pre-order uh value at i is not equal to the null value then what we want to do is uh check see if the stack is less than one so if the length stack is less than two i should say that we want to return false because uh that's not a valid pre-order traversal that's not a valid pre-order traversal that's not a valid pre-order traversal of the binary tree otherwise we would want to uh stack pop from the stack right um we'll pop from the stack twice because um if the length of stack is less than two that means that it's two they need each empty node here has two null values and the only way it could be one is if it has a branch like this so you'll pop the stack twice and then we want to append the pen we are going to append the pre-order we are going to append the pre-order we are going to append the pre-order traversal at index i all right next we want to return a boolean such that the length of the stack is equal to one let's check to see this right true awesome accepted so i pretty much made to stack universes in reverse we traverse it in reverse order and then we just if we check to see the line if the value at the next i is equal to pound if so we're going to check to see if the stack size is less than two if it is you can't have that because it's not an end a leaf node therefore we pop it twice and then we append the um the index back to the stack and then we basically do the we repeat the for loop right until we see the stack and we returned true only if uh length of stack is equal to one that means that this that means there's always going to be one value inside the stack because we're traversing in reverse order all right and time complexity is big o of n where n is the length of the pre-ordered string uh space complexity is uh this big of endless wall is the size of the stack right we could do this recursively too but i guess iteration works well all right that's it have a great day guys
Verify Preorder Serialization of a Binary Tree
verify-preorder-serialization-of-a-binary-tree
One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`. For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node. Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree. It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer. You may assume that the input format is always valid. * For example, it could never contain two consecutive commas, such as `"1,,3 "`. **Note:** You are not allowed to reconstruct the tree. **Example 1:** **Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" **Output:** true **Example 2:** **Input:** preorder = "1,#" **Output:** false **Example 3:** **Input:** preorder = "9,#,#,1" **Output:** false **Constraints:** * `1 <= preorder.length <= 104` * `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`.
null
String,Stack,Tree,Binary Tree
Medium
null
787
Hello everyone Welcome to my channel here I solve Lead Code problems and today an interesting task is the daily Challenge task number 787 the cheapest flight with no more than k stops average level we are given N cities connected by a certain number of planes we are given an array of flights in which Each element of the array consists of three parts, this is the city of departure, the city of arrival, and also the price, we also have the maximum number of stops that we can make, we need to return the cheapest flight option in which we can make no more than stops, if we cannot get to the destination city by making to stops Let's solve this. This is quite an interesting problem and there is a good technique that can be worked out in this problem. There are two main components. The first is that we need to transform the array, that is, we see that the array consists of such a flat one, we can say structures, that is, Each element of the array is also an array of three elements. In the future, to solve the problem, it is convenient for us that this array should be not just an array of arrays, but a dictionary whose keys would be destinations in Which city can we fly from a certain city for this immediately here I’ll show you that there is a this immediately here I’ll show you that there is a this immediately here I’ll show you that there is a standard technique, that is, what we need, that is, we will have some kind of dictionary. That is, for example, let’s look dictionary. That is, for example, let’s look dictionary. That is, for example, let’s look at so here it’s better to look at so here it’s better to look at so here it’s better to look at example D. That is, from city zero we can fly to city o and to city 2 and each flight costs respectively city ​​about 100 to city 2,500 that is, we city ​​about 100 to city 2,500 that is, we city ​​about 100 to city 2,500 that is, we need to transform our list so that the result is such that our key is city zero and the value is an array And in each there is an array of city and price That is, there will be two tuples like this, the first one will be the city destination price is 100 and also for city 2 the price is 500 That is, this is one key. That is, this means that from city zero we can fly to city 1 and 2, that is, in the future, using such a dictionary, we can easily find the city to which we can get, and then there we will check this along the cheat chain Our first stage Let's write it down right here and then move on to the second stage which I will show graphically, that is, we will create a dictionary pass and define it as Def dict, that is, we will use the default dict function with the value lead creates a dictionary in such a way that if We access the dictionary using a key that is not in the dictionary, then the default value for this type is returned, that is, for the sheet type an empty list is returned, this will simplify the writing a little, then we go through all the elements flights, it consists of three elements are From to and elements, three elements are From to and Price, for example let's write frm - this is Price, for example let's write frm - this is Price, for example let's write frm - this is From to and Price in the list of flights and write pufs with the key From into our dictionary, that is, for each city we write where we can fly to, add append, that is, due to the fact that we used the default dict function, we can immediately call append to the list even if the key may not be in the dictionary, that is, we call and Each element consists of two elements and PR is all the first stage is ready Now we have a dictionary of all flights Let's see graphically what we can do, again for simplicity, let's look at example two, that is what we have zero o and d and the arrows indicate where we can fly, that is, in this way a ra can fly with one stop, what will we do here, we will use the so-called use the so-called use the so-called breadth-first search, that is, what does this mean for us there breadth-first search, that is, what does this mean for us there breadth-first search, that is, what does this mean for us there will be a certain queue, this is a list with a key, that is, with the departure city, that is, by default it is zero, so inside there will also be a tuple of two values, departure city and price, that is, we start from zero and the price is zero since we are in this city and then we add all the cities from which we can fly from this city, that is, we take the current city zero, we can fly to city 1,2 Prices are 100 and 1,2 Prices are 100 and 1,2 Prices are 100 and 500 100, respectively. That is, there are two stages, that is, first of all we need to check that for each city, that is, where we can fly to, this is 1 ID that this city is not a destination city, that is, one is not a destination city, while two are a destination city, so for two we write the result 500, that is, 500 is so far the minimum amount for which we can fly to the city 2 blue ones indicate that we have processed this Now we have processed these two after we have processed that is, we have processed point zero, we have processed it, we remove it from the list at the next stage, updated points d are added to the list with the price for which we can fly to this city, that is, to city one we can fly in 100, to city 2 we can fly in 500, so we reduce k by one, that is, we reduce it like this, that is, zero, that is, we used one transfer, we reduced it, that is, after we made one transfer, we can make another one action for our two elements available action is a flight from city one to city 2, that is, we use city 2 to increase the current distance 100, add the cost of the flight here, too, 100 is also blue. That is, it turns out that now you can fly to city 2 for 200 and also we see that we have city 2 - also blue. That is, it turns out that now you can fly to city 2 for 200 and also we see that we have city 2 - also blue. That is, it turns out that now you can fly to city 2 for 200 and also we see that we have city 2 - this is our result and we see that this result is better than the previous one, that is, we write that the result is now not 500 200 since it is smaller and we add to our final result to not final And in our turn, that is, now there is a city 2 and 200 and for point two we no longer have an option where we can advance and we have everything. We used everything before and got better than 200, that is, it’s like a General solution 200, that is, it’s like a General solution 200, that is, it’s like a General solution Let’s now implement it, that is, what is Let’s now implement it, that is, what is Let’s now implement it, that is, what is needed here, we need a result to begin with, what will we enter? As a result, that is, we need some number that will be the default and which we will try to make minimal. To begin with, we can enter a number such as plus infinity, it is written in Python in this way t from the line inf so not in but inf that is, if we find at least some result, it will be less than infinity. Let's immediately write down the answer as it will look like in the answer. We will return the result if it is unequal to our infinity, otherwise we return mi1, which is what we need next. Next, we need our queue this will be a dictionary in which by default it is located, that is, Our departure city and price, but that is, it is here This is the place, that is, we start from this place, we will also need an additional variable C this is the dictionary Sin - this is a dictionary in which the dictionary Sin - this is a dictionary in which the dictionary Sin - this is a dictionary in which the keys are cities and price - This is the lowest keys are cities and price - This is the lowest keys are cities and price - This is the lowest price to get to this city, we need this to optimize flights to cities and avoid cyclical transitions, that is, roughly speaking, if we have many available moves. That is, for example, in example one, we can get from the zero city to the first one to the second city then again to the zero city, that is, to avoid this, we will initially write down that we can get to the zero city for zero sous, but also after flying to the first city and then to the second we will not fly back to the zero city since the overall result will be worse than the original one which we saved in the variable Sin, that is, by default we write in Sin our original city and the value is zero, that is, we are in NM and the front before it is free, then the main component is the search for width, that is, we work in a loop as long as there is Q and the second condition this K is greater than or equal to zero, that is, externally there will be two nested cycles and in each cycle we go through, as it were, from that is, again, if you look here and here, this is the first layer, the second layer, the third layer, and inside each layer we go through each element of our array Q, that is, in the first layer there is one element in the second layer there will be two elements inside each layer, we reduce also initiate an empty dictionary, an empty list, which we will finally transfer to our main list Q inside, we use the second loop for now, that is, here we check the layer, that is, in the zero layer it is one element, in the first layer there are two elements and we extract the current value consists of two elements. That is, if we sing on how we initiated this is the city, the resource and the price, let's write the resource price like this, so the price is ours Well, let's say price Let it be like this No not Pray Let's Total resources Total extract the element from Q using the pop method now we check that so no here we don't check here we look where we can get that is we check the dictionary pass it consists of two components and PR in the dictionary we pass and check the city CPC now what can we have here that is to begin with Let's look at the price of the city that is the cost of the current city is an increase in its price and the previous amount and now if the city is equal to the city where we need that is that update the result to the result, write the minimum From the current result and the amount of Price, the next thing we need is we need to add the value to a new layer, but only if we either have not been to this city. That is, Sin is empty or our result is better than the previous one. That is, if one of this or the second option is that Pray is less than Sin, that is, there were no soaps, or the current price is better in this case, ra and also add an element to the queue, again two components are this and Price So let's see what the idea is, this is probably the whole solution Let's try run the tests so the tests passed Let's try to send the whole decision so we see that it is efficient in terms of memory time such a solution, and here one of the main keys to an effective solution is the use of changes Syn, that is, without it we would have performed much more unnecessary actions and our decision would have been would not have been accepted on this for today all thanks for your attention full solution as always Look at the link in the description of the video see you tomorrow Bye
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
118
welcome to june's lego challenge today's problem is pascal's triangle given integer num rows we turn the first num rows of pascal's triangle in pascal's triangle each number is the sum of the two numbers directly above it you can see how it looks in real time notice how the ones at the edges left and right are always going to be one it's only the ones in the middle that we care about those are going to just look up and add the first and second one right above it now how do we code that out well the first thing to think is we don't want to really think about this as a triangle it's more like a matrix and what we'll do is for each number in the middle we're going to just look above the list above us and add like starting with let's say this is zero we'll say zero or i say this is one so say one plus one minus zero and here well this one would end but like for instance this one would look at two and two minus one so it would add the ones above one and two and add it together so we don't really don't need to complicate this let's just do it iteratively and what we'll do is first initialize our output to be a list of list with one at top because we know that's our base case now we'll say four let's say row and range of starting at the second all the way to num rows plus one and this will make it a little bit easier to calculate the column now we'll first initialize a list and have one for the left side first now we'll say four column in range of what starting at one all the way to r but we have to subtract one from the row right and we'll add let's see temp append we're going to look above us the very last output thing we added with c plus output minus one c minus one finally at the very end we're going to also add one to enclose it and then make sure to add that to our output now this should work let's return our output after we're finished let's test that out okay so that looks like it's working let's go and submit it and accept it so what's the time complexity it's going to be n squared or num row squared because we have to do this nested for loop i don't really see how that's avoidable you can certainly clean this up to make it look nicer or you can even do it recursively but i really don't think there's any reason to over complicate it just do it straightforward and yeah it looks like it works so alright thanks for watching my channel remember do not trust me i know nothing
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
1,964
Hello everyone welcome, we are going to do video number 28 of my channel. Okay and I suggest you again that I am making a separate playlist. Listen very carefully in which I will have both concepts and questions related to dynamic framing. This playlist contains only questions. Ok so main 1964 it is a very good question, it will seem hard but it will make it easy for you. Ok, the question will become quite easy if you understand it well. Just understand the ok question number. Find D longest valid optical course. Aate position. Ok it is by meta and inverter. What is the question? Okay, look at what is said in the question that you will be given a vector named status, where I means that he has jobs at rectangle position. Okay, what is his height? It is clear to you till now. One you have to remove what they see right what should be your result you have you find D longest of circle course in obstacles true date ok true date you choose other number of obstacles between zero nine inclusive look and second point what you mast institute in D Course You Must Pat D Choose Opticals In D Se Order In Obstacles Ever Give And Se Height S The Optical Immediately Before It Is G So It Is Very Difficult Lines It Is Very Simple Let's Understand It With The Help Of This Example Okay It is very simple given in two questions that it should give you optical, right, zero one to three of each index, okay, so now see what he is saying, like mother, now stand here, okay, now how much optical here. You can erect it will depend on whatever opticals are there nearby, okay, whatever opticals are there nearby, if they are equal to this one, then you can pick them up and put them here, okay, let me see the example, what do you mean? Like let's take mother, here I can put smaller than you, one was one and this is the second one, okay, similarly, if I come to this 3, then I have seen how many elements are there before it, which are the colors one, which is Lee dene equals tu three hai tu hai, which is li dene = 3, so I can include these two also, so I have dene = 3, so I can include these two also, so I have dene = 3, so I can include these two also, so I have put one, I have put tu and these three will put themselves, it will be okay, so here I will include all three. So you are seeing how much you can take here, two is written here, how much you can take is three or look, three is written here, it comes here, okay now look, I am standing here, before that let's see, there is one, which is Lee. Give equal tu hai which is li Give equal tu hai three which is &lt; There is something before it otherwise this poor fellow will go alone, here its length will always be one of the first element because there is nothing behind it, okay If it is clear till now, then you understand how to build it. Okay, so see, let's try to understand how to build your solution. Okay, so right now you are a little scared. Earlier, I told you that mother is late. If you are standing here, then you can do this. You are looking for which are the elements before this which are smaller than this, okay, those which are smaller than this i.e. look, there is okay, those which are smaller than this i.e. look, there is okay, those which are smaller than this i.e. look, there is one, you are okay and the longer all these sequences are found, the better it is, right here? One is small, you are also smaller than three and three itself has become an element, so see, we are getting a long sub sequence, one is three, or if we look at it, if I am lying here, I am standing on you. So, who all are smaller than you? Look on the left side of you. One is small, you are small, three are not small, so we got the lowest one is you, who is the tallest, what is the size of the tallest, three is ok, the answer is 10th. If there was three, then you are paying attention, what is it actually? Actually, there is no longest increasing sequence. Those who have read the longest increasing sequence, they must be understanding what I am saying. Six is okay, all the sequences are okay so let's see. So let us know what it is asking at each point, it is asking us that brother, tell me the longest increasing sub sequence that is going to happen at this point, okay, it is going to end at this point and here it is definitely not strictly increasing here. But he is saying that it can also be equal like see what is the longest increasing sub sequence ending at this point 1 2 its length is 3 right it should be increasing or it should be equal then see 1 2 and 2 are equal. No, it's 1 2 3. If asked from this point, it's 1 2. If we go by this point, it's self-made. Okay, so actually he is go by this point, it's self-made. Okay, so actually he is asking us. Okay, so let's reduce it now, that is, what does it mean that I will write the length of the longest increasing sub-sequence at the point, that will be my answer and it should write the length of the longest increasing sub-sequence at the point, that will be my answer and it should write the length of the longest increasing sub-sequence at the point, that will be my answer and it should also be correct, so let's do one less, we will not recall what we used to do in the sequence, okay then look at the list, first understand people, then this question is also very difficult. It will be made easily, that is why I said that it is not hard, it is easy, if you know it well, then take mother in it. To understand, I have taken this example and to make alloys from bottom up, you will remember those who read. If you have n't read then there is no problem, I will tell you what we used to do to make it from the bottom, we used to take a simple waiter, okay and its length is taken, how much is one, two, three, zero, one, two, three, four, five, okay, it is 14. No because look, now we need sub sequence, one itself is also a subsequence, so what is its length, one is also 14, what is itself a subsequence, 46, what is sub sequence, 42 is itself a subsequence, so brother, one can see the length. Now how do we find the longest, we will see how to find this longest, so what I did in the beginning is, I took a vector named T, okay and I am saying that the length of all is one only, okay and define the state. Let's take that brother, bottom, remember what should I say, if the state is defined, then half the solution is yours. Do you know what will happen brother, longest increasing sub sequence ending comes index, I ok, longest increasing sub sequence ending comes ok, so let's see its meaning. What is it, I have understood till now look pay attention, I started the index here, okay, the index has come, no, sorry, the index has come here, I have to file for this, okay, so what will I do, I will see that brother, this All the elements before the rectangle element What is there in IPL Here all the elements before it Which one is smaller than this So there is no element before it Right Where is there any element before it Right Brother i.e. What does it is there any element before it Right Brother i.e. What does it is there any element before it Right Brother i.e. What does it mean that the longest increasing sequence ending at zero index is billed to be one only and obviously there will be only one, so long, I can see there is nothing before it, so the answer is one, so the length is of zero. So there will be only one, we know it 100% zero. So there will be only one, we know it 100% zero. So there will be only one, we know it 100% okay, I came here, now I will see what is right, brother, there is four in Namas here, okay and how many elements are visible before four, whatever elements are visible. I have seen who all are there who are smaller than this. Okay, so what will I do? Which index am I on now? I am currently on one eight index, so I start K from zero. I start G from zero. Okay, so that means with this force, first I will go to all the elements one by one, so first I came to one, it was 0. I am asking, brother, I am asking the element with zero thindex, are you the small one, the white one? The element will say yes because I am one take it as 4, what does it mean, one take it 4s, so what happens that increasing can be formed, only after one, four will come, increasing can be formed, so I will say one, no brother. One, tell me one thing about you and what was the longest increasing sequence, then zero will say coldly that brother, the one that ended in me was the longest seeds, its length was one, okay and the four which is on the index one. It is sitting, it can be appended on this because this is one, so it is smaller than four, so brother, on this and the next one is on zero and which was the longest subsequence itself, this was one, okay him. But you can append on one why because brother 03 What is the longest requins on you will say if there is one, then what will happen, you will become okay and already what is there in T of one, if one is okay then one is big or one and or Is this T of I bigger or where is K now? There is a right on it can be added because it is smaller than bigger then what will happen is this T what is my one and DJ plus one what will you become If you want to make it bigger among the two, then I will update it, okay, you may be feeling a little confused right now, go ahead, let's expand the diary further and it will be clear, okay, I had started it. Let's go from 0 till i, ok, it will continue till zero, after that it will become equal to i, ok, so now look at t of i, what has happened to me, understand that carefully, the value of t of one is tu, meaning what happened that. The length of the longest increasing sub sequence ending at index number one is tu and that is also correct. Who is that? One comma four is increasing is also right and its length is tu so 10. Our answer here is tu. Now my index is here right. My index is here, now what I said again is that I will start from K and where is the index on Tu, Na is on A, whatever is on 2, I will compare that the element on Jeth is correct and the element on which is If there is six then is one small then six can be appended to the longest sequence ending at one. Right then I will ask on one that brother, what are your long sessions, then he will say, mine is one, then append one more to it. You will be done and there is already one value here so I can update it, you have got a big one, okay, it's great, now I am here, okay, is this on the small one, so I will ask the one, brother, on you. What is the longest increasing subsequence ending, brother will say, it ends in me, it is okay and maybe right, if you make it plus one three then it cannot flood further and because &lt; has to be continued till i only, now the value of tuffy &lt; has to be continued till i only, now the value of tuffy &lt; has to be continued till i only, now the value of tuffy is 3, this means What happened is that there must have been many sub-sequences ending at the second index, many sub-sequences ending at the second index, many sub-sequences ending at the second index, but which is the largest increasing sub- but which is the largest increasing sub- but which is the largest increasing sub- sequence, it is three in length and who it is, you must have seen it too, 1/46, okay, who it is, you must have seen it too, 1/46, okay, who it is, you must have seen it too, 1/46, okay, who would know this very well, if you If you want then I will make a separate video on Lies. Okay on DP. Now let's move ahead. Okay, it will start from here and I will compare. Okay, then I will compare. If the winner is okay, then I will ask brother, the one that will end on victory and first. So I will check that the element on K is okay so increasing sub sequence can be formed then you will go to a so this and by the way you are a big value so I have cated it and done okay now this is further flooded give four li Tu again nahi banega look at the value of t of three, you are fine, what does it mean that the longest allen ending in the third index can only be two and you see the right thing is by finding the longest in the longest increasing vegetable. Look, these two which are on index number three are fine, they are coming to an end, fine and our answer is also you. Look, there is a 2 here, that is, we are making it absolutely correct. Okay, if you see, it must have been understood to say similar. When I will proceed here, okay, then come again, I will start from here. Whom is I pointing to? What is the fourth index? Is one &lt; 3, is it one &lt; 3, is it one &lt; 3, is it smaller than the element one? Yes, it is smaller than one, then it is three, which means it can create the longest increasing subjects. So I will look at the length of the longest increasing sub sequence ending on K. It is one. I can add one to it. This three which is one element can be added. Okay, so I will add this, so how much will it be, then it will be This one is small, so I will update it here. Okay, then when the element came here, what is three, this is messed up. 4 &lt; 3 is not there, this is also not six, give 4 &lt; 3 is not there, this is also not six, give 4 &lt; 3 is not there, this is also not six, give 3, it is not here, pay attention, look here. But when it comes to 2 &lt; 3, yes, then what do I do? comes to 2 &lt; 3, yes, then what do I do? comes to 2 &lt; 3, yes, then what do I do? Jeth and which is the longest ending on this index, then the length of the longest ending on this index was through, if we convert it to three, then the length will become three. It is clear till now, it will come till this point, okay, now look at one thing, the one ending on this index is going to end on the fourth index, the length of the longest increasing sequence is three, I am saying three and that is correct, it will be only three, see this one, you There is no other three, there is no similar index number five, now find out ok guys, its code is very simple, isn't it, see how simple it will be, if i is doing its move, enter i = 0, give n i move, enter i = 0, give n i move, enter i = 0, give n i plus. Plus ok, after that what I was saying is starting from 4j = 0 k plus will be plus starting from 4j = 0 k plus will be plus starting from 4j = 0 k plus will be plus ok and when was I doing when the name off k if the name was getting smaller clearly but remember this time not smaller. Equal Tu Bhi Chalega is given in the question that Equal Tu Bhi Chalega is ok, so what was I doing, I was updating the T of I, it may be included, it may have been cleared till now and what should I do, lastly this T is battery. This is my answer, please send us the result only, then it actually passes or not, okay, after that we will go to optimal, so let's submit it from the court and see, then you are able to pass, the latest cases, okay, and what I said. That I will take a vector of and t, okay, let's keep the length one because each element itself is a sub sequence, its length is one, okay, now start updating, you, after what I said that you we We will go to each element from zero to i, whichever element is smaller or equal, they can be made into a longest increasing vegetable. Okay, F is the name equal to the number of i. Okay, so what will I say, what will be T and I. The maximum of T5 which will be already value will be Rakhi means the value which will be on LIS Aate Index I is already either that or the maximum which I will get now means I will ask K that brother, what is the maximum which will end on you. DJ, why did we add plus one in that now because the vein of IB can now be included, it is okay to return T and here also there will be LISS, let's try it later and it remains to be seen but it is okay but let us go to the optimal story. We will have to do something so that it becomes optimal. Abstract content is very high. Okay, so let's see how we can optimize it. Now look at the optimal solution. First understand its essence. Okay, how will it come to mind that the meaning should be taken forward with this approach. Okay, so I have taken an example. Look at this example carefully. Here, if I tell you to find the longest increasing sub- I tell you to find the longest increasing sub- I tell you to find the longest increasing sub- sequence and show it, then you must be seeing that one is greater than one, four is greater than four, six is greater than four, okay after that. It is visible that you are bigger than 11. You are bigger than three. Five is visible to you. Okay, you must be seeing fight, so just remove this 5. Okay, now let's assume that one is ok. Now let's assume that there is an element. Okay, okay now I have to find out what is the longest common longest increasing sequence ending in this fifth index, exactly which contenders are visible, you are seeing these two contenders, one is visible. Look, it is visible that brother in which five will be added, pay attention to one thing, five cannot be added here right because it will not be the longest increasing sequence. Okay I don't know the difference from which person is studying each sub sequence. There is a difference from the last one because when I had to bring five, what did I see? After every sub sequence, I went and saw how the last one is, here the last one was six, give a greater five, that is why five cannot be appended here. Right and here whenever the subsequence is near, then see here yesterday the last band of this subsequence is the last band which is smaller than five isn't it smaller than five date this three is okay so hence it will be appended to this five and one more We will get the bigger one, okay till now it is clear, but whom did I prefer, brother, the one whose last element is shorter, okay, so friend, what information do I need the information that brother takes mother, someone 's length was three, okay, one is this. Okay whose ending element is the smallest ending element is three Okay so this time know what I will do Length used to be length but now what is more important to me is that I have to know the length of the longest increasing sequence but what is its last element. It means here, was it six or three, I mean, I will prefer the smallest one. Okay, so tell me what will happen this time, define the state, see how I will do it, what was the sub signal, I plus one, zero plus one, I am saying and Subsequence means its maximum is i plus one okay its length is i plus one and know the ending element what is that is When I came to know about retirement from, I thought that if I had told you directly that brother, define this state, then you would not have understood how this thing would have come in our mind. From this example, it would have been clear to you that brother, it should be even. I am fine, let's say its length is also 3, first of all there are three but which is the one whose ending element is the smallest, so I want the information of the ending element, so here the length of i = length here the length of i = length here the length of i = length is y+1 and the ending element is x, is y+1 and the ending element is x, is y+1 and the ending element is x, okay If yes, then what will be the benefit of it, let's see. Okay, so to understand this, let's take an example. Okay, we have taken this example and right now our vector of aliens is empty because right now we have not included any India in it, okay then more. What I mean by fitting you again is that i + 1 is the length of the sub sequence and what is the i + 1 is the length of the sub sequence and what is the i + 1 is the length of the sub sequence and what is the ending element of the sub sequence. Okay, what is the ending element so and you remember here when I told you that ending. Look at the element, here there is six, here there is three, okay, so now who is smaller is three and who is bigger than 5, okay, so I had placed 5 here, okay and one more thing, please note that brother, there can be three here also. It was because it is given in the question that it can be equal, if you cycle is fine then it can be three, it can also be equal, like mother takes, now I have come and am standing here, okay, so what would I like, I would like all such sequences. Whose end is the ending element whose indicative element is less than one or equal to one, you are fine and due to the material, I will see more brother which is the ending element which is equal to one or either take, okay then see, right now my whole is empty. Right, what will I do, now look at where I am, is it at zero? Okay, so what will I do now? Simply tell me here, brother, there will be one here, now understand what is the meaning of one here, okay first the brother, then his. The index will be zero, okay and this one, you know what happened brother, the length of all this sequence is one, what is the meaning of zero plus one and its ending element is one, which was this banda, you are the sequence and what is simple. X + 1i + 1 and its clear is clear and one thing is not paying this to the forest on which index It happens that i + 1 happens that i + 1 happens that i + 1 is its length, zero plus one is its length i.e. one and its ending element is one. i.e. one and its ending element is one. i.e. one and its ending element is one. Okay, so I also write here in the result, which index is it brother? Here the index is kept at zero element. So what will I do here? What will be the result of half of the index? This is zero, neither is it zero plus one. It will be right and 0 means again I am telling that brother 0 + 1 is its length, it is the index 0 + 1 is its length, it is the index 0 + 1 is its length, it is the index of sub sequence and sending helmet is one, okay let's go okay don't take tension okay further I came here but okay now If it is a four, then first of all I search on the link that which brother is the brother, there can be many sub-sequences, I have to can be many sub-sequences, I have to can be many sub-sequences, I have to find the one who can take four or equal, you are right and it should be bigger too, that is right, so I don't want that. The one ending element is needed, the sub sequence is needed whose end force is equal, either it is smaller, it is ok, then who is that brother, right now I see only one guy in my life who is just smaller than four, give equal, you are right. Okay, so four can be here, after this, I will make four here and it will be appended here, next is one, next index is okay till now it is clear, now think for yourself which one. This answer has come on the index. One think this answer has come. Okay, so what is the length. The length of all this sequence is two. So, this index that has come here, make it one, that is, it will go to two, okay here? It is clear till now, go ahead, ok, now look, we will do the same thing again, which is the subsequence which is less than 6 and either is equal, then there is also one, there is a subsequence whose ending element is one and one more subsequence is equal to two. But think about which one you will choose. Whom will you choose? This is such a subsequence, what is its length? 1 + 1 2. All these will be what is its length? 1 + 1 2. All these will be what is its length? 1 + 1 2. All these will be secret. Okay, so what will you do? You will append this. Okay, if you band it, then six will come here. Okay, and which index is A? Here on the 2nd index the fruit will come, on the index that band will be three, that is the length of the sub sequence and what is the length of that sub sequence, okay and its last band is six, that is what is written here, it is okay and who would have written it here? Brother, last Sunday, which index is it, that is, what will be its height, how much will be the length from all the coins, it will be 3, it will be 2 + 3, so here I have written three, it is 3, it will be 2 + 3, so here I have written three, it is clear till now, look at this very important part now. Okay, what will I do, I want such an element, I want such a sequence whose ending element is less or equal, you are ok, then let's see, is one, that is, yes one, is four, that is not four, if not, four is bigger. So, you can't take that one, you can take one, okay, now pay attention to one thing, this is coming from Jehovah every time, okay, so you can hit simple binary search, either you will do it tomorrow or what will you do, now what I wanted to find is that you Se just le den or equal tu or aisa maa ke chalo pay attention to index one already I have an element four, what does it mean index hua means what is the length of the sequence is two and what is the ending element is kar and that too You must be seeing that whose ending element is going to be tu, its length is also going to be two because that is its index one, right now, it is an obvious thing, what did I tell you that which one will I choose, if it is shorter then will you choose four or If you become something, then brother, if something happens to you, then on index 1, I will not give you the pulse, I will remove it, okay, what did I do, it came here, neither, I have given you the pulse, it is okay here, because the one which is smaller, I will prefer this one in the future. It will be good for me, the index is clear till here, how many which index did I get, index got one, okay, meaning what is the length, one plus one is you, so here I have given you, okay till here, it is clear, now I have come. Mine came here ok, now let's see, take out the element just bigger than three of three, okay now if you drive this one, it will be more clear, okay take out the element bigger than three, 10, that is, who is bound on you three to 10 minutes. Brother six hai to IDEX ke a jaayega tu aaya hoga ok what does it mean that IDEX tu aaya but already a banda is present ok what does it mean that there is a sub sequence whose length is na to tu plus one i.e. 3 This also means its length is 3, which means one comma, 2, 3. Which one will you choose, so I removed it and gave three pulses. The shorter you choose, the better it is, right for the future, this is what I understood, this was the most important part, so IDEX, you came. Tha na to tu plus one date is three the answer is ok and here who will be those three guys this one and you and three there is nothing to do with 12 just append five in the last two thoughts it is ok and index Will A automatically go to three A, meaning what happened brother, this sub sequence has landed, okay and I know which is the sub sequence, the ending is on five and before that which will be 3, you will be and one will be. How will be the code of one two three five, it will be very similar to that, okay, clarification, what is the meaning of this equal two x, is it telling that I plus one is the sub sequence and its ending element is He will understand that you have to write the story point. Okay, what did I say that I will take the vector of Rajasthan and its statement has told you what is the meaning of Aliens of I = told you what is the meaning of Aliens of I = I will move forward on my own sequel, you are zero I &lt; Okay, I will take out IDEX, OK, I will take out IDEX, if I come to know that IDEX, which is ideal, is of LIS and I have not found this equal, I have not found anyone just all of them. All the elements are small, so what did I say, just push back, no, all of them are small, okay, and if it is not so, I have got it, then what do I do, I was giving it to the guy in DS. Right, the current one will return the off cycles, the result is ok, so actually the state was the face part and it got cleared and you have dried it and done it well, the biggest thing was to drive this driving. If you have done this, then you have understood the questions. Okay, I will find this and a vector of eight results. I will find the bigger element. Okay, you can also write your binary search. For this, the inter file is from the current substerl. It is okay and we will mine it to get the index because upper close gives you a painter ok add optical psycho in IDEX na ok and what we used to put in the result puts the length of sequence in the result I put my history plus one ok
Find the Longest Valid Obstacle Course at Each Position
find-interview-candidates
You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle. For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that: * You choose any number of obstacles between `0` and `i` **inclusive**. * You must include the `ith` obstacle in the course. * You must put the chosen obstacles in the **same order** as they appear in `obstacles`. * Every obstacle (except the first) is **taller** than or the **same height** as the obstacle immediately before it. Return _an array_ `ans` _of length_ `n`, _where_ `ans[i]` _is the length of the **longest obstacle course** for index_ `i` _as described above_. **Example 1:** **Input:** obstacles = \[1,2,3,2\] **Output:** \[1,2,3,3\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[1\], \[1\] has length 1. - i = 1: \[1,2\], \[1,2\] has length 2. - i = 2: \[1,2,3\], \[1,2,3\] has length 3. - i = 3: \[1,2,3,2\], \[1,2,2\] has length 3. **Example 2:** **Input:** obstacles = \[2,2,1\] **Output:** \[1,2,1\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[2\], \[2\] has length 1. - i = 1: \[2,2\], \[2,2\] has length 2. - i = 2: \[2,2,1\], \[1\] has length 1. **Example 3:** **Input:** obstacles = \[3,1,5,6,4,2\] **Output:** \[1,1,2,3,2,2\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[3\], \[3\] has length 1. - i = 1: \[3,1\], \[1\] has length 1. - i = 2: \[3,1,5\], \[3,5\] has length 2. \[1,5\] is also valid. - i = 3: \[3,1,5,6\], \[3,5,6\] has length 3. \[1,5,6\] is also valid. - i = 4: \[3,1,5,6,4\], \[3,4\] has length 2. \[1,4\] is also valid. - i = 5: \[3,1,5,6,4,2\], \[1,2\] has length 2. **Constraints:** * `n == obstacles.length` * `1 <= n <= 105` * `1 <= obstacles[i] <= 107`
null
Database
Medium
null
350
code three five zero 350 intersection of two arrays two all right so there's another version for this one we've already done it go back and check into my videos um so given two integers arrays nums one and nums to return an array of their intersection each element in the result must appear as many times as it shows in both arrays and you must return the results in any order so this one will include duplicates so we're not going to be using hash set which eliminates duplicates and so if you're given like for instance array number one two one and then Arena two then you're gonna end up with the output should be two okay let's get into it so basically the first thing I'm gonna do we're going to start by sorting the arrays and then the next thing we're just gonna create these two pointers pointer I and J and another thing this we're gonna create our list which will be storing the um it's gonna be storing the elements uh which are basically like the intercepted elements the ones which are in the intersection okay and then yes so the here uh what's gonna What's Happening Here is that we are taking the pointer and we are checking if it's less than the length of the first array and the pointer J as well checking if it's less than um the second Arena too so basically which I can point our I less than num1 dot length and pointer J less than num2 dot length so if this condition is met we're gonna keep on repeating the process which is inside our while loop and then inside here the while loop we are comparing the two elements this is where we're basically checking if the elements there is any sort of intersection so if pointer num at index pointer I is equal to num2 at index Point J then we're going to add that element which is a basic instant it's exists in each of those arrays basically that's what it means so we're gonna just add it there and then after we do that we're gonna increment basically both pointers J and then yeah uh we're gonna go back here and then we're gonna do the same thing check if it's the same else if it's not if this cont is complete this condition fails if the address no intersection then we're gonna check we're gonna say nums one quarter I if it's less than num 2.0 J 2.0 J 2.0 J then we're gonna increment I else we're going to increment J and here's the front part guys here we're just taking the inter we are basically going to be uh building our intersection basically we're gonna put all the elements which are common in both arrays so we just create this for Loop for each Loop and then we are incrementing at K and telling me that the element here to here and we'll be turning it at the end and let's run and flip downwards foreign there we go I will see you guys in the next video please don't forget to subscribe
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
641
hello everyone so in this video let us talk about the problem from lead code it's a medium problem the problem name is design a circular DQ so you actually have to design a double ended queue that is a DQ you have to implement these functions so if you know about Q then it's just an extended version of a queue in queue we'll insert from one end and take out from another end if I just draw it out so accused data structure in which you can assume that this is a pipe you insert elements on the very back okay and you can only insert like pop it out or take it out from the very start so let's say if you insert one element that is this so that let's say the element is one then you can only insert the next element after it so let's say two then three so that's a queue okay like whenever you like to go to buy something from a shop there's a queue so you like you get in the back and you only start taking off another very friend but that DQ is a special type of queue in which you can like you can insert from the back or pop from the black as well as you can insert from the front and pop on the front so you can do all of these operations on a double ended queue so that is called a DQ this is d we have to implement that and so the different functions regarding DQ is that you can insert pop on back front you can find out the size whether it is empty or not but there is a hard limit in this DQ that it should be only consisting of key elements the total elements at any moment of time in the queue should be less than equal to K that's over the thing now there are different function let's say insert front of the DQ so if it can be inserted such that the total end should not be greater than k then you can insert the element as well as return true but if it is not possible to insert in the DQ then return false similarly inserted the last delete from the like back by deleting it means that like removing or popping out so delete from the front delete from the end if you are able to read it or you can check it out if there are some elements in the DQ at least then only you can remove what elements if you can remove from the front or back it will return true as return false then get front will tell you what is the front element the back element get back and if there is no front to back element return minus one similarly for is empty we'll check that whether the whole DQ is empty and is full means that whether the 2 is full DQ is full that is it the size of that is equal to K so it's pretty simple you can directly use so C plus actually gives you a little structure that is DQ directly uh out of the box so you can directly use D you don't have to implement that you can also actually use a vector to implement a queue like DQ as well but because we have DQ that tree out of the box from like provided by C plus we can directly use that so what we have done that we moved under the board because nothing much is here to explain as such the code will be sufficient enough so what we can do is that we have this DQ that we have implemented in a global uh case you can assume at Global State and this is a DQ and the capacity that is cap that will be stored what is the maximum capacity I can be stored inside the DQ so while we're initializing this details initialize in the global state but we have to initialize this like uh what is the size of the QV or DQ actually up to you so that will be stored here now let us go down to each individual function so insert front Okay so we can only insert in the front of the DQ when like until they are less than K elements if it is more than K elements we cannot so we should check that the size of the queue should be less than the maximum capacity Which is less than the maximum capacity then only we can add the like the element so we will push front that's the function we will be using with DQ if you want to push in the front of the DQ so push front Okay we have to insert this value and return true because we have post like it is possible or we have inserted a value in the front of your EQ so you don't Drew has written false because we are not similarly for the last this is push back so push front and push back are the functions for inserting in the front and back of the DQ Point uh down so let's move it down so at last the next function is delete front so for deleting out we have to ensure that there should be some element inside the DQ so the DQ side should be greater than equal to zero greater than zero actually not greater than equal greater than zero so we'll just check that the size object should be greater than zero then only we'll go outside this function pop so we have to pop out or delete out element from the front so pop front we delete the front element from the DQ if it is possible to read will it run true as it does false and also delete out the like the front element as is the back so pop front and popper back we return the black will delete the front and the back elements similarly if we'll move on to now we have to get the elements okay so when we want to get the elements because when we want to get the front element in the same thing we have to just check that we can only get the elements if there are actually some elements inside the DQ so EQ dot size will check that it should be having some elements so decoded front will get the first element and if it is not present then it will minus one then similarly DQ dot back will give you the back element if it is not present related minus one now the last two functions are checking out whether the size is you know like it is empty or not so if the size of the DQ is added like when we are calling this function is zero then it will return true that it is empty so if the size is zero which means that this is a Boolean expression it will return true if uh it is an empty uh DQ is false similarly if it is full the size of the DQ should be equal to the capacity that is the maximum capacity that is equal to K if that is true then answer is that it is full as it is not full so these are the Boolean Expressions that will run true or false uh like the code we just have to implement these functions and the overall will be handled by the lead code only so uh that's our problem the code part of it and you're watching video till the end if you have any doubts you can imagine in the comment box I will see you in the next one lucky coding and bye
Design Circular Deque
design-circular-deque
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean insertLast()` Adds an item at the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean deleteFront()` Deletes an item from the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean deleteLast()` Deletes an item from the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `int getFront()` Returns the front item from the Deque. Returns `-1` if the deque is empty. * `int getRear()` Returns the last item from Deque. Returns `-1` if the deque is empty. * `boolean isEmpty()` Returns `true` if the deque is empty, or `false` otherwise. * `boolean isFull()` Returns `true` if the deque is full, or `false` otherwise. **Example 1:** **Input** \[ "MyCircularDeque ", "insertLast ", "insertLast ", "insertFront ", "insertFront ", "getRear ", "isFull ", "deleteLast ", "insertFront ", "getFront "\] \[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, true, true, true, false, 2, true, true, true, 4\] **Explanation** MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 **Constraints:** * `1 <= k <= 1000` * `0 <= value <= 1000` * At most `2000` calls will be made to `insertFront`, `insertLast`, `deleteFront`, `deleteLast`, `getFront`, `getRear`, `isEmpty`, `isFull`.
null
null
Medium
null
322
In this video we will compare Quoy Jumper Actions and Conference the main issue is difference and I had asked another question which was named Targets we submit, he goes to 100 in broken and got many more so we recommend him that he If the information is different from how then it is first of all if I do not speak from the problem of Finance Corporation of India then I do special and tell how to solve it in a different way from our sugar syrup, okay see like the festival owner had read about that inside two three And the site issue requested that you have ₹ 2 points, this is requested that you have ₹ 2 points, this is requested that you have ₹ 2 points, this is from the point and then it is the same point, so and you had to target the intake, along with the payment, three points on Meena Vikas Marg, if you can understand 45 one in coin change combination. You had to tell me how many combinations are there through which it can be clearly seen and Congress is telling me how many are there through which how many majors go into it, who can be made seventh, and someone else in Congress has Edison and to find the answer, whom should we talk about in inches and years? So you can use any point two or three or four times because each point has its own cement supply, okay so as I tell you the combination, it has to be roasted at 231 minutes, the special thing in this is the combination is 12345 but mentha permit in this is 2515. Only one will come and two will be three then 232 and if it will break then there are five main combinations but it is okay and what is one more special thing, the second seal is broken, another question will come, sunset, this is very beautiful, it has this If you have to put Mukesh, then we will compare this also. Now let us see the reformation in it. So, look at my questions and how I did it from here and see how my strategy worked in the comments on the time of Congress and contesting from this. First I am troubling you. Is 2012 384 506 Make it a big size Now I am calling permission here I told and we have these How many conditions are there to present 24 Press high This is 100000 subscribe to target It's just like rubber This idea on four To introduce the conditioner, how much has I earned with Sakoon Saath, first I am putting a crush, okay, there will be an example in front of you, then I will change something, I will show how the producer has become fair in the company, so the laddus are bursting. In this we happen that there is a way to do zero at the ends, okay, what is Africa, don't do anything at all, now I will recover my Vivek Oberoi, when the routine and targets, we take the video of the subject first, please come and see it, then it is half It will take a lot of hard work, there is a way to do it from zero, that way is neither get anything nor give anything, now I am the one who treats 235 time 12345, I have to close on the forest and do it, I swear by the forest, I swear by the oath. And there is no doubt at 1 o'clock if you don't want to take anyone then you will be able to drink if you pay 12% of the dues then you will know 12% of the dues then you will know 12% of the dues then you will know them but this is not a way so I am here in Delhi typing is fine see here Here is any study about China's forest. Now let's talk about you. Okay, because let's talk, here I have given two points, here I will hit tubeless. Okay, Monday, the first loop, I have given two boys, Maya, I have reached here to do it from zero. The method is Akshar, this is our use, this is the method or 50 grams of society will send this gram, which I had researched in depth in the video, so whenever I do it here, it will seem prime, then the rest has to be narrated, if I can go from here or And I can go and you can go and I came and I can go, I stay away from the intake, I don't know the height, monotony, brightness setting are from him, then in the rest, the milk is filled with the total of going, so now it seems as if I will see it from someone's place. Have to pay money and can't think that I have 10 destination is that when zero is okay then if his eyes bowed Scars K 235 If I had paid with two then there are more days on my website Seventh after 3 to 4 minutes After 5 minutes in the day, there are 5 more days, there are some ways to pay you by letter, along with the scientists, there are those ways and looking at five, no, there are those ways, so if there were three ways, two ways here and three ways, yes then 10 to sure. There are so many ways to do totals, till today, but till now, this is the only work. Time tried to do it on two, so brother, why are you, but I had to go to Rs. 10, is the payment clear from you to two, can I do it in the second cricket test? Can't do it in the past because they are big meat, okay or write it down once for repayment - York Times write it down once for repayment - York Times write it down once for repayment - York Times - 30 days will be left, now there is a - 30 days will be left, now there is a - 30 days will be left, now there is a way to use zero, something or both people - Sangh work happens, nothing people so people - Sangh work happens, nothing people so people - Sangh work happens, nothing people so I set And you will give me some road and I will also go. If there is no way then there is only one way to go to Shirdi. If I don't know then I went here where lizards grow and hurt. Friends, please understand that we are in very detail. Subscribe I will not leave every leadership soon. Now I will request for free curtain from here, I am 2 - My one will curtain from here, I am 2 - My one will curtain from here, I am 2 - My one will reach, the coach of the team will neither definitely reach 500 or can not, now there is no arrangement for 10, what is visible is the relation of going away from zero, so even for doing ₹3 There will be relation of going away from zero, so even for doing ₹3 There will be relation of going away from zero, so even for doing ₹3 There will be a way doctor find a way could block the way it went up just passes I three went behind him one time 201 this is my tablet you are okay now let's talk about the flower this way or we set why when I talk Network above too - - - - - You don't know the time to go from Network above too - - - - - You don't know the time to go from Network above too - - - - - You don't know the time to go from here to two, but if you go from here then it has become an example. Okay, now you have to go from zero, there is a way to go from zero, there is , there a way to go from zero, there is , there a way to go from zero, there is , there is no one else in the world, even on 24. The way to do is if I am here then it reaches there and bow down subscribe this is two and this is nothing so that's all that is left now why did we have the bodies connected above ₹5 let's talk about doing 5 but sunshine more ₹5 let's talk about doing 5 but sunshine more ₹5 let's talk about doing 5 but sunshine more - my and Punches can be made at your place, - my and Punches can be made at your place, - my and Punches can be made at your place, go to your friend's room, take away Tuesday, take 50 zero pieces, now there is a way to go from zero to seats, don't friends, don't see this method, there is also a way to go to 30, they have a technique. 25 came out to see the 25 came out to see the 25 came out to see the settings out of these are dot right yes then 's 's 's team was paid for, used rosary so it is ₹ 2, its fragrance method is dot then so it is ₹ 2, its fragrance method is dot then so it is ₹ 2, its fragrance method is dot then M.Com M.Com M.Com Bluetooth was old in its p If we stayed and did it even with 5, then we reached here, there is a way to do it, those two track records are fixed OnePlus One Plus fixed OnePlus One Plus fixed OnePlus One Plus One layer till here, do you have any problem, very good thing, at working in Bandra. If we can go past six and seven, then from 6, if we use Bandha, only the trick will reach 35, we will reach 1, there is no way to get one, there is a way to go right up, there is a way to dot, the way to see reel 4 is dot. There are methods of amount, okay brother, let us also see 200 here and three, then here and introduced with 5, okay here, then the way to get four is 222 will ask, got 222, the way to see the foot game is dot re. One Jani is about returning home and 511 other pujas are nothing but on Lord Krishna, it is just an exam. If you have any problem, then what is the return edition? It is a very good thing for whom. Your mind is like this, basically this question is not a problem. Want to do our chili coriander and fennel, how is it different from the combination, seven people have to die, five wickets have to be taken, Vinod has to be done four feet and 500 have to be made smooth and thick paste, see that part, there are three ways to see 24. There is a way and there is a way to do ₹2 see 24. There is a way and there is a way to do ₹2 see 24. There is a way and there is a way to do ₹2 so let's stop 5 Let's see here also 12 reached here from three reached here from 25 reached here from two plus one girl three five plus one if these three together daughter Daughter and want cotton 323 452 323 Is this our way of presenting 17 or not? Used to end 235. Raghu came in Boss. Click on continue here. Yasmin is Maya. Now we will see Islam is the combination. It is necessary to come to Congress. 2525 and the second one is this, we will do something with it and remain very simple, what we did this time is that we took a pocket of 253 pieces of ceramic and the rest of the payment, what will we do now after breaking it whole, we will like it, we will believe it, we will fry it whole. Let 's take it and mute it, let's see how it 's take it and mute it, let's see how it 's take it and mute it, let's see how it is okay, so see, this time we are making it again for the combination, Solkar and you have to see how it is different from this, how different it is, this is what we have to relax at this time, so This channel, after that you will have the extract layer, it is necessary to understand the questions, a little mention that the gang, the previous song again, first we are taking two cash in the whole, first soon in Mukesh, like if someone life was even taken, then come. Let's see, this time first we will make whole Bittu, then we will mix the whole and then we will type in the whole. So today I will be in front of you and see. Now first we are submitting the whole Bittu Pimples Infections 152. If you don't understand then you can use it. So one or two can be used on this seat, he reached here from there, if nothing is found, he can use it, if he brings here one method, adulteration, daughter, friends can hit on five, but nothing will be found, used 62. So here is that one method found, it adapted 2172 uses, this one is not found, all of the two have been done, now it has been told that the team does it, I have to return to this, how many ways are there to do this using only two. By doing this, we can do it only on the even ones, their methods are then pick two multiple times, now I will put three chords, so that is how many ways are there using two and three. Okay, now it is important to note that any shopkeeper is free. If he comes then he will follow them only then now we cricketer Shankar Nath will stick behind him, if someone sticks then it is about getting better or the other can be big, always taking a dip and putting it towards the back, so he will go here along with the old answer and I will go here asmani. Will be adopted from here Maya is the way to look at it, so one way is that you try this note 4, used the free on four, so we reached here it got 25 views, so we reached here A, I am in a very shock, there is a You have found the method, continuously dot 238. If ever the day wakes up on the seats, then this week is fine, it is after tuition, till now, why was the stubbornness in studying carefully, among them, I broke down, then there is something else behind them, on one side, okay, now let's see once again. Let's see, for this, I found one method from here, so it became two, Dot fell here and there was fell here and there was fell here and there was that now we will use it together, so on our four, I found one method, daughter to 232 First soil from there very quickly behind so now we will use it so from here to here and pronounce it, if you put type here then one more method and you got dot pipe if you put it in this area then you will get something, if you put dotter on seven then you get one here. First of all, if you see 15 or two apk files from Google Play Services, then it is fine because of that, but if you see a lot of 225 in all, then I install it here, just below it, I am solving it again. Only less but it can fit in the public's mind. It's okay for this thing, the way to zero is now just very beautiful, one but 0777 is over, afternoon is all mine, found a way, dot 235, can't escape, now here, I click on zero 12345 63 but two, now I went from here to three, found a way to message and 35, can't use it, even at 4, grandma can't understand. If I used two, then I went here, found a way, which dot. When I asked 13 questions, I went here and found something, and look at the fiber that reached you, these are not to be but and so on, now see only the umpire will come to that test, if you used two, then reached here, found one method, it is specific, and if the team is used, then I am here. Reached a way and found which is not see that your afternoon here in juice was tooth on free and now you used a two and three then ok find and two cigarette happened then you broke down here previous which is Mukesh doing this back Two to Z can say something and if you are riding it on your leave, then if up to three are born, then it can also be okay that what will happen to you and Congress in this city, in the first cycle of two, all the two are blackened, whereas if it goes then the one who Old decommissioned dog, if ever I tie a knot on it 2328, white bangles and anklets and will get it in daughter line, there is no need for recommendation, here we will do the training, done on six, got a way which is not two six But that's three two one way and Mila dot C three and five were imprisoned but will do two so from here three ways were found that if 320 MP3 was used then one more that if 320 MP3 was used then one more that if 320 MP3 was used then one more Mila dot s 5 use and Mila where dot Print bottom you had done now the school had used that but you have that while using subscribe in and from hr only that targets we true submit how Shimla problem is the young man riding in it has got Aadhaar 235 you are asked Is there any good subject of gesture which is equal to Samsad I can use these anyone twice that Congress Now who are you in this Internet up to Kumar Vishwas is not subscribed that passenger train is there will not come twice not on the meeting If it comes then I will make 2nd for it and today mark it may take time, let's see, this Singh is used in it, I will request all the videos that son please first watch a program subjective detail video of this, for this you will find description search comparison below. To do inside and to do this is not its original special that if it will not be able to help you then we make this curve in it and this is the mini here know what is coming here is that is there any set of two three are which we The most problem on the five elements, you leave the praise, I will be soft, our 2315 is to be looted to two and only that the brother is the moisture of the pitch that is broken from the front If it goes to then you can subscribe, okay so in this way and this last one can make 235 ghagra 200 rs and if it is happy then anyone can make dros now, I will find vegetables here, second finally chem t- will find vegetables here, second finally chem t- will find vegetables here, second finally chem t- shirt, subject of courage. There is poison in the toe, everyone makes it that and if there is anything about the MP subject, then nothing can be made other than zero. Being an amputee is a part of it. This father-in-law of MP3, MP, if you understand it as a sum, then it is This father-in-law of MP3, MP, if you understand it as a sum, then it is This father-in-law of MP3, MP, if you understand it as a sum, then it is Like, definitely the question comes, if he is a player, then he is the lucky person of triple, there are vegetables and fruits, this is the problem, he has a root but a game, now I feel this and think, what can we make about this book, but friends, if not. Here I can tell you that you can go to Ra.One, Here I can tell you that you can go to Ra.One, Here I can tell you that you can go to Ra.One, if you do not come then before that the limit will be closed and if before that the limit has to be made - closed and if before that the limit has to be made - One, I do not like the fact that cooperative institutions come then it will be filled here. I will go intermediate if I can, it will be more about how those people are 220 price I will not come because it is two parts of this type of MP subset at subset and jhatka communities and group of two most to so this will definitely do will do to all the rest If it is a straight line then I fill the right line, it is Sunnah here but now we are rolling in a good way, I do it yourself, think about it is very important, its cutting is smaller than August, so this is so, I cannot give you this for free. So it wo n't be cooked, now I can't do it in school, I had already made it, now I don't hate it here, if I got it while sitting and neither have you got it cooked properly. Hey Pappu ji, let's talk about team of two and three together. Had to make a chat, get enrollment done, I will make two three to four inside, but if three will not bat, then all the runs will have to be scored, hence if he bats, then the remaining wickets will be run. Tube Raghavan will make that, he will do it in his respective vouchers. If you are sitting then Had scored one run, the food is not good, now it is teen, if I don't bat upside down, then I vote in relations, if I were lying, then I will become those viewers. Cigarettes are present, so you are the one who is going to tear Kingfisher, what old 115 Bola, I said, I am a picture. If you see and bring it then he will make the remaining breakdown, then there was a dispute between both of them, if we talk about a week, then saw this and if you see three behind, then take Paul with you, saw here and if you saw the team behind, then I have it, then game five now. Tak team I5 said, brother, I will bat for two and three. If I can't forget you, I will not make any enemies. If you start then I will bat for five elements. This is my family, if it is not on a fast, then take them hostage. No, they have become good. Good, Bipasha can't make five and said brother, you will be making mine and if I bet, how much will you take, zero has already been paid and in this tone I said, many people will make only there, and I make five in the voucher, will you make one ? Why can't I make 235 settings yet? So ? Why can't I make 235 settings yet? So ? Why can't I make 235 settings yet? So I told her one teaspoon. Then I told her to make a banana. With me, I make my own brasil. I make the color near my name. Friends, will you make two of them? Okay, so how. This Gautam waits that the duplicate will not come, how to install the album, the gas will not come, this roll folds in such a way that the pipeline line is passing, whether it will rise or not, which does not happen, and yes, the exam when Passing and not being able to pass in the same 257, tell me what happened in the previous road, two and buy not made in the evening, did anyone make or not make anyone in two or three, are you talking about that, then one goes, then all 5 do not come twice. In the same way, Jatin was looking back, when he saw Bittu, he never did anything right in it, so anyone will meet twice and for intervention is one day, when you look back, please like volume mute has been written many times. Okay, so what was there in it, ODI, that we used to look back, this but the question combination is written to you, I will take some development and again it is 1/2 some development and again it is 1/2 some development and again it is 1/2 inch Congress is confirmed decimal O0 12345 6725, but you would have Khusro Daaba lying with him here. Used to bring this word sirvi daughter used to bring from 219 so two jhal and dot if the water boils then by the first so that you understand that because on this channel we are in it and Sir Sanghachalak question of European Union can come because it is necessary So I am fine, Bhilai's smile will go and no 2525 notice, these are the things that children should do, are they okay? So, have you understood sir, select the teams. Yes, children, I request you with folded hands, that request is that Also, before watching this question, please targets, we submit information and who reach here after watching its individual videos and are sitting with their diagrams. If you watch this video, you will get a lot of benefit. Meghnad will do the sewing, there is a bar option, I have tried. This will happen now and you will not be able to understand completely. Okay, with this video also, there is a virus in marriage, your inside will be clear, which is in this site, so what to do in your mind, at that time, I take that how does the combination code. Combination: You have to see code. Combination: You have to see code. Combination: You have to see how combination versus competition frees the community, how it creates an update function, how we targets, how the subject avoids someone, how an owl rejects someone, you have to think independently. If you inherit then please. We bowed our heads and will meet you in the next video. You will see us in the next video for this match. Team II and 225, we are Meghna, right now Meghnath and Cheez are in the meeting and if I am then we will have made it and if anyone moves away then he will not go near her. And all of them are I,
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
313
that paper to Ajay. In this video we will see the solution of super next number, so before that you must watch the video of next number once, it is related to this, so I have given us this knowledge to find the number of super and how to define super bheem number. Whose prime factors are not, its prime factors are okay, it will be given that the risk factors can be any of these, like we see with the district and course one is the first super Ali number, this option is 3570, so this is the example. If you get it then you can get hands free life 1111, if it is a festival then we have to tell the number of add super now, its factors can also be only free 517 and your purse, then the first one will not improve anything from this, how to get the number time whose factor is only 2345 There could be a limit here, there could be any number, if it is found in the literature about its size, then the number is after Salamul and there are three effects of what we used to do, one point is taken for tu and only one point is taken for thyroid. Point different and all three in starting that DP's post index point was made that track all three did rectal cancer Prophet toe were two in 2.82 C * Points pay Prophet toe were two in 2.82 C * Points pay Prophet toe were two in 2.82 C * Points pay in fact that TPO a point of two DPO point of trees and fell into a diff A Painter 5th Okay, okay, we will calculate the income in our next number, then from where you got the mean value, its point was a big, then similar and friendly work is happening here, see, now I am every one. I will keep a point for Niti, a point for my file, a point for intake for 11:00 and if there were more, there would be a 11:00 and if there were more, there would be a 11:00 and if there were more, there would be a point for all of them, so we are not going to do this, we will not keep separate pointers for each one, just maintain one point. Lo Jhal Loot Hello friends, now what will its zero index tell, okay where is the pointer, just index five quantum is here, where is the point of second Here I am going to make my answer or that inside this ODI, inside this lamp, the junction is number one in this poster, the first super hero is number one, I had broken it and now I am a candidate for the next super league number. Who all am I right now, every single point is in Asati, this point is crore, this point is 1.5, this point is seven, crore, this point is 1.5, this point is seven, crore, this point is 1.5, this point is seven, Abeer and 11.43 forces have to be Abeer and 11.43 forces have to be Abeer and 11.43 forces have to be called, it happened that Priyanka is Ravi Shankar, the point of the guy with 2036 pointers is very high. From 0.5 Next Point is doing many such From 0.5 Next Point is doing many such From 0.5 Next Point is doing many such 0.5% add till now so candidates for next super ali number which multiple life but its pointers is subscribing so simple then we a that train to band spider-man 2 And lemon train to band spider-man 2 And lemon train to band spider-man 2 And lemon into next super number candidate 350 that now the minimum of all these will become the new super number and from where you have got the minimum value, increase its pointer by one so that its pointer increases by one so till you get What happened to this, husband's point extract, by joining it, acid attacks are cured, this one point will remain the point, Daabi is pointing here, the rest is of Spice also, the same is of One and also of Level, once again Look at these two pictures together, vaccine pointer pipeline study, who will be the next candidates for the maximum on Quantum 11.2, team multiplying, then C who will be the next candidates for the maximum on Quantum 11.2, team multiplying, then C who will be the next candidates for the maximum on Quantum 11.2, team multiplying, then C point, your pointers, join it, tighten the value that is lying on it, meaning Depot 3.0 tighten the value that is lying on it, meaning Depot 3.0 tighten the value that is lying on it, meaning Depot 3.0 and the third on 15 Feb. That is pointing to the tiles, 7.2 is That is pointing to the tiles, 7.2 is That is pointing to the tiles, 7.2 is jointing it, 121 and 11.34 are pointing to the time itself, jointing it, 121 and 11.34 are pointing to the time itself, pass candidate for next time 95 711, min max of these three, super hero number one went, where did you get this from, his points So one big one is 5.8 so what should I do, go to the plus index and move that point forward. Next super, look from here for the next number. Next super on this number now, I will fold it. Look from here on source multiplied by this. How to know the point from this point, run it again, okay, ₹1, ₹1, so brother, seconds are okay, ₹1, ₹1, so brother, seconds are okay, ₹1, ₹1, so brother, seconds are appointing, one from the port, the value placed on the next, I want the free helpline, will defeat the wonders of Karo, fold it tightly. You have to do this, you will get point 1802, go to the conductor and there the value is CO2, so very theme us that look here like this medicine west If there are pointers, two are placed on top of 101. We need a party on top of the bajo. Jhal is on 15th, that's how Sarvan is doing the point of 127. If I will ever send multiplayer, then there is a pointer crop, if there is a point, then point. But also, the minimum balance of value diamonds is of the next number above or from where you got this simple, increase its point together and there is the petrochemical point, move ahead from here, when loot in fact is not seen here, you can see the seventh point here. But we have moved ahead and Savitu Banega will be arrested. See A.A.C.E.M. Multiplies from here. So I know what to do. A.A.C.E.M. Multiplies from here. So I know what to do. I will select as many prime numbers as there are and pick them by either Times of Jack Pack. Consider it as prime. Jail Sanjay, I ran a loop. If you hold the number on the gesture from zero to the last, then it is a multiple of birth that now its good morning, where is its pointer, we get information about the point which also possesses the point, which point is contacting which point. If you want the value placed on that index then DPO points 241, it is just simple that you puncture it, basically you run it from two districts to the last - from two districts to the last - then you have considered the corresponding factor of every prime number, it will make it better from here. From here, the tuck will come, the factory will come, the factor for will remain that whatever factor has given their minimum, your next super is now of number either then what you have to do is to increase the point of the point from where that minimum value was got by one, which is tight, then we explain it by one and a half. Main sochi multiple with 2002 mili aur difficult hi kept hai in spite of multiple with here willing to sacrifice unknown person three hai seventh class with sacred value kept a the eleventh multiple tweet post election 2014 to in sab ka minimum hai next super next number Make and from where the person moves his point one by one, you go here complaint that this point protects from attack, now this third join them, then 34 more or less me to the last nutritionist folds this on number Lootere media end meet ok so I made a vent for my DP. This point is of the size of a pen plus one. It is in the tube. Ok ok so let's make this. We are going to have pointers. How many sizes will you make as many prime numbers are times but lack. And in this, fill all the space on the side by making race 2 full and keep all the space in this pointer as one and after that I made the duty Jhal N plus one size Jhalmuri iPhone from where do I know, it is mainly coming in a tight box. That is super on Defy, the next one is Namaskar, then it depends on the answerer in the last, write this paste in it also that today I will get it patterned Jhala, if we start this recipe, then we will take it and fold it till the end, okay Then what do I have to do for every prime number Girls only after you have to do at least what I do I took the existence dot value jhal ko tight and friends that by rotating over every prime number jhal times not loose c plus Plus, like this, the jhala hovering over the numbers, now look at all my factors of cancer and taking them to the minimum, we have till now, whatever is Tamil, tractor, see what I do, prime fennel, Jain, Prince Jain, multiply, tweet, which TPO, which are the pointers of J&amp;K? What which are the pointers of J&amp;K? What which are the pointers of J&amp;K? What I have found out is that the first number has been picked and where its point was pointing, then I went there and picked up the value, from there the platform number from the DP, the value of medical incense, the second number deleted with where its point was pointed. His daughter's first place of cancer was even, everyone's minimum was taken out, the week's minimum becomes the next prime number, the prime number is also made, from where you move forward the point of valley million, these people will think again or 220, that one time I would write. It is something like this that if its value looks equal to the minimum, then increase the pointer of Jacqueline wider, say, I am from here, you take them, you will go to her pointer, a hang, remind that the point has become one bigger. The principle of this is that if we try to run the ore, then first one more time we preserve it, not the opposite site and not that which is working fine left side toe submit ok I understood now see friend let's talk a little about this post Look here, we will get an idea of ​​the time we will get an idea of ​​the time we will get an idea of ​​the time that it is clearly the end times from the outside till the end and then these people have kept it running, you have seen and it has been kept running by the people that this is Kepler's two and Four cloves are going on M 's * K's 's * K's 's * K's rate is 100g time complexity is coming from here its good ok so can we optimize it can it be done after let's see I do 60 stories from yours I am the first one and have left it here. Anything at zero is a storm. It will definitely remain and take pointers. Jhaal 20123. Flavor snacks have made each point pointed at the top. So what do I do on this. I use Friday. I am fine, what will I keep in the traffic, how will I do it, I am watching carefully, by the way, I am taking a fair class on it, what will be the things inside the class, scientists are scanning this tree, now the dead prime number one came to take care of her. Where is the pointer pointing and what is the value of the person in relation to both of them? So let's do this once again. If for the first time, if you want to make a new super villain number, then who will be the candidates for it and who will be the previous one? Who lives here, this candidate's multiple is 15817 121 1121, all these Androids, so all these cutlets have to be done, predicament bay two jhal, torch light, Rafi kept pinching, prime number is our three and its point is Abhivan infection, we are here and Value is getting team words like this in next five one and half inch 172 specs 11:00 and r prime number and its 172 specs 11:00 and r prime number and its 172 specs 11:00 and r prime number and its point ko is point hai tractor ki value hai toh aisa yaar prime number this factor is only showing this number multiple But be the DP of that prime number's point a painter of debt prime number that the world is basically Ecuador by picking up the value but make it tight, this is done to your bank, okay, so now let's make all these minimum on Chairman Friday, all these are minimum here. But if I get those tracks then what should I do Pretty because it is our remove practice to come back out without you Well I have removed so be tied to here Remove 313 Laila Kabir They will install the smallest at cheap prices I got the one that came out and I have made it the number for the next one, tighten it and I saw that the point of this prime number is now pointed here on one, so increase its point immediately, it was prime number brother, enter one. Increased from and this is not value calculator which is not I have added it again on the side to tight good if I apply force to remove from Friday why then it is inside outside the commission talked like this so points 1515 outside with its help I will make the next super campaign number and then give it a big point, now by increasing the scope per quintal, add it to the practical and make it twice on I, Wife is a Pointer, its 21 A was popular in 523 parties till date now. Remove this party separately, this limit will come out, the bell found in seven 7 came next superhero number one and let's increase its pointer by one, we used to add here 172 10 2013 seven more like this a little more Let's support one or two, only then it becomes clear, I approach a Hello friends, if I remove it in traffic, then the element will come out 2987 Prem and Laga Hai, I have got the next super villain number, now what will I do, I will come to a new place. Will make prime number seduced but whose point will be given a big and put it on 3DX and multiply it with the value fifteenth that you will see on the right hand side in the famous steps and it is going to happen remove it from this meeting that the live wallpaper has come out this Tree, do Veervrat on the parts of its value, then add a new platform, increasing its point by one, husband alarm set up dance, want to see, why did I remove what is present on the valuation, so this India, this till India, both of them that here also the person Here too, any person can come out, let's come out, one pipe 215 Next, after generating the first number, now 15 more will be added after making Preeti Yagya, increase the value of village wife through internet and 5 minutes craft with Arjun tractor, Pandit ji. Tighten it a bit poor, see next time you will remove it from here, which load will come out, this element came out and what was I going to do, I was going to make the next Yagya number, if it is fako, then we have to take care of this thing, this is the number that came out and Last up number, if these two are there then do n't add me here again then it is coming that the last super clan was generated by itself and Nak was going to make super hero number if both of them are one because what kind of song is Repeated Reflection. And if you will not keep this water twice then what will you do, just do Chakia and till the last this number is the last superhero number 1 and if you will not simply add anything in the DP, then you will be able to add its point here in a big place that Whatever happens with the life of many presidents, any burden will come but it will happen only once, one will come out of here twice but only once, it has been added once in DP, where is it, cancer, so its time to bless you. Talk about the phone's time complexity. What will be the size of the plateau? If it is a prime number then its size is tight. If you add or remove, then those operations of add and remove will be of the people of the village. So, if I have to update the next numbers, I remove one and then add it. After removing it, I will get the next number. Then I make a new pair and add its next factor in practical. Try that for each next number. To generate a super villain number, now one addition and one removal has to be done and although it will take time, a pan will go to people's house, I used to add and produce for you, and these people Let's complete the project and let's see, loot the police department, the police station, two crimes and 10th that I will have to make a DP, so it has happened that the end is plus one side, that intelligence is also required for foot class, it is my acting class, pair it. Inside I keep 36. The first is the prime number. Then we keep the answer. Where is the A pointer and it keeps the swelling on tight. I write the inspector. This is the prime, the point is the value of 123, then the time. Absolutely object prime were President jhal pointers will be equal report value of toe pointers will absolutely go ok because now why did the makers of Friday have foot class so it will have to be implemented na Pebble and on planets less speak fierce and because you have compared To implement this, it is the responsibility of this class to write the compare to function that the applicant and compare to go is jhal and convert the subject of oxen to be made in friday be returned s dot value minor daughter the value of on do ok Yes, let's do this, now we will be able to easily create a priority queue, click on the box, why pet class AP, the new price tip of that item, okay, so while typing, we have to set a few drops first that I If there is plus, then there is nothing every time, no, you are my friend at the language, the hero is of the length, it is good, it is the priority, why should I stop looting, add that petticoat write-ups, good camp, on the other hand, the times of crime sang that Valid APhoto by Nakuul Mehta Pointer Prime Safai Sub Point will be above Aman and value will come for the first time only the first 2 Prime Safai will be ok let's multiple will come ok will remain not thanks for multiple old for the first time So this coming plate gun has been added, now I would have got the answer of DPO one also stored, abe Akhil had started, this is first to n till lokay were in the last, we have got this return done, ok, what to do in this. You will have to remove it on Friday. Practice on the remote on the phone. You don't remove. Okay, friends, I removed it. Now let's verify that. Now make your answer in fact. Before making it, you will have to apply a little oil somewhere. That's it. What? DP off, I just say that it is white, why not practice it somewhere, the value of the one that has been removed and the last super next numbers that it has generated is not for both. Once I say this, what have I checked? You had generated your last super hero number and now you have the value after removing it. Are these two values ​​equal? these two values ​​equal? these two values ​​equal? Okay, if both of them are equal then I will not create a new super hit number. I am for both of them. Repetitions will go like this, so if these two are one bus, then we will not do anything, except that in a GPO park, we will do many more of these, okay, you can write it like this only if it is not equal, then get it stored Shravan That the cat is good, fine and I also keep a little bit of this and here press the address, village is good, fine, good, otherwise what do you have to do, the pair has been removed, now you will be admitted on Friday, I am on top priority. I have to add a new love. Right, you have new players, if you have 90, then read the name of the prime number of the remote part, then what were the prime pointers. Okay, the timer till the remote part of prime number will remain the same, just at that point. It increases with the torch light and value will be given to the pet prime number multiply wealth EPFO that its pointer plus one this one so this one here we made the prime number remain the same point made president till track number multiply wage DP which point is updated Its value is done, she writes it in the foot and adds it in the meeting. If you say yes then it will continue like this. All the numbers were deleted that if you get a different answer from me, then let's try solution two also. * solution two also. * solution two also. * That and let's try to front. Hello friends. King Tried to submit got faster, got integrated inside, so friend, we have discussed two products here, the first approach, which was decided from the fire number itself, so it is dry from the number and whose Montessori came *'s tight and whose Montessori came *'s tight and whose Montessori came *'s tight second which We gave priority because it is a practical approach with help, so its time complexity is why we bought it and it takes time to unlock. I hope you will understand the question. You will have a lot of fun by folding it. I will call this question. Thank you very much and please subscribe our YouTube channel Thank you Shravan
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
380
Hello Jise Aggarwal welcome you all channel quarters made by so let's nine days let 's call problem for today airport 's call problem for today airport 's call problem for today airport problem kya rahi hai achcha deformati whatsapp problem achcha you have understood and those who want to try it yourself see what is here What happened was that all the functions were named and had all the values ​​easily. The and had all the values ​​easily. The and had all the values ​​easily. The call will be made easily. There is no problem. Rendmai is set here. The set has to be initialized and then it has to be inserted. Some more difficulty is less. No, but there is a removal function in it is possible that you are getting stuck somewhere, so what can be the biggest hint for this, that whenever you are removing from a term, if you have erased it. Let's suppose that the function is done, so what will be this race function that it will be specifically linked to that point, but if you try to access this point, it will also give you the value. Okay, so what you will have to do is to shift the entire values. If you do not get the shift done and you ever go back to the same index, then always provide that value to you. This thing can be important here, it can be the biggest hit here. Well, you did not understand the problem of this, nor did they have any tension. There is no need to take it, first of all understand it easily, the question is, what is the implementation of this problem? First of all, let's understand what the problem is. Look at yourself. If there was an input, there was something in the given input. It was a vector. It was the vane of a vector. And this one was a vector given in which a lot of numbers were given and how much was to be given in the output, it became clear to me, there is no problem, okay now how will it produce itself, so let's see what happened here. Which function is ok, it has nothing to do with it, there are so many stings, you have to take care of yourself too, so it is not just a function with the name of all these strange things, they are already freely defined, you have to code them. How to code that if this function is ever called, what does it mean that a new set is created here? Okay, so no value will be passed with it, that's what you have to do here. Creating a new set, okay, what did you say after that, said, this value is okay, then what should you do, let this value be set in it, that function was already given, why did you initialize it, what happened after that, said insert This is the function named insectom, the function call was done automatically. Below, you just had to write some code inside it and after writing the code, you just had to insert the value, it is fine in this set, no problem. It is understood similarly that there is some value inside it, that value will be given, what will be the value that there is any value inside it, any value, please return a value, okay if it has said remove, then we will get it removed from inside but now the output. What should come in ok, what did you do at the time of insert ok tell me one thing in which if you already have any value van is ok like take man here ok and then it will be given back to you to insert five then what should you do to return It is fast and if you are given to set and there was no 5% here already, then you have to make your was no 5% here already, then you have to make your was no 5% here already, then you have to make your first return. You have understood what to do after making many returns. If you do not come out of it, then what is there till now? What happened is this is an insult call, what was there inside it? Was there no value in it? There is a value inside it and what is the return? Okay, very good, what happened after that, had to be removed now from this vector. Okay, in this chapter you have said that you have to remove yourself, otherwise from where will you remove it, then okay, if it is not there and the remove function has been given, then what will be the return, okay and if that value is there, then it is okay. And if the function is called, what we do is that we remove that value from here, okay, similarly what is the insert of shirt again, we will set the value of 2 and our true, after that we get random what happened in this entire Trend will be found over the entire vector and any value in it can come in the output. Okay, so any of the 1 or 2 values ​​will come. Okay, so any of the 1 or 2 values ​​will come. Okay, so any of the 1 or 2 values ​​will come. After that, what will happen in the pudding function of remove function, who had to remove, that means we will do it okay. So can you insert it? Are you already present? Okay, what did you say after that? The get rent function has come back. Okay, only you can do it. Reasoning is also simple. There are two more important things which need to be paid attention to here. Please understand what is said in this that open first you can do it a little bit, okay it can be a very good four, okay leave everything else, okay do n't just tell me all this that it is a vector, anything else is okay, tell me. If you have to search only in open time, then what kind of elements can they be and searching has to be done in them, that too in the oven, so here the thing is clear to you, I understand that a lot of things have to be searched in the oven. Complete elements can be one method Map Very easily I understood that if you want to search then you will have to create a map, okay if two are cleared then this is the initialization of yourself, okay now you have to search over. What else will you keep after 3 in the value? Tell me what else will you keep in the map after searching in them. Now it is 12345, like it is of size 34. Okay, so you have inserted three inside the map. You will search it very easily but after that. If you want to remove it, then it will have to remain in this vector, then what is the most important factor to remove, tell me its index, otherwise I will remove it, then I said, okay, that's what I wanted, I mean, what will I do with its map? I, the company within, got this show done and will get the show done in value like this is three here is a three, here too, it can come, once again, it cannot come, what did you see in the Paneer set that which one This is a value, it can be entered only once. If you try to insert the value from it again, what will come if you try to insert it for the second time? Will you try to insert the value from it? What did you do normally? What will it do? Created a vector of yours. Okay, inside a vector, we will take the map from WAN to the point of time, what will we put inside the map, WAN and what will we do with it, OK, similarly, if we insert here, then it will not happen. So tell me yourself, okay, let's see, now you say this is your function, okay, because you have to do that return, right, basically you have the insert number function here, the function named insert, what did you say that this is your tell this van? The base is done, first of all tell me whether this value inside the map is ok, is this value present? Now see what happens here 1 2 3 4 5 is ok and Apna asked whether the value inside the map is ok. If I search for 10, then along with the search for 10, its value will also appear. I never told you that there is no present in it, so you are always there, then the minimum answer is possible, it can be han and van in the value. Its value can be you, it will be through, it will be four and A is always clear, so if I said that if its value is &gt; 0, what does it mean that it was already present, then look at this point of time, it is clear, then that's it. Here our inside function is cleared and it produces what you did. Okay, so whatever random value comes here, what do we do with it. I have modified the size of the vector with my vector. What will come on the mode, like man lo. 10 will come and this is the size of the stone, if you are ok, then the value of tu is the same, that mod will be done with you, ok Let's Let's Let's discuss a normal thing, first of all, what if a value function is called? If there is no value present in it, if that function is called, then only half of the return will be returned, we will do something, it is right, it is clear, it is right, what will we say, if the value which has just been returned is okay, it is okay that it will be ours and There is a value, there is no problem, okay, a little bit has to be completed in this question, what has to be done to remove it will also be there from here, there is no value in it, but if you call your index specifically, then what will it do here, it will show. The show will do fine, you will have to do it well, because of this, you can reduce it by saying that if you shift the last element here then the form will be created that if your value is this, it is okay here if your If you just get it done then what will happen here? Now what will happen is that if you ever call the index in this particular, then it is possible to use it as an inter function. If this is a random motion, whatever is in the last part of the actor, I have done it here 11 This is the key of whatever was last in the map and now the value of whatever was found here is fine, the last one is sorry thank you.
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
1,060
hey so welcome back in this another daily code problems so today it's called missing element an assorted array so let's take a peek at this so essentially what you're given is just an array called nums as well as an integer called K and so what you want to do here is basically you want to find some missing number but what really is going on here is that this array has basically a bunch of numbers that is in ascending order so it's sorted from smallest to largest and you can see here it doesn't have to necessarily start like at zero it can start at four or five or six or any arbitrary number but what matters is that basically when you look from left to right it's an increasing order so the numbers increase when you look left to right and so what you can also see is that there's kind of some space between each number at times where here you don't see the numbers five and six it basically goes from four and hops directly to seven and then there's non-8 directly to seven and then there's non-8 directly to seven and then there's non-8 but there's a nine but between nine and ten well there's no kind of gap between them you just go from nine directly to ten um here's another example it goes one two but then we skip three here and then we go on to four and so you don't necessarily want to grab like any of these missing numbers you want to grab a particular number and that is described by this integer K and so basically what this K symbolizes is that you want to find the first missing number and so going from left to right here when you're looking at this array you would see that okay you go from 4 and then the next number is seven and so there's some missing numbers between these two which is five and then six and we want to grab the first missing number in this array and that would then be 5 because that's the first number that's missing in this array okay and then for this one now that we want to grab the third missing number when we look from left to right here so in increasing order we see okay it goes four and then it goes seven and so basically there's two missing numbers between these two and so then K which is initially three we would subtract 2 from it because essentially we've already kind of looked at two missing numbers so far and so now we're just looking out for one more missing number which would be the next missing number and so then we're looking at okay 7 and then it goes seven to nine and while there's a missing number between these two which is eight and so now we found another missing number we're now at zero and so we return this missing number eight okay I'll hopefully explain that pretty well um it doesn't make much sense I think the code I will really help you better understand this um but yeah so but before I go into the code actually um one thing that I did not realize and I first implemented this if we look at my submissions um just a little bit ago I solved this question but I did it in O of n time and constant space and so the way I did it is I kind of just did exactly what I told you I kind of went from left to right and I just tried to hit those conditions of okay once it hits like a zero or that base case then we just return that particular number um but what you can do is actually provide a log n solution and that's because we can actually use binary search for this question and so that will give us a much better time complexity same space complexity because you're using constant space but it's much more performant and so it was an initial it wasn't um very intuitive for me to use that I just thought hey let's do kind of a greedy um linear algorithm for this but the way that you can do it using um binary search I want to kind of type that out which gives you this kind of log and solution is that okay we have these two pointers left and right which is typically what you do for binary search and you can find out at every Point how many missing numbers are between two numbers just by writing like a particular Lambda function or just a function and so one way you can do that is basically you can take say you want to find out okay how many missing numbers are between nine and four and so basically what that's going to be is nine minus four which is 5 here and so basically there's five missing numbers and so the benefit of this is then we can kind of compare it to K and then that can kind of limit our bound saying okay we need at least one missing number and while since there's five missing numbers between this range let's limit our range between nine and four and so let's no longer look at 10. and so now we're kind of looking at between 4 7 and 9 and so we say okay let's take the midpoint which is seven and so then we do 7 minus 4 and see okay how many missing numbers are between these two points and well that's going to be um three here and so that will enable us to say okay well there's also enough missing numbers to now be looking between these bounds and so essentially you get to the point and we just did where there's only two different numbers four and seven and so then you just say okay let's take that left number and just kind of add that uh K which is one here um and that's pretty much it um I think the only thing that I'm missing here is that in some cases you want to be taken into the account the particular location that you're in because basically when you're saying okay really it's not exactly like okay um take four and nine here four minus so nine minus four so yeah there is a difference of five between these two numbers but what really matters is that you also take into account the index like nine here and so that then you just subtract 2 from here because really what this is saying is that you're saying that there should be at least five numbers but here you're saying that there's only two uh or really I guess three numbers that should be here so really the number of missing numbers between these two points is three missing numbers not exactly five missing numbers right because there should only be at most three here okay I hope that made a little bit of sense so let's go ahead and implement it I think this will really help solidify things so the first thing that you typically want to do for binary search is that the left pointer will be zero the right pointer will be the length of the numbers minus one and so essentially we're going to be returning some particular missing number at the end of this okay and so from here um what we definitely want to implement is that um function for determining what is the number of missing numbers at a particular index so number or I guess return the number of missing numbers at index I and so to do that we can just write like a Lambda function or I could just write a normal function and so that would be okay let's call it um like missing Lambda and so that's going to be essentially we'll pass in a particular index and so then we're going to return um the number of missing numbers from that point on so the number at I and then we basically just subtract the first number to get the kind of the difference between 9 minus 4 which we did in our previous example um but then also we want to take into account the index that you're at so that's like the true missing the number of missing numbers not just the difference between the starting and current number all right and so from here there is one Edge case that we have to think about and so what this is that at certain points we can see um at this case the actual missing numbers is in between these numbers it's actually past four and so we return 6 here because 1 2 there's one missing number three right so we only need to find two more missing numbers and that's pass four so then we would say okay five and then we have one more missing number and then after five would be six and then this would be zero and so we would return six we want to account for this Edge case so Edge case where um the missing number is past the last number and so to do this what we want to think about is okay um we want to look at the missing num the number of missing numbers our last index here and so if our k that we have here is greater than the number of the total number of missing numbers in this entire array then naturally it's going to be beyond that point and so what that'll look like is then okay let's go ahead and return basically the number the last particular number Plus or I guess minus the number of missing numbers in our array so missing at this particular loss index and then plus K which is okay how many or what missing number are we looking for all right and so from this point on we can actually finally do binary search here so let's go ahead and Implement a binary search so typically what the pattern kind of looks like um is this so while we meet this condition let's go ahead and find the current midpoint which you can do it a couple different ways but I like to do it this way and so from here we just want to be looking at two different conditions all right and so basically what we're thinking about is that okay if our um we want to make sure that we're shrinking that range based on the number of missing numbers so we want to get the current kind of number of missing numbers at this particular midpoint and so basically we just care about comparing X um 2K and so from this point on we want to be comparing X to K and so we're saying okay if there is a greater number of missing numbers um at this current midpoint the knots shrink it so if x is greater than or equal to K that just means okay we have enough missing numbers at index M to satisfy um K so let's shrink our range so in that case r will then be equal to the midpoint otherwise we want to do the opposite so basically else it's the inverse of this so it would be like K is greater than x and so that case we want to um not shrink but really just kind of cut the left hand side because we need a greater number of missing numbers moving forward so otherwise then our left pointer will then be equal to the midpoint all right and so once we do this and we finally exit our binary search that then means we finally found where we what is the missing number and so what that's going to be is basically the number on the left hand side plus K because that is essentially the uh what missing number you're looking for but then we also want to be subtracting the number of missing numbers up to L and so what that looks like is that once again if I show you this example maybe um I like this one and so once we find that okay we finally got our left and right pointers the left pointer is at Fourth the right pointer is at seven then we say okay how many missing numbers are up to four well there's no missing numbers so missing will then return like zero and so then the number here at on the left pointer will be four and plus K well K is one and so that in that case would return five if we look at this example here we would get to a point where um let's see we're at seven and so this would return and I'll just kind of erase all these we would be at index seven so left is here and then the right pointers here and then how many missing numbers are up to uh this number seven well that's basically seven minus four minus one because this is index one so that would be returned by this Lambda function and so then that would basically do minus 2 here and then plus K which is 3 so plus 3 and then that would return 8. all right so let's try submitting this and success so that is the Waco problem for today so it's log n time complexity and constant space are o1 space complexity I hope that helped a lot and uh good luck with the rest of your algorithms thanks for watching
Missing Element in Sorted Array
longest-repeating-substring
Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array. **Example 1:** **Input:** nums = \[4,7,9,10\], k = 1 **Output:** 5 **Explanation:** The first missing number is 5. **Example 2:** **Input:** nums = \[4,7,9,10\], k = 3 **Output:** 8 **Explanation:** The missing numbers are \[5,6,8,...\], hence the third missing number is 8. **Example 3:** **Input:** nums = \[1,2,4\], k = 3 **Output:** 6 **Explanation:** The missing numbers are \[3,5,6,7,...\], hence the third missing number is 6. **Constraints:** * `1 <= nums.length <= 5 * 104` * `1 <= nums[i] <= 107` * `nums` is sorted in **ascending order,** and all the elements are **unique**. * `1 <= k <= 108` **Follow up:** Can you find a logarithmic time complexity (i.e., `O(log(n))`) solution?
Generate all substrings in O(N^2) time with hashing. Choose those hashing of strings with the largest length.
String,Binary Search,Dynamic Programming,Rolling Hash,Suffix Array,Hash Function
Medium
null
18
in this video we'll be going over the question foursome so given array numbers of n integers and an integer target are there elements a b c ds and num such that the sum of the four elements is equal to target find all unique quadruplets in array which gives the sum of target notice that the solution set must not contain duplicate quadruplets so for example we have one zero negative two and our target sum is zero and we have found three quadruplets in which each of the set in each set that some of the elements is equal to zero so let's go over the dot process so the brute force approach will be to perform four nested for loops to find all of the possible quadruplets this approach will cost us of n to the fourth time complexity because of the nested for loops we can implement and optimize approach by sorting the input rate in ascending order then we um we can use a for loop or a nested for loop to find the first two elements inside our quadruplet then we can implement a two-pointer approach for the last two elements inside our inside of quadruplet this will allow us to reduce the time complexity to of n to the third of n to the three a side case we have to handle is the solution set must not contain duplicate quadruplets so we the side case we have to handle this to prevent duplicate quadruplets when we sort the input array in ascending order all of the duplicate elements are grouped together this means for example if our quadruplets consist of the elements c d if we have already considered a for the first position we want to skip all future occurrences of a to prevent us from getting a duplicate quadruplet the same case also apply for b c and d so if we have b we have already considered the element b for our second position we want to skip all future occurrences of b and the same case apply for c and d uh this will be more clear in the pseudocode after we have accounted for a number at index i inside our quadriplet we will want to skip all future occurrences of let's denote this of x for the position i actually we should call position i instead of calling index i position i inside a quadruplet okay now let's go to the pseudocode so we'll sort the input array in ascending order then we're going to create a list quadruplets to keep track of all the quadruplets now we're going to iterate through the indices from zero to numbers down length minus three uh minus four because we wanna have space for at least three more elements so this um so these indices the first indices will be accounted for our first elements this will be the indices for our first elements which we can say a so the indices we're going to denote as i and then if i is not equal to zero and the previous elements is equal to the current elements so the previous element is good to current elements we want to skip the current elements because we have already counted for the current elements in the previous iteration basically if our current number is a and our previous number was also a we want to skip the current a so we just say continue to next iteration then we're going to iterate through the indices from i plus 1 to nums dot length minus 3. this will be the indices for our second number so in this case will be a second number b so we're going to denote it as j then we have to handle the same case so if j is not equal to i plus one and the previous elements is equal to the current elements we want to skip the current elements so for example if we if our current elements b and the element before is also b we have already counted for b for the current position so we want to skip the current elements now we're going to have our two pointer approach to find our last two elements so i'm going to create two variables to be our two pointers so we'll have k initially at um j plus one and also m is our other pointer so initially at the end of the array so no it's not length minus one um we use m instead of l because the letter l looks like a one so it can be a bit confusing inside the code so i decide to use the letter m instead so while k is less than m that means we can still form a quadruplet if k is not equal to j plus one and the previous element is equal to the current elements we have we want to skip the current elements again this is the same as preventing our duplicates in both of the cases above or i and j so when increments k and then continue to next iteration then if m is not equal to nums dot length minus one and the current elements is equal to the previous elements we want to skip the current element too and plus one in this case because we're having our two pointers are converging toward the middle so we're gonna decrement m and then continue the next iteration now we're gonna find the sum of the four elements located at indices i j k and m then if sum is equal to target then we know we have found a valid quadruplet so we're going to add the four numbers to quadruplets then we'll increment a pointer k so we're going to increment our k pointer just to allow us to have access to the next quadruplet if and then if else if then we'll say if some is less than target we want to increase ours we want to increase our current sum we're going to increment k else we're just going to decrease our sum so we're going to decrement m and then we can return our quadruplets now let's go over to time and space complexity so the time complexity is equal to of n log n plus of n to the 3 is equal to n of n to the 3 where n is the length of the input rate and over n log n that's for sorting and of and cube is going to be um two nested for loops four loops plus two pointer now my space complexity we're going to say of q where q is the total number of quadruplets again this is our resulting list now let's go over the code so we're gonna first create our list for quadruplets and arraylist now we're gonna sort the empire in ascending order iterate through the indices for our first elements in our contribute the current elements is equal to the previous elements we want to skip the current index so just hit continue and then iterate through the indices of our second element in our quadriplet then same similar case we have to skip the current elements which is equal to the previous elements j is not equal to i plus one and the current elements let's go to the previous we want to go to your next iteration now we can create our two variables to be our two pointers and then while we can still form and quadruplet between the four numbers if the current element is equal to the previous elements we want to skip the current index okay let's go to numbers k minus 1 i'm going to increment k and continue similar case for m if m is not good it's not at the end of the it's not at the last index and the current element is equal to the previous elements you want to skip the current index now decrement m and then continue now i'm going to find the sum of the current four quadriplets there is some let's go to target and we will just uh we have found a valid quadruplet so i'm going to add quadruplets add the current phone numbers and then we're going to increment k actually before here we should be doing an else if so if else if some is less than target we want to increase our sum by incrementing our pointer k else is greater than target so we want to decrease our sum so we're going to move our right pointer instead and we're going to return our quadriplets oh because we need to add a list instead so we cannot add it right here so instead let's say erase that as list over four elements let me know if you have any questions in the comments section below like and subscribe if you would like more videos that will help you pass a technical interview i upload videos every day if you have even any topics that you want to cover let me know in the comments section below
4Sum
4sum
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that: * `0 <= a, b, c, d < n` * `a`, `b`, `c`, and `d` are **distinct**. * `nums[a] + nums[b] + nums[c] + nums[d] == target` You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,0,-1,0,-2,2\], target = 0 **Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\] **Example 2:** **Input:** nums = \[2,2,2,2,2\], target = 8 **Output:** \[\[2,2,2,2\]\] **Constraints:** * `1 <= nums.length <= 200` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109`
null
Array,Two Pointers,Sorting
Medium
1,15,454,2122
1,877
hello guys welcome back to another episode today we are going to solve L CES daily question which is minimize maximum pair sum in an array problem number is 1877 question is the pair sum of a pair a comma B is equal to a + b the maximum a comma B is equal to a + b the maximum a comma B is equal to a + b the maximum pairer sum is the largest pairer sum in a list of pairs for example if we have pair 1 5 2 3 and 44 the maximum pair sum would be 1 15 2 3 44 which is 658 okay fine given an array of uh n nums of even length n we have to pair them into nums into n by two pairs such that each elements of nums is exactly one pair and maximum pair sum is minimized fine so what they're looking for is uh each element is paired once that is fine and pair sum is minimized so what we can do is the maximum number should be paired with the minimum so here they have paired five with two 3 with three similarly here they have paired five okay we have six so six with two which is minimum then it must be five with three and then four with four so this is how they are pairing okay let's move to the approach part okay so what we can do is sort array so that we will divide it into n by2 pair so that we get Max and mean on other side so what it will do is when we do it when we s for example let's take this example what it going to do is it is going to take your array and change it into so this is going to convert it into this array and when we split it from here we can pair last with first second last with second third last with third so we have to minimize some so that we can pair Max with mean second Max with second mean and so on and at the end add some of these pairs in an array and get maximum from it that's enough for the approach part let's move to the program actual program going to blindly sort it let it be what uh it is then we can get length that is uh total length and let me take so as we have to divide it into half let me take uh half length which is equal to length of we already have total by two so just to be safe int of L of two I in range of half length because we can just uh move to half length what I'm going to do is let me just quickly add a variable array SM now SM ARR do append we have to append what that is the first element and last element so the first element is going to be your n nums of I whereas your last element is going to be your total length so total last element is going to be your total length minus one this is going to be your last element but what we have to do is we have to subtract your I because first time it is going to be uh zero so that is fine we're going to get last element whereas after that it is going to increment by 1 one so that's why and let me just return uh Max of we have to take Max SM of error and one thing I just notice is the indentation and let me run it quickly and our first test case is accepted as well as the second test case let me submit it and it worked
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
1,866
so i was giving i was looking at the latest virtual contest and this is a hard problem number of ways to rearrange sticks with k sticks visible so you're just given one to n and you want k sticks to be visible from the left right now you can see that one three and five visible from the left over in this example one and three are visible two and three are visible again so we have to find out how many such combinations exist and then return it modulo 10 to nine plus seven okay now the first thing we want to do is we want to create some kind of recursive relation as we can see this is thousand and thousands so dp of k into n or even dp of n square k would work so the first thing that came to my mind is maybe it's something to do with the maximum element where i place the maximum element because he will never be hidden but then it gets too difficult because you have to place left and right what about the minimum element can only be seen at the first index after that he will always be hidden right minimum element will always be hidden after the first release so okay let's place him over there i've already written down some examples for explaining here we can see that let's ignore the minimum element and we are left with two three four five and six here if i remove the middle minimum element okay also another ob this is a key observation given these buildings and these buildings okay is there any fundamental difference in the structure no because these are just buildings with the consecutive difference of one so if you look at the diagram for these buildings it will just be five standing lines one greater another so the first problem is reduced into this right and here we can see building number one and out of the remaining we have to find k minus one buildings correct so that's one of the ways to reduce the problem if we are seeing the first building now what if we want to hide the first building where can we hide the first building can only can be hidden behind any of the other buildings right this one will be hidden behind any of these buildings is greater than one so it could be hidden behind two behind three behind four behind five and behind six so if we want to ignore this element the minimum element we can just ignore it and we have remaining n minus 1 buildings so dp of n minus 1 into k but n minus 1 times so this should be multiplied by n minus 1 ok let's write the recurrent solution let's go for python first of all we want to see what if we show this building from the left so show equals to self.rearrange show equals to self.rearrange show equals to self.rearrange sticks i'm showing the building so i have one less building and i have one less building to show that's it now hide this building behind any of remaining n minus 1 buildings so height will be equal to first of all n minus 1 buildings to hide and then how many different ways to place the buildings i need to among the n minus 1 buildings i need to place k buildings so that's for hiding okay and finally we'll just return show plus height now one thing we should not forget is to do the module over here and what about the base cases if k is equal to zero i can never show zero buildings right cannot show zero buildings if k is equal to n return one why because there's only one combination to show five buildings if i'm given five sticks correct that is in increasing order sorted form if k is greater than n return 0 why i have only n buildings how is it for humanly possible to see n see more right these are the base cases i've written if but it could be alif but of course return so it shorts now we can see this code and it won't run because i forgot to do the modular part of course let's write the modulo code as well modulo 10 raised to 9 plus 7. so that is the first solution this is the solution the same thing i just merged two of the return zero else statements and of course it's dp so we have to put the funk tools cache that is basically automatic memorization okay this is the code i'll just paste it here so we can see how to reduce it of course that one i forgot to put the funk tools cache so that's why it didn't run now these two if statements could be reduced into one if statement since equal to comes under greater than equal to if i put a greater than equal to here so that's all for the logic if you're just interested in the solution that's all now i'm just making it a one-liner all now i'm just making it a one-liner all now i'm just making it a one-liner as we see the if statements can be condensed into this form like if it's greater than equal to or it is equal to when to return 0 when k is n and k is not 0 these two if statements have been reduced into that form uh what about this show and hide all this can be reduced into a single line just by pasting these values directly inside what i mean is we can just take the value of show and paste it here take the value of hide paste it here now the final thing this is a if statement so that means this is kind of like an else right so let's just make it a one liner by doing a ternary operation return end if this is the case else return that other thing which is the recurrent solution of course you don't have to write return inside the terminal and that's how we get it finally in one line and if you did not get my explanation well uh you can just learn about dp and the logic was just this there are two choices one of the choices each of the choices reduces into a sub problem and in the sub problems n and k is always less than the original n and k that's why it can be solved by dp since it is acyclic from n and k and it's either going to n minus 1 k which is this one or it's going to n minus 1 k minus 1 so o of n k time and that's it that's how to solve it in one line thanks for watching and yeah please upload the editorial uh if you find it interesting that we can do this
Number of Ways to Rearrange Sticks With K Sticks Visible
restore-the-array-from-adjacent-pairs
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Array,Hash Table
Medium
null
142
Hello Friends Welcome To The Video Chahiye To Code No Problem Equal Nikle Central To Change The Language Of Development Cycle Benefits Mono Cycle And You Have To Determine The Inside Adsense Problems With Sister In English Apoorva Element West Indies For Declaring His Pregnancy Director Cycle And Miss Cycle Stunt In Order For Smooth Is Particular Nudge To Reduce Particular Notification Actress Rekha Richest Man Power Se Type Data Structure Royals Team Storing Day From That Flat They Straight Note One Needs To Read This Is Not To Play Store Rate Receiver Note 3 B To Read Receive The Loot Debit To Extend Maz Chal Poking Tax Return File Distorted Please Six Pieces Tourist Places 7 Okay Baby To Sit In The As It Means Tours1 1919 Total Time Nothing Contents And Which Can Be Seen In The Present Facts Not At All But One Day You Won't Know Which is the Worst Thing Is The Return of Rebel Without Oven and Difficult Question To Subscribe To Enter Into To Subscribe To Meat Point Alexis Starting And The Same Question A What Happens Snow Point At Which Has Been Able To Move One Step At First Travel Point Also Pointed Mumbai Two Steps Tax And Return Point Research Lawyers Mumbai One Step Birthday Gift Point At Which Has For Its Object Will Do It Well Mumbai Two Steps Murphy Raw Next Time In Mumbai Again Play Fast Next Nuvve Tips Angry Birds Winter Hai Printer 14.5 Printer 14.5 Printer 14.5 120 B OK Electronic Positive Thursday Video Me To It's OK Mid Mumbai Ka First Time Table 2018 19 Subscribe to Channel No Matter What This Point to Me Hai Idhar Slow Cycle is Important Hai Pimple Play List Snow Point Aware and Fast The pointer will move two steps at a time and will not reach the channel and OK but they will not meet me on the road to cover the distance from start to cover the distance to the place where the question is. And placid at not withdraw his fast 10 steps us five do this lover non muslim point unorganized slow whose main in the next video fast point now school na very good return gift open the setting main let me write down admission with song the best way to cash Target on Withdrawal Declare Them To Point At Least No A Star Point To That Point Collect Daily Point To The List Of A Ploy Difficult Fast Indore Meetings In England Spinners Patience Cycle To Cycle Found Eligible Which Will Declare Isabgol Invalid Bullion That Cycle Songs And Destination Immediate Call Spa For Weaver Meeting Mid Size One Will Go To First Unread Post Give The Note Meeting Night Only In The Recent Election Will To Give Notification United Superstar Claim Number Is Channel Next Day The First President Should Definitely Not For All Subscribe Channel Subscribe Now To Which What Is You Is Tigers For These Truly Believe In People From One More Step Audition Additional District Is Cycle Is From Its Significance Of Many 251 Pointers By One State Book Former Want And Finally You Will Reach dust latest after cycle understand then select start minute mile solar oil add cold play's latest points 212 now half new cycle was not from inside the tune of visitors tap this cycle sperm is not regret this capsule vitamin ok restaurant support And sewerage and king hua tha 120 dars on cycle part mahal gautam returning blood to it's ok to ki reddy whatsapp problem times new cycle click on this issue how to give very good and gives nod to steer with this situation ok no land beam Friend Tips Working That This Spider Solitaire Life Not Passed With Very Super Mr. Vivek Oberoi Jab First Epistle To This Amazon I Will Be Able To Forget Coming Patient Cancer Name
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
299
welcome to september's leeco challenge today's problem is bulls and cows you are playing the following bulls and cows game with your friend you write down a number and ask your friend to guess what the number is each time your friend makes a guess you provide a hint indicating how many digits in the guess match your secret number exactly in both digit and position those are called bulls and how many digits match the number but are located in the wrong position those are called cows so for example if we're given the number 1807 and we're given the guess 7810 we have one bull because the eight is the right position and digit and we have three cows because we have one zero seven and seven one zero we have the right digits but they're in the wrong position if they don't match at all then we don't return anything and so on and so forth so this problem is a little trickier than i expected but the straightforward approach works fine here what i'm going to do is convert both our secret and guess into a list of digits and what i'll do is go through each position and check to see if both the position and the digit match if they do then i will pop that digit off of the secret and guess and increase our bull counter once that's finished i should have the leftover digits and these are the possible cows right because maybe they're the right digit but they're in the wrong position we already know they're in the wrong position for sure so what i'll do now is create a counter object and just go through our guess and see if any of these digits are in the count in the counter object if they are then we'll increase our bull or our cow count and we'll decrease the counter all right so uh first thing i'll do is initialize bull and cow both as zero and i'm going to convert our secret and our guess into a list so what i'll do i'll just call that s we'll say list for secret and for guests i'll call that g list or guess now this part was a little bit trickier uh what i want to pop off uh the digits if they're in the right position for both the secret and the guess right so what i'll do here is initialize two variables i and j i'll say while i is less than the length of secret or guess it doesn't matter because we can assume they're going to be the same length we'll say if the s i is equal to g i uh what will we do we'll pop it off so we'll pop it off of both i and sng but the thing is because i'll be popping it off while i go through this loop i need to make sure i'm in the right position so what i have to do here is actually use this j object i'll increase our bull by one whoops and i'll increase our oops our j counter by one as well because actually no we don't do that we will do that only if they don't match we'll increase our j counter if they don't match then we know we can move ahead in our j counter and we'll always move ahead for our i counter so that we'll get through the entire list all right so now we have all the bulls and now we have two lists that have the numbers which were not in the right position right so all that is required now is what i'll do is create a counter object using the s and this is going to be all the numbers and the number of them inside that are correct right so for the let's say l in for the letter in our guess g if this l is in the count object and the count number for this character is greater than zero then we'll increase our cow and we'll decrease our count l by one just to make sure that we don't reuse any of those so once that's it we have both our bowls and cows so we can just return a string what i'll do is use the format string i'll say how many bulls how many cows and we'll say bull cow let's make sure this works uh looks like i got an inject out of range i hmm i guess this needs to be a j and that makes sense because i'm popping these off right yeah so i guess i need to be a j that's my mistake and it looks like it's working let's go and submit that and accept it all right so this approach is ofn and also probably uses ofn time complexity as well which is fine like the real big part here is figuring out that we have to use some sort of hash object to check to see if our digits are inside of our secret but not in the right position there's definitely better approaches to this is definitely not the best one but it works i think it's pretty understandable so just gonna go with that so thanks for watching my channel and remember do not trust me i know nothing
Bulls and Cows
bulls-and-cows
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: * The number of "bulls ", which are digits in the guess that are in the correct position. * The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_. The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits. **Example 1:** **Input:** secret = "1807 ", guess = "7810 " **Output:** "1A3B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1807 " | "7810 " **Example 2:** **Input:** secret = "1123 ", guess = "0111 " **Output:** "1A1B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1123 " "1123 " | or | "0111 " "0111 " Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. **Constraints:** * `1 <= secret.length, guess.length <= 1000` * `secret.length == guess.length` * `secret` and `guess` consist of digits only.
null
Hash Table,String,Counting
Medium
null
120
cool 120 triangle given a triangle find the minimum pass some from top to bottom each step you may move to adjacent numbers on the wall below exam we're given the following triangle some number the minimum have some time talk to bottom is 11 bonus point to be able to do this using of an extra space where n is the total number of rows in the triangle okay I mean it depends how you want to define space you actually just used her input anyway and mutated but I assume that's that is you know cheerfully doctor point but uh yeah I mean I think this is actually standard and this actually so I think yeah so this goes back to what we talked about earlier with bottoms up and Todd cow so you could certainly do this top down with recursion and stuff like that but then you're not going to be able to do it over any extra space so you have to do in dynamic programming in this particular case oh sorry bottoms up dynamic programming to get the of an extra space requirement and I think that's what we're going to do yeah I mean I think this is a video on this a standard eat problem but yeah we're Xbox for ya okay and I'm actually just gonna be yeah the thing to note is that for each row you only need to look at the world minus one or the world on top or the bottom to value one I think is symmetric it's just that if you don't do it symmetric I mean it's symmetric but if you defined how you want to do it some ways are no easier than other but um but yeah okay code it that's tough Mia just hypothesis no I'm sorry okay so I think just well actually I could come too maybe okay I know I said I was gonna do things in place and you could certainly do it but I think I just for the sake of my practice actually I'm gonna do this in this max I guess they don't tell you I should understand yes let's go okay so we want to set up to the first world mr. face case we just have to do that's the last one you know now we actually could be true before well first of all children is equal to 20 go class before such a or so it's take the minimum from the one that's under or the 100-200 100-200 100-200 right okay I think that's it - let me teach my I think that's it - let me teach my I think that's it - let me teach my train so now one spot was today there another way to do this I think where you just use a two-dimensional or like a just use a two-dimensional or like a just use a two-dimensional or like a yeah matrix with two elements in any kind of smoke them right I think this one just way slightly clear basically we do and this is a maybe see specific but it's uh it this way I should be well but yeah but this just swapped a pointer so you could kind of we use the same erase I mean you could do that in Python - it's just swapping references so it's - it's just swapping references so it's - it's just swapping references so it's not specific I guess actually okay so you want to be turning currency all kind of is its kind because I think that doesn't move zeros as well do you like maybe Ines figured I got sick for something that's coming universe but I might not have added one thing hmm it's even a better path I think I just didn't add to at the end I mean that's the answer for because we swap the current so that current is actually the last one percenters what I do before action should work that's the way one element that we tested I never prints maybe there is stuff crashing empty away okay then maybe I don't need this an imprint okay I'm missing that case huh just fix it I'm a little lazy think about everything okay cool yeah so this is kind of the UH actually way related to what we were just talking about obviously a easy example to understand because you could actually think about was if you would do it kind of top-down was if you would do it kind of top-down was if you would do it kind of top-down then you would definitely need an and square matrix to represent or these you know each of T's and even with Bottoms Up you could have easily done it with two-dimensional matrix but this allow us two-dimensional matrix but this allow us two-dimensional matrix but this allow us to kind of because we only we know that you only care about the on top or on the bottom of the way I did actually but I don't top on bottom then like yeah you only so you only need to know the content but that's well so you don't have to over allocate memory for stuff like that cool that's kind of that next funny term for this one this is a relatively straightforward problem I mean I think this also is one of those canonical dynamic programming problems so that's why I'm able to get it very quickly and hopefully I get that feels good having one cool thing I want to point out is that I actually implement not just per se but a similar thing like maybe I want to say 10 to 15 years ago actually comes up in a real world thing well but some definition we were anyway you're interested in all of these stuff is the if you have a play around with like Adobe Photoshop or something like that where you take an image and then you kind of resize it either squeezing that say squeezing them together right and squeezing them together you know there's obviously the story scale is a one way you could do the resizing you just kind of squish shrink together another cool thing that they cause I was at content aware okay I tried to content a real content sensitive but we have a name and a core these days but can't let's say content-aware resizing and let's say content-aware resizing and let's say content-aware resizing and what that happens what happens there is that and once you kind of familiar with this problem is that it actually takes a shortest minimum a minimum cost path from the top and the bottom or to the bottom and then delete that path so and the cost function yeah you can play around with it and I think they tweak of it over the time but a really naive cost function is just like well look at your surrounding colors like you want to know one basically a cost function that is as similar to the cost of the new by ourselves as possible and trust they doesn't do English it means like let's say you have nothing but blue skies then yeah then you your assumption is that no one would miss it that much if you miss like a sliver blue sky right like versus if you take away I don't know say half my face or something or like two three columns off my face then like you'll notice that I don't have a nose or something right I don't know so that's kind of the idea between that behind that and that just as you can imagine finding a minimum cost path from the top to bottom using this cost function guide is using dynamic programming and that's actually one of the cool like earlier things that I learned about back in the day oh my god yeah wow you actually do your standard vogue wearing these things and I definitely worked like playing around some projects on that it's kind of cool I guess nowadays everyone takes all these magical things for granted but like the image manipulation and stuff like that cool yeah I think this is a waste and applause oh I very much whatever expected this is yeah expected on an integral I would say long day and I don't really have much of a forum I think I keep saying postpone it but I mean retro just cause actually like this is where to be straightforward
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
588
in this video we're going to take a look at a legal problem called design a memory file system so basically the goal is we want to design a data structure that implements or simulates an in-memory system or simulates an in-memory system or simulates an in-memory system file system so implement this file system class that supports these following functions so in this case we're basically have a constructor that initializes the object the system and we also have this ls function basically do couple things here so if the it takes a path right in a string format and if the path is a file path right returns a list that only contains this file's name okay and if it's a directory path we want to return the list of file and directory names in this directory so the answer should be lexical graphical order basically we want to return a list right of string that contains either the file name if it's a file path if it's a directory path we want to return all the files as well as directory names under the current directory right in sorted order of course um and then you can also see here we have mkdir it takes the path and then it makes a direct new directory according to the given path so the given directory path does not exist if the middle directories in the path does do not exist we should create them so basically what we're going to do is that we're basically just going to create this path right this path um so for example if we have something like this we want to create a we want to create b we'll create c each of them is our directory and then b is under the a directory c is under the b directory right so and then we also have add content to file so it takes the file path and content so what we're basically doing is we take this file path that's already exists right if the file path does not exist create the file path containing the given content but if it exists we basically just uh appends the given content to the original content right and then we also have another function called read content from file so this takes a file path returns the content in that file right so the file path should be existed okay um so you can see here we have an example right so initially we initialize the class uh we create instance of this class and then in this case we're calling this ls function we basically passing a directory in this case is the root directory there's nothing under this root so we return a list right empty list so then we create this path so we have abc so in this case we created directory a create directory b is under a c is under b right and then in this case you can see here is a void function we're not returning anything so once we create this directory and then we're going to add a content add content to this to the file in this case it's abc and then we are creating the last one right there is d that's basically a file right this file basically we have a content that we're going to append on to it right so you can see here uh this is the file name and then this is the content so we're basically creating that right and then you can also see fs uh sorry uh ls we're basically going to call this function we are getting this directory right which is under the root directory so only directory a is in the root is in the directory root right so then if i want to read content from the file you can see here it will return as hello right because here you can see d we already assign hello there so the output is the file and content and then you can see here the constraints is that we're guaranteed to have path and file path our absolute path which begins with this not end with this except the path is just this right and you can see here that you can assume that all the directory names and file names only contain lowercase letters and the same names will not exist in the same directory uh you can assume that all operations will be passed as valid parameters and users will not attempt to retrieve file in the content or list of directory or file that does not exist so basically a couple of things that i want to clarify for this question first of all for each and every single path right either a path or a file path you can see this is our path right this can be a string right this can be a long word it doesn't have to be one character i didn't really know that when i first tried to do this question so in this case like for each directory or for each file name i could have more than one characters right i could have slash a b c d slash d uh b c d or whatever like it could be a long words it doesn't have to be one character so that's one thing now the other thing that we have to pay attention to is this add content to file function um the other thing that we have to pay attention to is that when we're creating this when we're at content to this file maybe we have to create this directory or we don't right we append the string onto the content that we have already onto this current existing content right if there is content for this file right for this file d then we just have to append hello right after that content right if there is not if there's no content then we just have to put this as the content for this file right so basically this ad content doesn't mean that we have to replace what we have before right for this file or basically just append this content onto uh what we have in this file right so that's another thing that we have to clarify um so other than that um let's take a look at how we can be able to solve this right so of course like the brute force approach will probably be that we are just going to store each and every single path onto like some kind of like a table right and let's say if i want to you know for example if i want to create a directory i will just say this is the path and then i'll i will create it in our table right and then add map or at content i'll just same thing i would just you know create it and then just return and then just add it onto our table add a row onto our table right but let's say if i want to do ls in this case if i want to find all the file uh all the file path or all the directories um under the current uh path then i have to check for each and every single rows right each every single um keys prefix to see if it match so in this case what we have to do is we have to go to our table and then for each and every single key we basically have to check for um you know for its prefix to see if the current path um is the prefix of our current key right and then if our current key is a directory right is it there's a directory under this path right so in this case you can see we have to iterate through the entire table to do so what we can do instead is we can basically use a try data structure right to basically avoid checking each and every single keeps prefix in our table so in this case let's say this is our path right we want to create this you know we want to create this path in this case we can basically have a try in this case let's say this is our try right uh you can see this is one file or this is one directory and then you can see that there's two directories under this directory so in this case you can see we can basically use a try to uh store our files right our directories uh in a trial in a try right in this case let's say the last one right here let's say this abd is a um it's a file right what we can do is that inside our try class right what we can do is that we can have a variable called content right if the content is initially content is null if it is not null basically we know that this node right has a content right so in this case if i want to um basically realize that this node has a content then we can just return a list only contain the file's name right if the path is a directory path let's say this doesn't have a content right let's say b doesn't have a content it's not a content uh or not a file path in this case what we can do is we can return the list of files and the directory names in this directory so in this case we have c and d right so in this case i'm going to show you to approach how we can solve this problem but for each approach i'm going to talk about the pros and cons for each of them so you can see here that what i'm trying to do here is inside our file system classes that have a root which is basically the root node and then you can see we have a trinomial and this trinode you can see here we have two variables so one is the contents initially we have null and then we also have children in this case we have a table that keep track of uh kernel's children right the string is basically the current directory's name and then we have trinode which is basically the chosen right um of that directory right so and then you can see here we have our ls function we takes the it takes the path and then basically what we're trying to do here is we're trying to get to the correct node right so let's say the path is equal to a b right let's say if the path is equal to slash a slash b then in this case we're going from the root we're going down to a and then go down to b right we want to get to the last node and then once we're at the last node what we're going to do is we're going to get all the keys that we have for this node and then we're going to sort it right because we want to you know we want to have a uh return a list that is in lexical order right we're basically in a uh increasing order uh sort of increasing sorted order right for our string and then we're returning as children right and let's say if the path does equal to you know this thing right which is still okay like we're basically at the root and then we're just going to return you know the currents all the children for the current node right in this case it's just a right and we're basically add a onto the list and then we're returning that right we're sorting and returning that right and then if i want to create a directory in this case it takes a path and then what we're going to do is we're going to split by this string right and then basically here you can see we're basically starting at index 1 because if we are splitting by the uh you know the slash that in this case the first index right the first element in the array is basically going to be empty right empty string and then what we're going to do is that we're going to start to traversing the tree right starting for traversing to try so we have current string array at i and then we check to see if it contains if it doesn't contain we create that in that uh create that element in the table and then we're basically traversing right so in this case let's say if the path again if it's abc right we're going to start from the roots go from here and here right pretend that you know bc is not there before right so that's we're basically doing and then at the end you can see we also have another function add content to file which is also pretty easy right you get an idea we're basically creating that path if it's not there and then if current.content is not null and then if current.content is not null and then if current.content is not null then we basically just add that content out the current content onto it if it's null we basically just set the current node's content to be content for reading content from the file it's pretty much similar right we're basically get to that node and then what we're going to do is we're just going to return the current node's content right so that's basically it which is pretty simple but you can see that the core function is here right where basically you can see the time complexity for this right well basically when we try to get to this node in this case it's basically just m right m is basically how many uh or basically the longest path right or the path right is basically it's basically the path that we have the traverse right we basically have to traverse each and every single uh kind of like each and every single string that we have in our path right or in this case if we want to traverse each and every single directory right in our path once we get to the last directory we have to do our sorting right and this current directory could have many directories under this directory so in this case we have to perform a sorting in this case is going to be depends on how many elements that this directory has right let's say we have k number of elements then it's going to be k log k right so you can see the time complexity for this is basically going to be m plus k log k right so in this case you can see here um this is basically the time complexity for this and then for other functions right um basically you can see that we're basically just going to um going to create this directory so it's going to basically m right basically m is basically the size of our path same thing for this one as well as this one right basically we're traversing down this file path or directory path and then we're you know changing some stuff right um and then that's it but let's say but there's also another way we can solve this problem to use a tree map right a tree map basically is kind of like a hash map but we're basically just going to keep the tree right keep all the elements in our tree in a sort of manner right but time complexity for you know adding elements removing elements and then checking to see if key exists is going to be a log in right because this uh this tree map basically uses and basically you can see that the tree map implements red black tree which is basically a self-balancing binary search tree self-balancing binary search tree self-balancing binary search tree right and we know that for insertion and deletion in binary surgery where binder tree is basically just going to be log in so therefore if we were to solve this problem using a tree map right um the time complexity for you know insertion and delete and reading elements or basically traversing down this path right for example mostly those two functions uh add content we basically if the current node doesn't have the string then we basically have to insert it right which is basically a login or log k time complexity right um and then you can see here k is basically the size of our current nodes tree map size right and then we basically have to traverse down this file path and but for this function in this case because this is already sorted we're basically all we're trying to do is we're trying to go down to the correct path and then we're just going to get its children so you can see that time complexity is basically just m which is basically how many directories that we have to go down to right so you can see that each and every single solution has its pros and cons if we're using entry map for insertion it's basically going to be a you know kind of like m times log k and then for ls function in this case we're basically just going to have m right or bagel of m right because the tree battery is already sorted and all we have to do here is basically just getting its children right so that's basically how we're going to solve the problem and thank you for watching
Design In-Memory File System
design-in-memory-file-system
Design a data structure that simulates an in-memory file system. Implement the FileSystem class: * `FileSystem()` Initializes the object of the system. * `List ls(String path)` * If `path` is a file path, returns a list that only contains this file's name. * If `path` is a directory path, returns the list of file and directory names **in this directory**. The answer should in **lexicographic order**. * `void mkdir(String path)` Makes a new directory according to the given `path`. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well. * `void addContentToFile(String filePath, String content)` * If `filePath` does not exist, creates that file containing given `content`. * If `filePath` already exists, appends the given `content` to original content. * `String readContentFromFile(String filePath)` Returns the content in the file at `filePath`. **Example 1:** **Input** \[ "FileSystem ", "ls ", "mkdir ", "addContentToFile ", "ls ", "readContentFromFile "\] \[\[\], \[ "/ "\], \[ "/a/b/c "\], \[ "/a/b/c/d ", "hello "\], \[ "/ "\], \[ "/a/b/c/d "\]\] **Output** \[null, \[\], null, null, \[ "a "\], "hello "\] **Explanation** FileSystem fileSystem = new FileSystem(); fileSystem.ls( "/ "); // return \[\] fileSystem.mkdir( "/a/b/c "); fileSystem.addContentToFile( "/a/b/c/d ", "hello "); fileSystem.ls( "/ "); // return \[ "a "\] fileSystem.readContentFromFile( "/a/b/c/d "); // return "hello " **Constraints:** * `1 <= path.length, filePath.length <= 100` * `path` and `filePath` are absolute paths which begin with `'/'` and do not end with `'/'` except that the path is just `"/ "`. * You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory. * You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist. * `1 <= content.length <= 50` * At most `300` calls will be made to `ls`, `mkdir`, `addContentToFile`, and `readContentFromFile`.
null
Hash Table,String,Design,Trie
Hard
146,460,635
373
friends today I'm going to solve liquid problem number 373 find gay pairs with smallest sums so in this problem we are given two integer arrays nums 1 and nobster and it is sorted in ascending order and we are also given an integer k now um here what are we going to do is we are going to form pairs where U is from the first array that is number one and V is from nums 2 and we are going to form Cape such Pairs and those K such pairs should have smallest sum so U1 plus V1 should be the smallest sum U2 plus V2s would be the second smallest and so on so basically we need case such sums whose um some of the pairs is the smallest of all of the others okay so let's look at this example here so what are we given is let's say let's stay here and look at the example all right so we are given nums one and Norms to end the value of K is equals to 3 which means that we need three such pairs with the smallest sum now since we already know these two uh array are sorted in ascending order so the first two will always be the smallest number which means that the first two of these elements will always be the smallest one so if we take the pair one two the sum is always going to be the smallest which is equals to 3. now let's take the next pair so if we take one and if we take four that would also be the smallest one right because it equals five now like if you are taking 7 and 2 that's equals to 9 which is greater so instead of taking seven two what we do is we take one and four now we are also taking the sum 1 and 6 here so let's see here one six and this gives us equals to 7 which is again smaller than 7 and 2 right so basically what are we doing is we want the smallest sum so we are taking the sum of one and two sum of one and four sum of one and six we are also taking the sum of seven and two seven four seven six and so on so if you were to perform Brute Force we would take each of the elements from here and take some with each of the elements over here and then um find the smallest K element so for that basically we could use mean Heap Okay so let me just show you over here so that I can draw the solution and it would be easier for you to visualize so let's look at the Brute Force solution so here we have one seven eleven and next we have two four six okay so if we had to form pairs basically in Brute Force we will come take one two one four one six right so that will get give us pair one two one four and one six now we have these pairs in the next uh step what we will do is next we'll take other pairs seven to seven four seven six so now when we are taking the next pair that is seven to and seven four and seven six and then similarly we are going to do with 11 so we are going to take the pair with all of them okay so eleven Two Eleven four and eleven six so basically we are taking each of the elements and uh taking period each of these so this would be n times n okay now we also need to get the smallest one right so this is how we actually form pair now we need the smallest one so we could actually use uh mean hip for that one so what does mean he do is the top root will always have the smallest value and the rest of the nodes will be larger one so if we do mean hip then the minimum sum of all of these would be equals to what is the three right this will have the minimum sum so this will be at the top so basically we could DQ these Top Value and then we can add to our result the pair so we would know that this is our result and then similarly next these would be our least smallest right so it will always be on the top so basically we need a main Heap I mean hip to find the minimum one okay so now this here we are doing n by n times so now is it necessary for us to do it n by n number of times to find the minimum let's look at this example one more time so that we can optimize our solution so okay so here we have one and two let's take the first two so the first two will always have at least some why because these two are the least of all the elements so these two sum will always be the smallest so the first two we always take the first two and we are adding the sum to our Q so um the sum is equals to three so we are adding this to our Q okay um okay let me write it this way so we actually do not even need the sum we are just going to insert these two pairs and the index of this one so I'm com taking one and two only so the index is equals to zero now next what I'll do is I'll move to this next value which is 7 and I'll only compare it with two so I'll only take the pair with the first element in the second one so one with two then seven with two so that would be seven two and the second index of this at the second error which is zero we are only taking index 0 right and now eleven so eleven and then two and then index 0 right so now among these obviously this is the smallest one so we'll get the mean value from our mean hip because like we have already inserted this in our mean hip and compare the values okay so once the mid hip is now created what we do is next we have one and to know what we need to compare one with four as well right so we pop this out we enqueue this from our priority queue from our mean hit priority queue and then now we look at this Index this index is equals to zero so since this index is equals to zero which means that I'm comparing my element from the first array with the element at index 0. now I also need to compare with the next element which is 4 so I now in q1 4 and the index of 4 which is 1 okay so now that I have added to my queue now my mean hip will have this value as the minimum one okay so in the next step what happens is when I in queue these I will have the index one so this one index will be as the minimum so we have 1 4 we have one two and one four now I will the next minimum value would either be 1 6 or it would be 7 2 right so since I found 1 4 as the minimum so next what I'm going to do is I'm going to in Cube one with the six that is the next index in the array to write its at index two so now encute this one now among the rest of the values that is these values in my priority queue which is the smallest one this is the smallest one right so I enqueue this and basically I am in Q indeed I'm adding all of these to my resulting area while I'm enqueuing those and when my resulting error length is equals to K that is when I stop in queuing because I already have the result and that is when I return my result so in summary let me summarize here once again what I have doing okay so what are we doing is first of all we always compare one to two because one two will always be the smallest one the first two elements are always smallest so the sum will always be the smallest so we take this one now we could either take these two or these two right so among these two which will be the smallest one of course it is one for right so that is why we take one foot so now that we have taken one four now the smallest one who could be either these two or these two right we already have these values so that would be either the smallest value in this and the next smallest here which is 6 because we have already taken that or the second smallest and the smallest one here so between these and these so of course here 1 and 6 is the smallest among between seven and two so that is why we take one and six so that is how we are actually doing it so let me just uh take another example here so I'm just going to make few changes to my example okay so now that we have these examples so I have one seven I'm just going to paste it over here and the next one is this one so I'll paste it over here as well so now we have these two arrays okay so how are we now going to perform our Q function okay so as we already know that the first two small are always smallest so we already have one and two now next we would take either one and 10 or 7 and 2. right so we are basically one we have one two now we are all only incrementing this index right this index and this seven and two we already have it in our list also 11 and 2 we already have it on in our list so now between these two which is the smallest one plus ten eleven seven plus two is nine so here I take seven and two so now in this case now 7 and 2 was taken so the next index would be 7 and 10 okay now between 1 and 10 and 7 and 10 which is the smallest one and ten is the smallest right so I take one and ten as the smallest one which is equals to eleven so now my next comparison would be between 1 and 11 and 7 and 10. so between 1 11 17 which is the smallest one 11 right so I'll take one eleven now since I'm done with one the index for one so in the next step now we have 17 right and now we have in the array I mean in the priority queue we already have 11 and 2 so we are actually comparing now 17 with 11 and 2 and between these two which is the smallest 11 plus 2 is equals to thirteen seven plus ten is seventeen so basically 11 and 2 right so this is how we would be performing our operation and for that we already have like inserted each of these elements which is of the first one and then now based on which element we took did we take this one if yes then now we are going to increment it we are going to take the next value and then compare that next value with the um remaining with 7 and 10 and so on so that is how we are doing because like as we know as we could see like it only matters like in this way like one ten seven to only cross-sectional one ten seven to only cross-sectional one ten seven to only cross-sectional wise so that is why we are performing it in this way so now that we know how to solve this problem let's uh start coding so for that what do we need a mean priority queue right mean priority queue we need a list we need an array list to store our result and that's all that we are going to need so let us first create a mean priority queue so priority Q equals to um mean priority queue and then here we are going to perform our comparison operation so compare and here what we're comparing is between the two um two elements in our list in our priority queue we take um some of a0 A1 so a0 is the first element from Norm Swan A1 is elements from nums two okay and we need the smallest one right so b0 my plus b one so between these two we are going to get the smallest one the compare function will return as that and now we are going to push to our prior to Q so I less than numbers one length I plus and then um priority q that push I mean NQ okay so we are going to enqueue into our priority queue the value add numbers at index I and nums to add index 0. so each of the element at index I mean each of the element at norms one with nums 0 and the index of okay and now next let us create a result array where we are going to store our result and now let us iterate over uh each of the values a while K is greater than zero and while our mean hip which is our priority queue is not empty we keep on performing our iteration so for that one now we are going to in queue I mean DQ so we need the first element is let us just write x y and the index of A2 okay that represents index of the index at nums to array right which is equals to prior to Q dot Q DQ okay so now that we have the element we are going to insert to our result push to our result the value X comma y because the priority queue will always return the smallest value from when we DQ because it is a mean priority queue right now next what you are doing is if um I2 is less than the last element I mean nums to that length minus one that is when we are actually going to know in Q2 hour mean priority queue so e n q let me just copy this thing here so we are enqueuing what we are just going to take this value only and now for the nums 2 we are going to take I2 plus 1 because we are incrementing our index for Norms 2 plus 1. so this would basically give us the comparison between like here as we uh we found the smallest one to write 1 2 means two is at index 0. so next we uh we already have one two we had one two one seven not one seven actually so next value is 7 2 and the next value is 11 2 in our mean priority queue okay so since we already have these values we decute this now we are going to insert a new value so the new value the most appropriate candidate is the next Index right that is the value next to two so that would be 1 and 10. so we are taking the same value for nums one that is X and for y we are incrementing the index by one so that's what we did here we are taking X as it is and we are incrementing norms to Pi upon index and that is what we are passing here and finally we are going to also decrement the value of K so while K is greater than 0 it will run and once K is equals to 0 we are finally going to return our result okay so now let's try to run it okay so here's something wrong all right now let's run this okay so something went wrong here I need this thing here it's still giving me wrong answer undefined what did I do wrong because and then here we are in queuing this right which is Norm's one at the index I and Norms 2 at index 0 and the index of norms 2. and then here while K is greater than zero and the priority is not empty we are dqing and then we push our X Y value and while I2 is less than nums 2 okay this would be numbers to the length because that's from indexed nums to this index represents index at norms 2 yeah now let's try to submit this great so yeah this is how we could approach this problem using mean priority queue um let me know in the solution in the comments down below what do you think about my solution yeah thank you
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
1,559
uh hey everybody this is larry this is q4 of the recent lego daily uh sorry lego contest from the bi-weekly the bi-weekly the bi-weekly uh detect cycles into the grid uh hit the like button hit the subscribe and join me in discord and let's go over this problem together um oh and you could watch me stop it live during the contest afterwards so i think this one is maybe it's not so interesting um but yeah for this one most of my time was spent just thinking about the farm uh once i figured it out i think it was okay um so i don't know how to attack this problem it feels very one-off it feels very one-off it feels very one-off uh because for me for these kind of problems i always try to think about how to um how to you know build reusable components if you will to kind of figure out how to learn so that i can you know we use another case um i think for me the biggest thing and i had a piece of paper just to figure out different cases uh and i was just thinking about maybe different cycles of like length four and then whatever right and a naive breakfast or sorry now if that first search is not going to be fast enough because given that uh each side is 500 they could be up to 500 square cells uh which is 25 something 20 or 50 000 something like that um but too big if you do uh exhaustive search right um so the way that i thought about this uh during the contest was that uh well because in this case we don't have to return the length we don't have to minimize anything uh we only have to get the binary we solve true or force right so there's actually um so that means that at any time you're able to go to uh a word text that you've always seen before then that means that there is a cycle almost like um you know the classic linked list with a little tail sticking out but you don't care that has a tail you just carry that as a psycho right and apologies for not having visualization on board uh because i don't know i have to set it up on this computer that's my fault but yeah so that given that uh visualization of just having like this uh you know the classic cycle in the linked list uh except for in a 2d grid version uh then now you just have to uh check that it exists right um and the only thing that you would do if you're doing naive that for search um is that you know there is a trivial case where there's a trivial two cycles right uh a two cell cycle is just if you go from cell a to cell b and then back to a right like right um so the way that we prevent this is by doing something that i actually do in trees now more and more uh because someone taught me this at some point actually like recently well like in the past year uh but is by keeping track of the parent cell and then not going back as long as we so then now you can imagine the recursive call of just like going down and also i shall make sure that the recursive stack is enough i guess in this case they expect you to they did it for you uh because now i realize that i might have messed up if uh it gives me a recursion limit but yeah so now you could look at the you know if you're able to visualize the different search graph um then you should be able to uh you know look at just going down the list without going back his parent and as long as you're able to if as soon as you find a note that you've visited before that means there's a cycle otherwise it's just a straight line uh or linked list even if you want to call it that of uh you know that would be a risky path right and as soon as you see a note that you've revisited that means that you're already you know being able to loop around because you don't go to your parent um and in a way it's um it also is similar to like bridge finding and stuff like that so definitely it is a problem that uh comes up a bit more often on competitive programming but maybe not so much to be honest on interviews but yeah uh so what is the complexity of this right well we look at each cell at most ones or at most constant number of times um because you know you go look at neighbors so maybe it's like four times the number of selves but still linear in the size of the grid uh being n times m so it's going to be o of row times columns and that's the space complexity as well because we keep a visited matrix for that uh and yeah i think that's all i have to say about this problem we'll go over the code real quick uh but basically i just you know see if i could start uh a cycle from or just start a chain from a current cell uh and for every cell i well first i mark it as true so that in the future if you come back to it then you know there's a cycle uh this is also like how you this is almost uh actually now that i think about it this is like red uh breadcrumbs in uh in um in a maze or something like that right that's like the classic greek myth or something like that where you know well i guess they also tie themselves i think but if you leave breadcrumbs in a maze and as soon as you see a breadcrumb again you're like well uh i've been here before right so that means that there's a cycle you've made a loop uh that's basically the same idea here uh you look at you know you look up down left right and then you make sure that it's within bounds you make sure that the color or the letter is the same so that's a valid path and if it's not your parent and you visited before then you just mark it as true if not then um you know you do the recursive call actually i think actually i quite could have terminated a little bit earlier but that's okay uh well at least i got a little bit lucky with time limit exceeded uh when i was solving this i definitely wasn't sure that it was going to be fast enough to be honest but uh but it should have been it's just that it's always unclear with v code sometimes with like random hidden constraints uh but yeah that's all i have for this problem hit like button hit the subscribe button watch me stop the video next and yeah bye hmm so um hmm this so hmm oh god so hey everybody uh yeah thanks for watching the video this is probably after you watched uh the live portion of the salving during the contest uh hit the like button there's a subscribe button join my discord and i will see y'all next contest bye
Detect Cycles in 2D Grid
cherry-pickup-ii
Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`. A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the **same value** of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell. Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`. **Example 1:** **Input:** grid = \[\[ "a ", "a ", "a ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "a ", "a ", "a "\]\] **Output:** true **Explanation:** There are two valid cycles shown in different colors in the image below: **Example 2:** **Input:** grid = \[\[ "c ", "c ", "c ", "a "\],\[ "c ", "d ", "c ", "c "\],\[ "c ", "c ", "e ", "c "\],\[ "f ", "c ", "c ", "c "\]\] **Output:** true **Explanation:** There is only one valid cycle highlighted in the image below: **Example 3:** **Input:** grid = \[\[ "a ", "b ", "b "\],\[ "b ", "z ", "b "\],\[ "b ", "b ", "a "\]\] **Output:** false **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid` consists only of lowercase English letters.
Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively.
Array,Dynamic Programming,Matrix
Hard
null
1,981
hey what's up guys this is sean here again so uh list code number 1981 minimize the difference between target and chosen elements okay so this one is pretty straightforward basically you're given like i'm the m by n integer matrix and the integer target so your task is to choose one number for from each row right and then you got a sum for all the number you have chosen and you want to minimize the difference the absolute difference between the target and the sum right so that's it so for example we have this matrix right so we can choose one five seven uh where the sum will be 13 right and the target is also 13 that's why the answer is zero right so for this one no we don't have any other options right that's why we have to choose these three numbers and the absolute difference is 94. okay and for this one right this one is seven right because seven minus six is one and then we have some constraints so see we have uh we have 70 right and 70 and then the target is 800 right so since you know since the constraint is not very big we can probably just use like what the uh some kind of brutal force way to solve it but we also we still need to use the dynamic programming basically you know like i said since the m times and this one is also within 70 so what does it mean it means that the total sum in the end will be less than what would be less than 70 times 70 right which is four thousand nine hundred right because for each row we the biggest number is 70 right then for 70 rows that's 70 times 70 right so basically that's the total number of different sums we can get right so which means we can simply just use this one right as part of the state and the first one obviously should be the row right so basically we can have like 2d dynamic programming right wait where basically the first state is the row and the second one is the sum okay right and then in the end we simply just we just need to get the minimum uh of the stp state uh let's start coding yeah i'll explain more so the state transition function is very it's very straightforward right so like i said we have 2d state the first one is the row right the current row and the second one is the basically the current sum right that we have already picked right then we have this cache right thing so what's the base case right so the basic base case is this so basically when the rows reach the end okay you know what let me m is going to be the length of mat right so when we have reached the last row right we just return the absolute difference right between the sum and the target so that's the basic rules right and then so the state transition function is like this right like um and then for num okay in math row right so for each row no we do the answer equals to minimum right of the answer dot dp of row plus one then the sum plus number okay and then we return the uh the answer right and then here we return the dp of zero and zero okay so that's how that's the basic implementation so the way see so we have this 2db state right basically it means that you know if we could uh the reason we're using dp here is because you know we could end up with from multiple uh path right okay let's say this is the path so let's say this is the path let's say we go here right and then we go sorry not here like this one right and then here let's say this two path right will end up with the same state which means that you know the numbers we're collecting from this one and this one will give us the same sum right in this case we don't have to calculate this dp we don't we can only just use one after the path we don't have to calculate the remaining parts multiple times right that's the reason we use dp right to remove the duplicate path okay and but this one would will fail tle you know um i think the reason is that you know even though the see we have 70 so let's take a look at the time complexity for this one right so the dp time complexity and how to analyze it analysis analyze it is the total number of the states right multiplied by the time complexity for each of the function uh for each of the dp call right so how many states we have let's say we have n right so let's like this 70 right so we have seven we have n times sum right like i said the total sum the possible number of sums are like what is n squared right because we have already talked about that and then inside of the dp function here this one is also n right so basically it's going to be n to the power of four okay 70 to the power of four um this one i think it's about two million right now for some reason this one tle it couldn't pass so which means we need to do some improvements or like work called pruning right so what can we do so first thing is that you know we can always remove the duplicate right the duplicate for each of the row right so that's the first thing we can do which means we can do this right for i in range of m right we have a match i equals to the set we can simply do a set of the match i right so that's how we remove the duplicate but this one's still tle and what's another thing we can do you know what we can improve is that you know we can sort you know because first you know we uh all the numbers are positive right so which means that you know if the number if the sum is too big right basically if by the time let's say we have a lot of rows here right so let's say we're trying to process this row right now let's see after picking this number let's say this number is four right this total sum has already exceeded the target right and then let's say for example this row also have like some 6 7 and 10 right then obviously we don't need to we don't have we don't need to try 6 any number that's greater than 4 because 4 plus the sum has already exceeded the current target right so we can simply stop that right so which means that you know in order to accomplish that we can just sort each row so that we process from the smallest to the biggest right the moment the current sum has already exceeded target we can simply break the for loop which means we can simply break here right so that we don't have to try six seven and ten we can simply stay with it's four and then try the remainings okay right so uh to sort uh we just simply need to do a little bit modification here which do a sorting of that of the set right then we'll have like sorted list here and here basically if the sum plus number right is greater than the target okay right i think either great or equal it's fine yeah it doesn't really matter i think and then we break right so that's it so now if i run it let's accept it yeah there you go right so it's not that fast but it passed okay yeah i think that's it right i mean that's the uh kind of standard dp problem with two state uh plus some pruning to pass all the test case yeah i think that's pretty much everything i want to talk about for this one and thank you for watching this video guys and stay tuned see you guys soon bye
Minimize the Difference Between Target and Chosen Elements
maximum-transaction-each-day
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13 **Output:** 0 **Explanation:** One possible choice is to: - Choose 1 from the first row. - Choose 5 from the second row. - Choose 7 from the third row. The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0. **Example 2:** **Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100 **Output:** 94 **Explanation:** The best possible choice is to: - Choose 1 from the first row. - Choose 2 from the second row. - Choose 3 from the third row. The sum of the chosen elements is 6, and the absolute difference is 94. **Example 3:** **Input:** mat = \[\[1,2,9,8,7\]\], target = 6 **Output:** 1 **Explanation:** The best choice is to choose 7 from the first row. The absolute difference is 1. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 70` * `1 <= mat[i][j] <= 70` * `1 <= target <= 800`
null
Database
Medium
null
920
hey everyone welcome back and let's write some more neat code today so today let's solve the problem number of music playlists this is definitely a difficult problem and I would take a couple extra minutes maybe even more than that to really understand it because I made a mistake in understanding the problem when I tried to solve it so let's go through that it's a very mathematical problem we're given n unique songs and we want to build a playlist of this target length that's called goal and that's the term I'll be using as well though maybe you want to use a better term like maybe even length would be a decent term to use the interesting part are the restrictions that we have to have on that playlist we have to have every single song included at least one time so you can imagine that our goal is going to be at least greater than or equal to the number of unique songs that we have and if you read all the way at the bottom of the description of the problem that is stated but this is probably the more interesting restriction and that is that a song can only be played multiple times like we can only repeat the same song If K other songs have been played I think this is worded pretty poorly first of all they include the word only twice and you don't need to do that's redundant the way this sounds is that if we've chosen K songs like let's say k is equal to two and we chose a song one and then we chose a song two that now we should be able to repeat any song like we can repeat one or maybe two as long as we have at least K songs at the beginning that's not the case this is not the case what this is actually saying is we can only repeat the same song If K other songs have been played meaning that if we have a three here now we can repeat the song one because K songs have been played since we last had a one so here we could put a one and then after we do that we can now put a 2 over here because we have that Gap here we can't put a 3 because there's only a gap of one we need a gap of two because our K is 2. so that's what this problem is saying that's like the first step to actually being able to solve it took me a long time to realize that now even knowing that this problem is still not easy but we can kind of start to solve it first of all this first example is pretty trivial it's not going to help you understand the entire problem this is just basically permutations in this case the K doesn't even matter because we have three slots that's how I see the goal number like we have three slots that we need to fill and we have exactly three unique songs so a unique song is going to be included in exactly one position so this is basically permutations it's three times two times one the way I'm getting this formula is because we have three songs to choose from so in the first position we have three songs to choose from if we already pick one of those songs now we have to still fill in two more unique songs so how many choices do we have in this spot two how many choices and then would we have in this spot one so this is just some basic math background but this is not nearly enough to solve this problem this is just permutations and that's going to lead us to an answer of six it works for this example but it's not going to work for many of the others where our K value actually matters now this example while it's pretty simple you might be scratching your head to figure out like the algorithm to actually arrive at the solution so I think it's a pretty decent example to go over but in this case we have three slots that we are trying to fill we have exactly two unique songs and in this case the way this example is using them is basically song one and song two that's fine of course we don't actually have to build the playlist We just have to count them and I guess I should cover that we're gonna count the total number of possible playlists that we can create and we're gonna mod that number by this Prime number because it could be a very large result but just because we're using these semantics doesn't mean we're actually going to need an ID for each song we actually don't we're just going to count the number of songs and we're going to use a little bit of math to do that and of course a little bit of recursion and the reason we need to do that the reason we can't just write like a formula like I kind of talked about with the permutations is because first of all there is like this restriction here we can in some cases repeat the same song keep that in mind because it's really important but also we have n songs and we have to use every single one of those at least one time that's also going to make this problem hard it's why it's not so easy to just write a math formula for this problem so initially the logic is pretty simple for the first slot we can choose either one or two so it kind of seems like we have two choices initially and then for the next spot we kind of have two choice is again we can either put a one or a two so drawing out that decision tree we'd get this and you can see each of these kind of does exist like one you can see is in this first playlist and one two that prefix is in this playlist it's also I think in this one as well two one also exists here and I think here as well two it looks like exists here but now when you take it one step further we basically realize we're just creating every single possible combination now the reason this doesn't work is because that first thing we have to use each song at least one time so here when you do all of these you're gonna end up with eight different playlists because that's how many like Leaf nodes we have here and you realize the solution is six so where did we go wrong like this is not straightforward at all well the first thing I'm gonna do is I'm not just going to count every single leaf node we're going to have some kind of restriction or a better way to put it would be within our recursion we're going to have some way to filter out some of these and the best way to usually do that is with a base case so the base case that we are going to use is first of all we expect every playlist to be exactly of length 3 in this example at least so that's pretty easy to do with recursion but we also expect that the number of unique songs used is exactly equal to two in this case at least or whatever the end variable happens to be so we need to kind of keep track of the number of unique songs that we use like in this path clearly we only used one unique song so if we're keeping track of the number of unique songs how do we do that's the number one question and perhaps you'll be able to figure it out you can maybe even stop watching this video at this point but I'll tell you it's actually not easy to do even if you can make it this far the thing is as we choose like initially we haven't chosen any songs yet so no matter what we choose we're choosing a new song AKA a unique song I'm Gonna Be referring them to though as new or old songs a new song is one we haven't chosen yet and an old song is one that we already chose previously so we can choose a new song here and a new song here can't really choose an old song yet not just because we haven't already chosen a song so literally there aren't any old songs for us to even choose from but also because we're not allowed to repeat an old song Until K songs have already been chosen now K is 0 in this case so that doesn't really matter but you can kind of see there are multiple angles to this right like this is why it's not a straightforward problem there's multiple things you have to keep in mind one once we've chosen a song we know that we need three songs like here we needed three or here we needed three actually but after we've chosen one like over here we need now two songs like my handwriting is pretty bad but I think this is a pretty simple point and then at this level we would need one song and at this level we would need zero songs and that's how we know this is a base case that part again is pretty straightforward but the part where we're counting the number of old songs that we've chosen so far that's how I'm gonna use this conversely you could keep track of the new songs that we have available but I'm gonna do it this way so old songs initially is gonna be zero right here we haven't chosen any songs there are zero old songs for us to choose from now at this level whether we chose a one or a two the number of old songs now has become one and at this point you're kind of realizing we're keeping track of two variables we're keeping track of the goal which initially is going to be E3 and we're keeping track of the number of old songs which initially is zero so these are our actual variables in the recursion we actually don't need to keep track of which song like that's why I'm drawing this out like the ones and twos but remember when we code this up we don't care whether we chose a one or a two we're not going to consider any of these individual numbers this is what we actually care about over here now at this point like at this point over here we chose one so we can choose either here an old song one or we can choose a new song too when we do choose another new song then we would set our old equal to two for this part but here where we chose an old song old would actually stay as one and the reason we're even allowed to choose an old song Here is because K is equal to zero but if K was not equal to zero suppose it was equal to one we would still be able to choose an old song here but if K here was actually a one we would not be able to choose an old song here because remember we can only choose a repeated song AKA an old song If K other songs have been played since if we haven't even played well actually we have played K songs we played exactly one song but remember that K actually refers to the Gap like remember that sequence I was talking about one two one the Gap has to be K between the previous and the repeated old song The Gap has to be K that's what you have to keep in mind and that's what is going to be relevant in the code so firstly what we're only allowed to choose an old song If the number of old songs is greater than k for the reason I just talked about second what is the number of old songs for us to choose from can we choose all of the old songs like for example theoretically let's say old was equal to four like we've chosen four old songs before perhaps the sequence would look like one two three four now just because we've chosen four old songs doesn't mean the next song and I'll use a different color doesn't mean the next song we have four choices actually we only have one choice we can only put a one here we can't put a two a three or a four and that actually is if our K value is equal to three that's very important so I forgot to mention that K part sorry about that because here if K is equal to three then we have our K Gap here and then we can only choose a one if our K was smaller like perhaps K is equal to two then we'd be able to choose either of these two values to go in this slot but the formula for this let me tell you the formula first and then really explain it to you is going to be the number of choices as we have here is going to be exactly the number of old songs we've chosen the unique number of old songs we've chosen minus K now why is that because well first of all no matter how long our sequence is like I've showed you some pretty simplified examples here but no matter how long our sequence is one two three four this is just one sequence we could possibly create others but again let's assume our K is three and here our old is clearly four because we've chosen four unique songs even though we repeated some of them we repeated each one exactly twice there's still four unique songs that we've already chosen so the number of choices we'd have here is going to be four minus three we can only choose one song and that makes sense in the context of this example because we need at least a gap of three if we took that three and changed it maybe to a two but we kept old as four then we'd have two choices here because a gap of two is sufficient we can either put a one here or we can put a two here so that's the reasoning behind that and with all of that said and done I'm gonna jump into the code now and I'll explain the time complexity when we get into the code I didn't entirely explain like a hundred percent of the solution here but I think I gave you enough of the intuition that the code will actually make a lot of sense so first thing I'm going to do is actually just quickly create that mod value because we might need it in multiple spots I think in Python actually you don't because we can get away with a lot and we're gonna use a DP cache I'm not going to write that yet because I want to just solve this problem recursively first to just show you that it works so remember we have two variables we're going to keep track of our goal and the number of unique songs I think I could actually use goal here but I don't want to like create a name conflict so I'm just going to change this to current goal I think this might be my first time using snake case in a leak code video but I probably should have done it all along and the second thing we're going to keep track of is the number of old songs and I'll make it even more descriptive and actually call it that now we kind of talked about the main base case one is we have to use well first of all the current goal let me show you actually how I'm going to call this count function first we're going to call this passing in how many songs we need which is what our goal is and that value is supplied to us here and secondly we're going to pass the number of old songs that we've already chosen which is initially going to be zero and we're going to return the result of this helper function now since we need this many songs we're gonna wait until this current goal has been decremented all the way down to zero but that alone is not enough remember one important fact is we have to choose every single one of these n songs at least one time so the number of old unique songs has to be equal to n exactly and if that's the case we can return 1 because we found one playlist now this base case might not make a lot of sense until I actually show you the rest of the code but it's basically we have filled all of our slots but we used more unique songs than we actually needed to or that we even had available to us and you would think well how the heck would that ever happen how would we ever use more songs than were available to us and not just the nature of the solution that I'm going to show you so if this is the case or even that old songs is greater than n then we've reached a base case where we did not create a valid playlist and we're going to return zero the reason I'm putting an or here is because this case will execute first like I put this first for a reason if both of these are true we return one but if this is true and this is not true then we want to return zero that's what this part of the condition is for and can and the other part here if old songs is ever greater than n of course we can't like that's just not a playlist that we were trying to build so we would ignore that as well now here's the part where we have our actual choices we have two choices either choose a new song or choose an old song the new song case is a bit more simple so I'll start with that we're gonna recursively when we choose a new song our goal is going to be decremented by one because we filled one of the slots anytime we choose a song we have just filled a slot so we can go ahead and say current goal minus one is going to be the new current goal that's a new sub problem and if we chose a new song then the number of old songs has clearly just increased by one so old songs plus one the number of unique old songs has just increased by one now there's only a finite number of times we can choose a new song long and that's why we have this base case that will return zero if we ever exceeded that threshold this is the sub problem but how many new songs do we actually have available to us because that's what we should multiply this result by like this is the sub problem but how many new songs do we have that's what we need here and that's going to be n here minus the number of old songs I think that's just a little bit of math so once we have that we're going to store it in a variable and it's possible that this could end up being zero because of this base case now we can also choose an old song but remember we can't always choose an old song we can only do that if we've chosen at least K songs in total or probably more than K actually that's why I'm putting this condition old songs has to be greater than K because the Gap has to be at least K if we haven't even chosen K songs how can the Gap possibly be okay so that's why we have this conditional that's protecting this uh recursive case where we now choose an old song so let's start with the recursion what's that going to look like the easy part is that our current goal is once again going to be decremented by one because we just filled a slot secondly the number of old songs is actually going to stay the exact same because we just chose an old song so the number of unique old songs we've chosen should not be incremented it's only incremented when we choose a new song I'm still not sure if I should have named this variable new songs if that makes more sense for you feel free to do that but I think old songs is more clear and it is more even more clear here in this equation that we're about to do because when we choose an old song what is the number of old songs that we have to choose from well that's pretty simple it's just going to be uh old songs the variable that we have but remember also that we need that Gap to be at least K just be because we have all this many old songs available doesn't mean we can choose all of them we need the Gap to be at least K and this is the formula we came up with in the drawing explanation old songs minus K if K happens to be zero then we can choose all of the old songs if it happens to be one then we have to skip at least one of those that's the idea here and what are we gonna do with this value well we're going to increment it we're going to take it and add it to the result like this now I haven't really been using the mod and that's because in Python integers are like infinitely large so we can actually get away with it but if you're using a different language you probably want to put a Mod over here where we initialize the result and also you probably want to put a Mod here where we take this value which might be really big and then after you've modded like this part by this you probably also then would want to say a result is equal to result modded by that prime number up above but we actually don't need to do that in Python here we could just say return result mod and just like that and I'll run this I'm not going to submit it I'm going to run it to make sure that it works on the first few cases and Below you can see that it does and we're going to get time limit exceeded if we try to submit it so now I'm going to go ahead and add caching you can see that we have two variables here there's no Loops or anything like that within our recursion So in theory this should execute a total of the number of goal multiplied by the number of songs so that's going to be the overall time complexity it's going to be n times goal that's also going to be the space complexity because we're going to have a cache that I'm going to use a hash map for you could also use a two-dimensional array so here caching is two-dimensional array so here caching is two-dimensional array so here caching is pretty easy to add here we'll check if this is a case that we've already executed before of this combination is already in our DP cache I'm going to go ahead and return it this is probably the bad part of having to descriptive variable names because we have to type them all out like this so old songs and we can only return a cached value if we actually cached it in the first place so here I'm going to go ahead and cache it like this and I'm going to set that to this over here and then I'll go ahead and just return this value over here so as long as we did that correctly it should work I'll go ahead and submit it and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're praying for coding interviews check out neatcode.io it has interviews check out neatcode.io it has interviews check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
214
Have Yes Anokhe Showk The Last Question Is What Is And Given String Guess You Are Alone To Convert Into Your Pendrive Wedding Characters In Front Of Written Test For This Page You Can Perform In This Transformation Activist Arundhati Subscribe To Ajay Ko Main Successful Example Jhenna And Vihave the telegraph m&amp;a singh neetu restore unit-2 telegraph m&amp;a singh neetu restore unit-2 telegraph m&amp;a singh neetu restore unit-2 directors in front of latest ring to make top and share and subscribe is missing from hair soft straight judge david warner ne vivar jhal ka on that and no basis on distic comes up and throne on that and school Before pickup intro for tailing will shoulder last and alerted in the forest similar to hair gel abcd ajay ko 12345 term for 416 how to make a talent from ap state unit to add car actors in front of 800 mist this is the largest river sand Dunes pendant is a great effort that unknown to quarter inch pct is notification place was 500 this question clear jhal that Anita out about this question Ajay got this cream ok 100 uneven part fast and approach them in your mind it jhal number wise post Will always be defined the middle character husband is James and to reach the middle character in this tree again later you a Bluetooth settings at home I also tank process for door and speak only book which will have to front of media the want to reduce 1.8 these 1.1 media the want to reduce 1.8 these 1.1 media the want to reduce 1.8 these 1.1 19 March we dandruff center point at which will move into a tight loot abcd hui all that this whole numbers bar different back side saw tve divya point mintu phir bhi now papa par banner1 middle aged person's nodal center of the spelling of kal subah kal subah kal subah hai honey letter even today notification no how to decorate a picture is worth a good example of a great 6162 ki a new 2019 add karo to 20 the police and amazed ee ab to pakka yaar main bhi point to b Relative Center Director Around You And To Win Or Lose Weight Reduce's Nodal Center Of Time Is Serious Bill Then 0.2 Now Inducted Time Is Serious Bill Then 0.2 Now Inducted Time Is Serious Bill Then 0.2 Now Inducted Yes Or No A Message Can Appear To Center Of Problems Traffic Point To Absolutely Character Veer Kunwar Started 20 Ki Abhi Ko Return Of Tweet Ek Abhinav Shyam Gupta And Long Span Room By Going Through Each Not Every Digit Loot-Loot According Character Loot Longest Legs Jhaal Suno And Vinod Nishad Long Spiderman Just Behind The Water Electronic On To-Do List Of The Day To-Do List Of The Day To-Do List Of The Day Network Restaurant Front Of This Video Shoaib button long distance from this riot victims and related to edit and of the character of the greatest threat with me to vs 801 Twitter The resources for the tractors fluid Yashwant Singh and subscribe bf badhi hai ki sunidhi to make cup me to find index and it Is It Is Like The British Creating The Equal Pay For Equal String Fix Hai Yahaan Par Jam Par In Us Govind Desh Ne BBA And This Is Not Equal To This And Effects Or It Will Be In This Again Devgarh This Is Mean Equal Spring Switch Mix And black pepper vitamin is this but adams print click which is vansh drink in business meeting of electronics and after doing what ever created all the best wishes that this witch mince in twenty-20 match that pinky is saroj hai ajay ko in unwanted vansh draw Samudra Approach Awadhesh Intense Pain In Different Algorithm Typing Notification Maurya A This Suit Dress Algorithm Is Boot Age It Is Finding The Meaning Of Meaning That Assembly Interception Of Tractors Ideas Already Existing Udaipur And Suez Not Reply Teacher Protest Against The Solution Doing British Midlands Experiments Se 2019 News About What Is Pendu Shifted To Tomorrow Cricket Find Ujala Settings Match Play And Calcium Aspirin Or Shabd Hai Ajay Ko Ki Nahi MP3 Jhal Ek Photo Fasting Sonu Nigam My Company Will Sell Ccl2ncl That C Triplets Loot Jhala Jhal Hai Because A That personal enmity is an example, scientific half, I became the subject of late, revolution and collector hanged setting on pass Mukesh WhatsApp long spelling in A B A that if Justin Hayward Top 10 Hot Trend Map Stuart Broad Triangle Matching Kind Lattu Medical Tha Very Fast Track Court Constituted Talk About Okay Sorry This Plate Media's Rights Or It's More Clear To That Person's Life Character Witnesses To Start With Correct Apps That And Will Expand Around A The Correct Hai But Is Highlighted [ __ ] Will See That We But Is Highlighted [ __ ] Will See That We But Is Highlighted [ __ ] Will See That We Can not live for others like nothing one left stopped but dozens of this tempered glass option stopped Darauli this point not correct half of the Khas non state actors were the Indian left no who can provide no OK to the longest born in a correct Nov 21 A my voice should wake up please like share address for 800 like but one should visit to be tried to know anything what is quora ok then message this text call me on whatsapp subscribe channel like and share with oo loot vision This Position Images Dhan Dhana Dhan Goal of One Month Left End Images On Handed Over to WB Board at This Point in Exams Page OK and Defeats Pass Is Dam Good Baby Mein Rake Vikas and Print Media 10 Point Ek Lagi Hai Be Continued Support and Go To Special So first of all we single character and subscribe testing tools witch again in the mid-1960s Subscribe Thank You Alarm clock off in cases in the crowd control OK now we can apply this approach a done but giving a question Is That Across Introduced With First Character President Doctor Injection Always Been Looted Light Subscribe With 100 I Must Sanitary Napkin Rome Ok Business Check Water Left Most Wanted To Right In The Middle Phase Considered As A Valid For Android Starting With A Torch Light Business Solid is it can be inside a specific playlist them noida plot solar trusted usa it's absolutely a to whatsapp first calculated sea voice character that den are you take two to credit the match loot reddy so that doctor left most pointer in sea right click here Voor for B.Com 2nd ed B.Com 2nd ed B.Com 2nd ed ko call light to but ride point amazing edit ok sorry k not included in this app was left to enter into someone on half hour bcd on this occasion enroll 120 prom left side but half but definitely not to B that its balance and this left or right is layer create new bank of baroda dance class 9 pass loop control that tub were correct in coordination settings pimples or before Deccan Odissi rise because they want readers with show Jaipur Via Back To Loot Quantum Wife In A Room Near Me That Area Difficult Kevin Question Is That You Find A Palindrome Date Sports Buddha First Character Do n't Forget And Inspector Mist Or Dying To Stop This Thank You Need To Be The Scripters In Front Of You Need to do subscribe button more answers a ki yeh ko iodine se bhai dainik bbm udhe-bun ki surya ki england ke internet and dj dynamic please is dish answer because only for starting index 8.2 all characters starting index 8.2 all characters starting index 8.2 all characters hai android airtel mein se perfect ok to lagne se Petrol now lens for middle but I cannot be considering a light yes your body diet.st body diet.st body diet.st that summer Ganesh Chandra Bose death in the attack took place Pandey AB Dhindsa Sudarshan Reddy Shiva Reddy channel subscribe also because so and Milegi keep repeating the Repeating It Will Be Found What Is The Left And Right Wanted At That Time So In This Case Too Left And Right To Interact Which All Like It Back To Travels Remaining Spring And Reverse And Rooted In The Beginning Light On Shri Krishna Sudesh Ne Bigg Boss Will Bay To Find The Length Romes Long Span Ape And Giving Ka Stand Near The First Character Always Need To Bind Songs Control Beach Eliminate Toxins Defined In The Middle And No Like Joe Whats Is The Left And Right The Forest And Losers Okay To Dushman Possible approach for school project discuss was present hai guava example also talk about the bill river to river system text that this hai also has reverse swing but right left side by side this is that 16 This is the first Indian river and you are Member of an American Person First Springs River and Ganges Water Wasted Tuk On Hai What Is Whose And Sorry Is A Broad It's Less Likely Due To Hai What Will Happen On So This Holy Shrine Server Introduction Like the first one I have this alarms On your work and you will explain notification comprehensive off pm meeting matching date seems like a pivotal practical what is the current spring collection spring is equal to that do it handed bf video of notes and matching where team take the first rank pendle poster- Banner setting boyd sorry first rank pendle poster- Banner setting boyd sorry first rank pendle poster- Banner setting boyd sorry for example diff between start with dr to the last date 8th of being drafted in the western wear or moving and point up in the independence reverse swing or points its intention and police are investigating point is the last second last point you amazon This Matching The Best Friends Rotting Hormone Taste One To Three And Looked So What You Want To Say 0.2 0.2 0.2 A Literate Over The Given Spring Is Party But Their Time So Subscribe To The Channel Withdraw From The Subscribe This Is Notified For The Giver Torch light in the match with the last character of the river system is your performance correct the river system so let's lagi lights ago that when give in the match with java expand the screen to days dating the spelling of and one light of baghwa and boy hu Is the last that soldiers match topic Dabang Possible answer is what happened track that in three districts will that 1000 bill deposit Clans lights S2 is done What is the servicing and matching Auckland Next to ok now tape to pause will disable on twitter Jhaal ok to aap spring is black three torch light to middle egged in the last three character doubles match it is known that Bhojpur district which services roadways bus stand on the soul is taking Dashrath Singh from being a us looking for years baby bluetooth is that it is closed Springs because electrification will remain different wife husband ok to variety 6 sava me blazo cent and have a good intention quantity me three characters from the fastest growing in the last three crush beauty vs England test match hua to credit the best answer degree college no Water portal's tech for tractors, remember that Salman gave Bollywood aspiring directors a nod in his eyes, those directors are judgment from Amazon, yes gas laga hai 500 bhi tushar same to the best answer bhi contact AB this is ok and avoid concept character hai to That shoulder select were in that they debit one bowling wash absolutely digit stay in match after match then this is the best answer divide of dedicated facility holy string into being elected testing lineage tractor time start with a good married with river spring from the last ok And Malefic Placement Can Also By This Time You Know What This Is The First Rain Day Gift A Look At The Bottom In Character Reverse Embraces This Is To Reversal Juice And Debit The Front After Seeing A Or Fax Suman Saurabh Kushwaha Approach To Talk About This 99 Comparing Subscribe To That Difficult Method I Will Tell RTI Activist Disha Relative Reverse Yeh Ek Bittu Correct First One Electronic And Tractors Okay So Let's Get Se The Length Of The Best Industrial Considering A That Baalveer Matching Isk Ulp Pher Mein Hai To Kis Jhaal Light Yeh Ko Whatsapp without connecting to hua tha hello viewers comparing the loot ishq train meter loot pintu singh jo hair and 270 days on between like and two boys pesh kiya mein ruke so director lage bhatkne ka chalan se na ho how to take right the longest possible ki end Rome Okay But Doctor Too That Substring But Bloody Were Given A String Is Substring In Difficult Words Have Sprung Is Present In A Given String And Just This Championship Candidate But Man Time Order Off And Time 11016 Camps For Attraction To Tempt Mention Tea Positive Approach Witch Mentions For The Longest Final Long Span Job Taking Water Open Time Taking And One Character And Taking Into Practice Upside Down That Electrolyte Crown Under String Stopped Candy Crush Totally Different Leo Championship Servicing K Play N Flashlight Off Shifted To 10 Of Springdales Matching Decimal Servicing Send this message Character Directors' So message Character Directors' So message Character Directors' So Let's Get Confused If Teams Read About Championship In Allocated for Discussion Quiet Let One Mode Turn to School Management Cell Turn to OK Vishal Gotan Se Used to Find a Longest Talent Rome Cook in Time of Death And that's the mp2 battu solution service that gives me a good thank you Gaurav
Shortest Palindrome
shortest-palindrome
You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it. Return _the shortest palindrome you can find by performing this transformation_. **Example 1:** **Input:** s = "aacecaaa" **Output:** "aaacecaaa" **Example 2:** **Input:** s = "abcd" **Output:** "dcbabcd" **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of lowercase English letters only.
null
String,Rolling Hash,String Matching,Hash Function
Hard
5,28,336
332
hey how's it going on race so in this video discuss about this problem reconstruct I turn already given a list of airline tickets represented by pairs of departure and arrival airports reconstruct the itinerary in order all the tickets belong to a man who departs from JFK does the itinerary must begin with JFK a couple of points to note over here is that the itinerary that we done must have the smallest lexical order and we need to use all the tickets only once so let us consider one example first so over here we are given a list of pairs so if you see it means that there is an airport mu C and an airport la chart and there is a direct flight from mu C to lhr similarly there is a direct flight from JFK to MU C so if you consider these airports as nodes and this pair as a directed edge so basically you will be able to find a graph out of it and we basically have to have done the Eulerian path of the graph so it's not given in the question that we have to attend the unit in path but basically this reconstruct the itinerary in order this means you didn't but only I know means it's kind of a weird explanation that they gave but they are expecting us to find that I didn't work so first let us try to figure out what is either in path and how to compute it at in path photograph okay so this is the definition of a written path I have taken this definition from Wikipedia so in graph theory and either in trial or rewritten path is a trial in a finite graph that visits every edge exactly once allowing for division inverted Isis so let me take some examples first so let us consider a simple graph this is a this is B and this is C so for this the hidden path is a b c so if you follow the Silurian path that is a to b and b to c then you are able to cover all the edges correct so this is what our requirement is we have to cover all the edges so let me just take a better example as well let us consider this example we have a then we have B we have C we have D and we have and E is good over here correct so for this the Eulerian path is going to be something like a b e b c d so just follow the spot a to b then we have b e there is we cover this edge then e b this is we cover this part this edge then to C so we think about this edge then to D so we cover this French so we have covered all the edges on going through this route so how to find this route so what we can do is we will apply DFS only so let us consider the DFS is starting at this point correct so we have to apply DFS and we have to just modify a DFS only a couple of modifications are required to find the sealer in path correct so what we are going to do is so let us suppose we are starting a DFS at this point so from a we will move to B now the modification is so whenever you are visiting a edge you have to mark that it basically you cannot visit any edge multiple times because it is given in the definition as the left we have to visit every edge exactly once so somehow you have to mark this edge that we have already with it this is it into this edge so one thing you can do is you can actually remove this edge from the graph so that you won't be able to visit this edge again so let us suppose that our DMS starts from here so from A to B we move our way over here and we basically move this edge from B we can either move to E or to C so let us suppose our DFS goes to C so we come over here and we remove this edge then from C we can move to D we move this edge from here we cannot move anywhere else so what we will do is we will simply add this to a list correct so will I have D now we will be back in the recursion over here so from C we only had one edge which we have already visited so again what we will do is we will simply add C to the front of the list or the front of the list only so and will just return back now from C that is from B we have an edge that is to e so we will go to e will remove this edge then from E to B we will remove this edge we will back to B now from here we do not have any unn so we will simply explore we will simply add B to the list and we will be back in the recursion to towards here any so again from e we do not have any unvisited edge so we will simply add e to the list and we'll be back in the recursion so veil back to B again so again from B we do not have any unweighted edge so we'll add B to it then we will back to a and from a we do not have any unvisited edge so we will add a to the recursion or to the list so we basically have this thing so if you see this is same as this thing so you are able to find the Eulerian path using DFS only just you made a couple of modifications the couple of modifications is whenever you are visiting an edge you're simply removing that so that you do not visit it again because we have to with it oh the edge exactly once it is given in the definition of Li all right and the second modification is that when you're able to finish our things that ad that is for our vertex you do not have any unbudgeted edge you will simply add it to the list the friend of the list so that's how you find the either in part a couple of points known over here is that in the illidan path for a graph only starts from a specific index it cannot start at any index so for suppose for this graph the Union path can only start from this a correct and you cannot start from B why is that so the reason being for tearing path we have to cover all the edges so if you consider this example a doesn't have an incoming edge so we won't be able to cover this edge a to be if you're not starting from me if you are starting from B or E or from C from D we won't be able to cover this edge so we won't be able to find out your own path so you lured in path always starts from a specific vertex now how do know in our question which vertex is that so it is actually given the question it says that the itinerary must begin with JFK so actually this is the base point of your DFS or DFS will move from this air code correct all right so anything else so okay so in the question you won't be given this graph what are you given in the question is you're given a list of pairs or something like you will be given a to B to C to D B to E and E to be and from this list you have to create this graph correct so this is what is given in the input you're given a list of pairs so my first thing is to convert this list into this graph so this is the first step and after this you given the point from which from where the DFS is going to start which is JFK and after this you can simply find the earring but one more thing it is given that we have to find that UN but which is having a lower lexical order correct so let us consider some example so to understand that as well so let us consider this graph that is a then we have B then we have C so we have an edge from A to C as well and from C to B as well so if you see if you move from a b c a c b this forms are you reading but as well if you move from a c.b.c a B as well if you move from a c.b.c a B as well if you move from a c.b.c a B this actually also forms a your own path so both of these forms are nearing but we have to a done this thing why is that because this is coming lexically order this is this will be before this thing because B is before C so how do I achieve that thing so basically from a we first we will move to be correct not to C correct so how can we achieve this thing so basically when you are creating a graph so over here you will be given a list of peers so what we are going to do is we are going to create something called as map of string comma list of strengths that is we are going to create an agency list correct so basically we can basically sort this list correct all that we can do is instead of sorting this list we can even create a map of string comma priority queue of string so that we always get B before C correct so I guess that's it from the explanation so let me just write the code for it and then things will be hopefully up so first we will have map of string comma right EQ of string let us name it map and you will having a list of string which is result so let me just initialize both of these things over here this would be new hash map and this result is going to be new linked list correct so the first thing is to build a graph right so first is build a graph so what you're going to do is we are simply going to iterate over this list of string given to us so we will be having four lest of string so this is going to be ticket for tickets so now what we are going to do is we'll have two strings that is wrong which is going to be equal to ticket dot get zero and two which is equals to ticket dot get one why is that because if you see this list is actually a list of two elements from n to next we will check if not map dot contains key for prom we will simply say map dot put wrong with a new variety cue correct and after this what we will do is we will say map dot get from so we get a priority queue and we will simply add 2 to it correct so this is building the graph so the graph is over so after this what we will do is we will simply call DFS with this JFK and after this thing it will simply add up result so let me write this method as well this is void DFS this will take a spring suppose this is from all right now you will have priority Q of string which can we say as like arrivals which is equals to map dot get of prom and you will simply say while arrivals not equals null and not arrivals dot is empty that in that case what we will say is we'll call the DFS with this arrivals dot so actually if you see we are removing the edge over here correct so this is what we have discussed whenever you are visiting edge whenever you are visiting a vertex you will simply remove the edge correct so this is what you are doing over here and after this is done we will simply add the current spring from in the beginning so this will be add cost so I guess that's it let me on this board once so this is giving a long wrong result is this Ling the list living somewhere solution and God accept it so I guess that's it from this video in case you have learner in the video you can hit that like button and I would support my work you may consider subscribing to my channel thank you
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. **Example 1:** **Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\] **Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\] **Example 2:** **Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\] **Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\] **Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order. **Constraints:** * `1 <= tickets.length <= 300` * `tickets[i].length == 2` * `fromi.length == 3` * `toi.length == 3` * `fromi` and `toi` consist of uppercase English letters. * `fromi != toi`
null
Depth-First Search,Graph,Eulerian Circuit
Hard
2051,2201
700
Hello Everyone Welcome Back to My Channel Suggestion or Increasing the Problem Aisa for Any Search Facility How to Do Something in Binary Search Tree Images Basic Problem and Binary Search Tree Leaves for Less Problems Where Given Root of Binary Search Tree And Stir Well Point Note In Bsp Dot S Well Suited For The Soft Root Without Notice Bachchan And 10 Minutes Egypt Returns It's Okay What Is The Means Of Binary Search Tree Giving Tools And Need To Find Weather Of Particular Notice York Pimple Person 12625 How To Check weather to lord in were and in the best and not to here to is the fifth just want to front it aa that bigg boss kalyan vitamin b2 notes address so on importance of tree witch vitamin e hai to tower distant places with as launches stem k Sorry for late say hi how to find value given to me is life to find how to right social science physics lab benefit when tasty to bsc fashion property dat root node key cutting fruit note fruit notes value on the right all can see it Parents Note Parent Node Value E Will Be Always Great Dane Left Child Labor Child Value Is So And Paint Ruk Notes Value With You Always Great Dane A For Apple B For Muslims And Dar Right Child Queen's Pimples Ishwarya Parents For Lips Scientist To Right 407 hai to you and parents is great apparent value for this greater than love child new delhi vs to cigarette him * new delhi vs to cigarette him * new delhi vs to cigarette him * is but for this licensed images right chat flash light on which applies to all mentality stood up and went to paint a hai to For this two places left side and decided to front value with greatest danger left side value battu villain jakar right end value addition a right to this will be applicable ₹50 a right to this will be applicable ₹50 a right to this will be applicable ₹50 applicable to all the notes in the binary search tree on any successful property Any Such Na Peena She Adds To Her To-Do List Neetu Any Such Na Peena She Adds To Her To-Do List Neetu Any Such Na Peena She Adds To Her To-Do List Neetu How To Find What You Will Not Write To 700 To Find Weather To States The Best I Want Any Valid For Every Problem Yagya Va Draupadi Swayamvar Pointer And Root Vegetable Hydrate Pure Form Food Additive And Election What we have to you to search weather tuesday oct ok so let's just and just simple - a just and just simple - a just and just simple - a simple binary tree for 100 simple binary tree and what to me to the effective soch tu yaar do something lootpat and 100 hand person sachin right photoless person sachin Bodhpath left and right to vote in this modern amenities in this soch meanings for the root value and subscribe you in binary search tree left value will always be pleased in front of Delhi and you will always right and values and to the laptop the root and Light Of The Day Ko Sarkha-2 laptop the root and Light Of The Day Ko Sarkha-2 laptop the root and Light Of The Day Ko Sarkha-2 This Loot Value Na A The Principle Of Which Will Be Reduced To Let That Bigg Boss Ne Binary Search Tree And - Key Bigg Boss Ne Binary Search Tree And - Key Bigg Boss Ne Binary Search Tree And - Key Take Ginger-Garlic Value Note Warangal Take Ginger-Garlic Value Note Warangal Take Ginger-Garlic Value Note Warangal Left Side And All The Great Value Road By Andar Side Effect of Drut in Binary Search Tree to check in 12th part on left side simply accordingly they value your computer with truth and value with me to go that is to abuse me account statement root warid so zaroor volume ko hai to what will oo will go To the left his well known to join right for this not present for details they will make moving fast moving this root to the root Loop Fast Bisru Drops Root For No 52122 Iss In To-Do List Sunao 52122 Iss In To-Do List Sunao 52122 Iss In To-Do List Sunao 12217 Check This Does Not Mean Equal To The Value Of Root Value Ki Inko Likho Tu To Daru Which Were To Find A Co Arrest Recovery Code Ab Bollywood Par Point To In That Case Will Simply 2815 222 Is Note Jasveer Kaur Bigg Boss Me To The Root Not Right With Your Twitter Account That Her Nature Is Problem Vote Not Even To-Do List Play List Previous Serial Puram To-Do List Play List Previous Serial Puram To-Do List Play List Previous Serial Puram Hai To Is Cheez Ke 142 7 A Free And One What made you will have the option research and root of the giver is the incident of excellent and call me to written notes vitamin b3 heart oo k notification a diet tips root value the root value is equal to the value which we were trying to Fight the ritual comes when a view of 300 to 10 12v battery visualization true weather this root and left and right what we do not disturb him will tree like this is life is the fastest root beet root and jyoti swaroop to water will have given Through The Years But I Will Check The Rooms Were Like It Say It Is Something Like This 213 And Values ​​To And What Is Something Like This 213 And Values ​​To And What Is Something Like This 213 And Values ​​To And What Is This I To For Office I Volume Mute Is To You To For Individual Who Tried To Here His Roots Value Is Equal To Value Meaning Of Mother Also Have Foot Pain Just When Did Not Return With Route 159 Wilson Simply Return To Go But If It Is Navodaya Jab Diet Is Roots Value On That Is A Great And Value On Result Hair Roots Electronics Foreign Drive Dispute between healthy child to this root of and Vinod hatoge nor raw to you find answers in root to person's 2.2 and values ​​for root to person's 2.2 and values ​​for root to person's 2.2 and values ​​for electronic root value Switzerland part of the root to in this will do the curse for annual fest so It's against qualification for fifth to search will again college function search but in this case root passed with one nose distortion to fruit slapped roots life but also in Europe Russia left vote for life into will be passed in root ok celery salute it might happen left boss -7K Episode 717 Greater Noida Route boss -7K Episode 717 Greater Noida Route boss -7K Episode 717 Greater Noida Route Value Neither Office Let Me The White Part 2 In Both Cases Search Indore Route Right Side And Equal Andar Right Routes Right A Okay Champion Twist Vacation Call With And Sunao Despite Route That And In The Twelfth Class 10 result value nickel to value this sequence return promise Tubelight that your sudarshan basically you everyday entry problems comes when every problem has given to sur2 Visualize tree is diet fear disappears and the root and left and right part to vihar to only rs.1 economic But approach only rs.1 economic But approach only rs.1 economic But approach lagya to want this root and rest of the left and right requests for mid-day right requests for mid-day right requests for mid-day ok so let's talk previous straight to device a very easy code sorry c torch bsc functions ribbon is tracking root and volume chief to search in routine lazy but Fruits na i just returned basically like quickly no value se 800 just find you for search history thank you will not regret to inform you have written that is the notification 12th a producer and not dare i can simply returned to ok otherwise a value is loot Value meaning pure laptop battery otherwise with greater than world tour right and in this way there vehicles were written route main hansi searching everywhere every time zara here going to be the left and govinda right a now time complexity for searching logged in the right time When is active login? I hope you understand the problem and affidavit. There is decline in comment in the areas of field by issue or subscribe our channel thank you.
Search in a Binary Search Tree
search-in-a-binary-search-tree
You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 2 **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `1 <= Node.val <= 107` * `root` is a binary search tree. * `1 <= val <= 107`
null
null
Easy
null
754
hi guys welcome to algorithms made easy today we will be looking at the question reach a number so you are standing at a position zero on an infinite number line and there is a goal at a position target on each move you can either move left or right during the nth move starting from 1 you take n steps we need to return minimum number of steps required to reach the destination in the example when the target given is 3 so we take one step from 0 to one and in the next step we take two steps from one to three so this gives us total number of step equal to two in the example two the target given to us is two in the first step we take one step zero to one in the second step we move backwards or left from one to minus one that are two steps and in the third move we move three steps from minus one to two this gives us total number of steps as three and so the output is three the note states that target will be a non-zero integer in the target will be a non-zero integer in the target will be a non-zero integer in the range of minus 10 raised to 9 to plus 10 raised to 9. so now let's see how we can solve this question let's take this example where we have this as our area and we need to read 6 so what we do is from zero we go one step forward to reach one from here we can go either to left or right so we move right this time two steps from here again we can go three steps back or three steps forward so we move forward and that we have reached our destination so the answer here is 3. now what if the question was to go to the target 2. in this case we would need to go backwards also so from zero we go to one from here we go two steps back from here we take three steps forward in this question the main thing that we know is in the nth time we are taking n step so if we find the maximum target that we can reach for n step it would be given by this formula that is sum of 1 to n function of n and this function of n would be the x the value of x or step the second thing that is given in this question is that we can even move to a negative direction for this example we are moving two steps behind to go to two in three steps but in previous example that we saw we were taking three steps to reach six that is the maximum target we could have reached in 3 steps so now if we try to manipulate 1 plus 2 plus 3 to give the output as 2 it would look something like this so what we need is 1 minus 2 plus 3 these are the steps we are taking to get the effect of this minus 2 we would need to do 2 multiplied by the steps so this would give us the effect of going to the negative side in the second step in the first minus 2 we are coming to a neutral position in the second minus 2 we are going actually to the negative side so according to the theory that we have seen we can come up with this algorithm that is mentioned over here so we would add the steps till we reach a target so for example two we would add step one and step two we add the step two because in step 1 we have not reached the target now once we have the step 2 the target is already surpassed so we are sure that there were some negative steps which we missed so we would go on adding the steps while we can subtract two and do some steps so this gives us these two conditions that is add the steps till we reach the target and then add the steps till the sum minus target becomes a divisible of two that's all about the theory let's go ahead and code this question so we will take two variables sum and step which would be 0 initially now since here we are given that the target can be minus 10 raised to 9 2 plus 10 raised to 9 we know that moving to negative part would be actually mirror of moving to the positive part so in order to shorten our problem scope we would take the absolute value of target that's it now while sum is less than target what we do is sum plus steps and we do steps plus after we have come to the target what we do is while sum minus target is not divisible by 2 we again keep on adding steps at the end steps minus 1. okay and let's run this code let's try for some other inputs let's try for a negative input that's it and let's try for okay so for 0 we can add a base condition where if target equals to 0 return 0 and let's run for this test case now and that's it let's submit this code and it got submitted so the time complexity would be equal to the number of steps that we are taking and the space complexity would be o of one that's it for today thanks for watching the video see you in the next one
Reach a Number
cracking-the-safe
You are standing at position `0` on an infinite number line. There is a destination at position `target`. You can make some number of moves `numMoves` so that: * On each move, you can either go left or right. * During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction. Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_. **Example 1:** **Input:** target = 2 **Output:** 3 **Explanation:** On the 1st move, we step from 0 to 1 (1 step). On the 2nd move, we step from 1 to -1 (2 steps). On the 3rd move, we step from -1 to 2 (3 steps). **Example 2:** **Input:** target = 3 **Output:** 2 **Explanation:** On the 1st move, we step from 0 to 1 (1 step). On the 2nd move, we step from 1 to 3 (2 steps). **Constraints:** * `-109 <= target <= 109` * `target != 0`
We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.) We should visit each node in "post-order" so as to not get stuck in the graph prematurely.
Depth-First Search,Graph,Eulerian Circuit
Hard
null
1,171
hello and welcome to another video in this video we're going to be working on remove Zero Sum consecutive nodes from link list and in the problem you're given the head of a link list and you want to delete consecutive elements that sum up to zero until there's no such sequences after doing so return the head of the link list you may return the answer in any order now in the examples below all sequences um are serations of list so basically they give you an array but it's really a link list so in the first example um you can delete this for sure because this sums up to zero and then you get either one two one or 31 you can also get 31 by deleting this so as long as you get rid of consecutive sequences it doesn't really matter um yeah and in the second example you can delete this and you get one 124 and in the third example you can get you can delete this and this together so this whole thing can be deleted right here and then you just get the one so the main thing to know for um deleting like you're basically looking for subarrays here that are add up to zero and if you've done problems with prefix sums before this is basically like the perfect use case for it so prefix sums um whenever if you do prefix sums if you get the same prefix sum twice that means the sub array between those two sums has to add up to zero so if we take a look at this here's like our array and here's the prefix sum in the bottom so if there are two numbers that are the same like the prefix sum is the cumulative sum you've gotten so far so if you have a sum of three and you have a sum of three later on how do you get to that it's because all the operations you added and subtracted end up canceling out and giving you the same number so if we take a look there's a three and a three that means that everything from the first three to the second three not counting the first three has that up to zero so this has that up to zero also here there's a one and a one that means this whole section has to add up to zero because this whole section has to add up to zero then you would get 1+ 0 equals 1 to zero then you would get 1+ 0 equals 1 to zero then you would get 1+ 0 equals 1 and let's take a look at that so this 3 + 3 is 0 2 + 4 is 6 + 6 is 12 - 12 is + 3 is 0 2 + 4 is 6 + 6 is 12 - 12 is + 3 is 0 2 + 4 is 6 + 6 is 12 - 12 is zero and so you can do a prefix sum and like some link list stuff but instead what I'm going to do is I'm going to use a um I'm just going to take an array of the values because that way I can pop values off the end whenever I hit like the same prefix sum that I can't do with the link list because I can't go back in a link list so we're just going to like go through like imagine this is our starting link list we'll make an array of values and instead of prefix sum we'll just maintain a current sum and anytime we hit a current sum we've seen before we'll just start deleting items until we hit to the other sum and because we're basically looking anytime we hit a duplicate we're just going to keep deleting until we go back to our other thing we can just use a set for that so we'll have a set of all the sums we've encountered so far and we can build our array of items so let's walk through what that's going to look like let's use um I guess we can use like an array of items we build and then we'll just like pop things as we go actually we can just pop things from the original array as we go and this is going to be the new one that we're building and so we'll have a set on the bottom and we need to keep track of a cumulative total to know our like prefix sum so let's walk through how that's going to go and also for a prefix sum um if you're not if you're looking for arrays of some zero you do need to put zero into your original prefix sum because let's say this adds up to zero you're going to be like oh I have a zero here do I have a zero before and you won't unless you have a zero originally so we'll add the zero into our set and we'll have a total with a zero and then we can just Traverse here so we're going to add the one to our total um so our total is going to be one and I'll just keep Crossing it I'm putting new numbers to make it a little bit faster uh and is our total in our scene sums no it's not so we'll just add it in then we go to the next number so we add a two so we will uh oops actually let me do it this way this will be easier so our totals three and we um we don't have it so we'll add it in then we go to the next one and now our total is six and we don't have it so we'll add it in then we go to the next one and our total is three again right when we subtract and now we do have the three so if we do have the three that means we need to delete until we hit we go back to our previous spot where we had a three and that makes sense because this is the previous spot where we had a three so if we just delete numbers till we hit there we'll get rid of everything that adds up to zero which is this and it doesn't really matter how you delete so like I think we origin originally said that this whole thing adds up to zero but it's fine to like get rid of a chunk first and then another chunk because if a whole array adds up to zero if you get rid of part of it which adds up to zero the rest of it still has to add up to zero right like if this is zero and this whole thing is zero that means the rest of it also has to be zero so it doesn't really matter that you're deleting as you go so as soon as we hit a zero we'll just delete right away so basically we're getting rid of this section here and we need to update the sum as we do so we need to get rid of this number here so we can toss it and then we update our sum so now our sum is six and it's still not three and as we delete numbers we're going to delete them from the set as well so our sum is six which is not three so we need to keep deleting so we'll delete this six from the set and we'll delete this block and now our sum is three so that means we've deleted everything we needed to go to our previous number then we go to our next number and we're not going to be traversing our numbers we're going to be traversing our link list so this will be more like we're going to be building this as we go and then just traversing down the nodes of Link list so here the total is going to be seven have we seen it before no so we'll add it in then we go to the next one the total is 12 have we seen it before no so we'll add it in then the total is 13 so haven't seen it before and we will add it in then the total is four so total is four now we have seen it um actually no we haven't seen it before and we haven't seen before so we will add it in then the total is one and now we have seen it before so now we're saying okay we have to delete until we hit our total of one again so we're going to delete this update our total we deleted3 so our total is four um is 41 no it's not so we're going to delete four try to delete four okay there we go um and so our total is four we delete it and then we have to delete this number because our total isn't one so now our total is 13 um is that one no it's not so we'll delete 13 then we delete this block and we just deleted one so now our total is 12 uh one no it's not so we'll delete again then we need to get rid of this item because we only have 12 and we need to keep going so delete this now we have seven is 71 no it's not so we need to delete the seven then because we still don't have what we want we need to delete this block now our total is three is 31 no it's not so we delete the three and we delete this block and now our total becomes one and now we're good we have a matching total so everything we deleted like if we go back everything we deleted ends up adding to zero so we deleted uh all these numbers right here so 2 4 5 so this is 11 12 and this is 12 as well so all these six numbers add up to zero which is what we wanted so we deleted all this like I said this Arrow isn't super accurate it's just kind of showing for the picture this Arrow will be really going through our link list and we're just going to keep deleting the last number in our array so we'll just keep popping um and then changing the total so now we go to our last number so the total and this should have been one not three the total here is six we add it in because we don't have it yet and now finally our array is only two numbers so we'll just keep popping off the end our array will be like a stack and then once we have this array that's all our valid numbers then we can just build a link list out of it so we'll just start from the beginning and just build a link list and then we will return this here and this will work for all this other stuff so you can um like move all your nodes but because you need to have space like normally in Link in link list problems there Conant space in this one you need to have space no matter what cuz you need to have like a prefix sum or some kind of thing so because you need to have space no matter what I'd rather just get the numbers modify the numbers and then make a link list instead of like dealing with all the pointers so let's take a look at the code so here it is so we have our nums that we're going to be building as we go um our current will be at the head and we'll just keep going and we'll just go one note at a time and then this is our scene which is like our sums we've seen and we put in a zero and we have our current total then while we have nodes we need to add the current value we need to increment the total and if we've seen this total before we are going to get rid of the node so we're going to update the total get rid of the node and decrease the total and we're going to save this value in this current total that we're looking for is current total so if we go back in the picture for example um like here basically what we do is if we have a number we've seen before I'll go back a little bit actually I think it's right here so here our total was one and we're going to be like okay we've seen it before so let's just save this value and then keep updating the total but we need to make sure that the total equals the total we saved earlier so as we keep updating this total we're looking for one so we save that in this current total so maybe this is not the best name it's kind of backwards current total is actually the total and then we're actually decrementing the total and then once the total is the current total that means we've like deleted enough nodes so essentially what we do is while they're not equal just keep removing prefix sums from your set and keep um deleting nodes so decrement the total delete the node remove from the set otherwise if we haven't seen this sum before just add it to the set and we don't need to delete anything from our numbers and we just go to the next node so we just like our current literally just traverses the link list and builds up our actual stack and anytime we seen a prefix sum we just keep deleting until we go back to the S the previous location we've seen it at it's kind of like a sliding window thing where you're trying to do like a no repeating characters or something you have a set of characters kind of similar scenario there and finally you just have an array of numbers and then you just build an array of numbers from link list so I just made a dummy node I made the current equal to that go through every single number build a node make its next pointer the next note and so on so that part should be pretty straightforward like given an array numbers but the link list and this does work and I do prefer this over like actually changing the points in link list cuz like what's the point if I need space anyway if you don't um I would say like 90 to 95% of don't um I would say like 90 to 95% of don't um I would say like 90 to 95% of Link list problems are o1 so then obviously you would just deal with the pointers but here you need oven space so like you might as well use an array and so for the time here this will be oen because we're basically like traversing our we're traversing our link list once and then um the most NOS we can ever delete from the array we make is also oen right like as we're building this array we can only delete node we can only delete nodes one time so that's oven um and then to build out like our link list for the very end is also ENT right given an array build out a link list that's oen then space so we can only have um for this scene set obviously for n nodes you can only have n different sums so that's over um for the array of numbers the number of numbers you're going to have is equal to the um number of nodes worst case that's also oven so this is just basically ovenoven um yeah but I think this going to be it for this one so definitely one of the a little bit trickier link list problems because you're basically just doing this is basically just given an array of numbers remove all arrays that add up to zero but in a link list so you're basically not using almost any link list Properties or anything it's just basically use an array and yeah so if you know how to work with proix sums and if you do know that um that concept except that when you hit two prefix sums that are the same that adds up to a zero uh that whole array between those is zero then this is pretty straightforward and that's going to be all for this one if you did like this video please like it and please subscribe to the channel and I'll see you in the next one thanks for watching
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
190
hello everyone let's solve the lead code question 190 reverse bits so a reverse bits of a given 32 bits unsigned integer so we are given an variable n which is equal to the 32bit number and we need to reverse every element we need to just reverse this whole n such that every last element comes first that's what the reverse means so after getting that value we just need to get the integer of that so we need to just get that number such that its binary number representation is reverse of this let's see how we can solve this let's take n as the 32-bit solve this let's take n as the 32-bit solve this let's take n as the 32-bit number which is ending with 1 0 here we can see that it's a binary representation of number four so that is not actually required the only thing required is if we reverse this we'll just get something like and that value should be given so this can be done in many ways but the simple thing is to do use the left shift and right shift operations I'm pretty sure that you know the concepts of left shift and right shift so left shifts and right shifts are the important Concepts in order to eliminate or add to the next element let me give you a code snippet which was very useful for any other codes also so if we consider a variable as a result and for 32 Loop just go through the loop of 32 times and if you take this result left shift and if you add the given number which is in the binary format like this way and one this gives you the last bit so this last bit can be used as the first bit and then later on if you just make this as your right bit for example if it's 0 01 so this gets pop up and the variable goes to this to in order to make it to the next integer value we can just do it as and right shift uh so finally we will just add these values and just simply uh return the result value at the end hope you understood this I think things gets more familiar when you just start coding rather than explanation like this so let's go and code it up so let's take our value result equal to0 and we need to it's given clearly in the question that every number is a 32bit integer and if you see the constraints the input number binary string is of length 32 so it's obvious that we need to Travers through 32 bits all the time so for I in range 32 so we should travel 32 times and this result will be equal to let's take the end last bit so every time you just need if you need a last bit take an end off it this way just take the last bit and one and if you want to get that last bit to the front of that result you need to do result left shift of one just add up these both together which gives us to your last bit and now that last bit has to be sent to the next variable like the next integer let me type that move to next integer that can be done through n right shift off equal to one so every time it goes to the next integer and now it just returned the result this is very obvious and simple let's check it got accepted let's see the sub let's submit and see this is a simple intution if you know the bit manipulation very indepth understanding thank you
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
240
um 240 search a 2d matrix let's see write an efficient algorithm that searches a value target okay um in an m by n matrix okay this matrix has following properties integer in each row rows a row are sorted in ascending left or right integer in each column are sorted in ascending top to bottom okay so two things to notice here right uh one is the rows are sorted and columns are sorted in from top to bottom and another thing is we have to search something so when we search we can do two things linear search right or if we know that the input is sorted we can do binary search yeah so i think um and they are asking us to write an efficient algorithm so this is kind of a um this has to be a binary search kind of algorithm but for binary search we like most of the time we have um just a single row right so let's see um one way i can think of it is like checking from starting from first row just do the binary search on this row okay then if it is not here then go and do binary search here so for this example we are searching for five and it is found okay and so let's say we are searching for 5.5 let's say we are searching for 5.5 let's say we are searching for 5.5 something which is not in this matrix so we go here again we do search now we come here now from this point on anything you don't even have to bind the research right because 5.5 is less than 10 5.5 is less than 10 5.5 is less than 10 and it's not never going to be in between this range and same for this so that's uh that's one thing doing binary search um and maybe if uh even reduce it from top right so let's say it was one everywhere here one then there is no point in searching in this row as well because 5.5 is greater this row as well because 5.5 is greater this row as well because 5.5 is greater than this value right so we can do that is there any anything else that i can think of but let's go through the our checklist in matrix okay we have integer matrix kind of list and we have a target value to find and what is the output do we need to return the index or return true or false okay so boolean is what is expected true or false is expected that's fine about the size so is it is there a possibility that this is an empty matrix no it's not so it obviously there is going to be one uh one element at least and at max it's going to be 300 looks cool and the values about the values um so these are the two properties they are sorted but i just wanted to check if um we can have duplicates there is a possibility of duplicates as well so and we also have negatives so we have negative we have zero we have positive and we have duplicates great now let's um let's see test and edge cases design code time space so is there any edge case uh maybe just one element that is case um other than that um there are like multiple cases to be tested right um so target not in matrix um target is less than start greater than and something like this so these can be test cases going further let's uh let's try to come up with an algorithm so first algorithm that i'm thinking of is a binary search algorithm doing on each row but i think there has to be something else because both of these they are sorted so let's go through this example right um what we are searching for is five okay so let's see i'm here and uh let's say i am checking if it is in between this range okay um i have solved this question before and i think there is a there's a kind of solution where we so let's say um so 5 right 5 can be in this row because it is starting from 1 and ending at 15 right so what we do is we decrement in that case uh if we go from this end to this end okay so what we are doing is we decrement the column now in next iteration we again check um if matrix of this is 5 no then again if not and if value is less than this value then we decrement the column so again we check here still not so value still target is still less than this value so again we decrement the column so now we have reduced all this there is no possibility that anywhere in this section there can be a five right so now our surge space becomes this much so now we check uh at this location is it five it is not um is 5 less than this value it is not so that means 5 can be cannot be in this row anymore because if we go in this direction it is going to be less than 4 always and we have decided that there is no value in this section so in that case we have to go down so there is only one possibility that the value can be remaining in this section or this whole section let's say um so we go here and this we find it here but let's say we are searching for six again uh we do the same thing we ignore these values when we come here right um we check is this value equal to 6 it is not is this value greater than 6 it is not if it was greater than 6 then we could just decrement the column so it is less than 6 that means we have to increment the rule we should go in the next row and check if this value equal to 6 it is not so we go here and now it is 6. again let's take one more example we are searching for 3 we start at this position so 15 is greater than 3 so we decrement the column 11 is greater than 3 so we decrement the column 7 is greater than 3 so we decrement the column 4 is greater than 3 so we decrement the column now one for this value 1 is less than 3 so we increment the row two is less than three so increment the column so three is uh is found and if it is not found right then either we decrement the column which goes out of pound or we go out of bonds on the rows so in that case we return false directly so i hope i was able to talk it because i didn't um draw the things but somehow i think we can do this in this way so let's see um let me take rows and columns so length of matrix is going to be rows and length of matrix of 0 is going to be columns we have to find target right um and let's uh let's have two values row and column so let's start at row zero and started at the last value right okay so row 0 and column is columns minus 1 length of columns yeah and so let's see why a row is less than total rows and columns is greater than or equal to zero right do one thing if matrix of row from column equal to target and return true that's the only case we can return true otherwise if matrix of r comma c right this value if it is greater than um target then we have to decrement the column so let's decrement the column minus 1 else and increment the row right that's the binary search kind of logic and if we go out of bounds then return false so time complexity wise it's going to be m plus n at max let's say we are searching for 31 right so in that case yeah even it is not m plus n because we just increment the rows and then we yeah i think it's amplison that's it so let's see okay it's working um m plus n and we don't use any extra space so that is constant oh i've solved this multiple times okay nice bye
Search a 2D Matrix II
search-a-2d-matrix-ii
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: * Integers in each row are sorted in ascending from left to right. * Integers in each column are sorted in ascending from top to bottom. **Example 1:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5 **Output:** true **Example 2:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= n, m <= 300` * `-109 <= matrix[i][j] <= 109` * All the integers in each row are **sorted** in ascending order. * All the integers in each column are **sorted** in ascending order. * `-109 <= target <= 109`
null
Array,Binary Search,Divide and Conquer,Matrix
Medium
74
253
hey everyone how are y'all doing today we're gonna check out the lead code problem this question is very popular often has done amazon facebook and many other companies interviews and it just gives a great deal of understanding about time management problems in general so let's crack straight into it so today we're going to be solving meeting rooms too we're given an area of meeting intervals where each interval is basically a pair of start and end times we have to return the minimum number of the conference rooms required first we have to find an intuition but before we dive into that main idea i want to give you a quick tip some interviewers don't like to disclose the constraints to their interview problems because in some cases you can infer the magnitude of the problem based on the length of the input or other properties for example in this problem the interval length is between 1 and 10 000 so it's quartic which is not a terribly big number but also not very small which means that you can't just attack this with anything because it might turn out to be too slow with 10 000 elements the solution in general is somewhere between the quadratic and the logarithmic range there is a great article on code forces that details how you can often guess the complexity just by looking at the constraints or most likely asking for them in the interview setting of course this is not guaranteed but an awesome thing to be aware of i'm gonna put the link into the description so how can we build an intuition for this problem you may ask i think let's start drawing and see how this works out if we sketch up one of the examples let's take a look at the first example in this problem so there will be three intervals in this list the first one starts at 0 and set 30 the second one starts at 5 and ends at 10 and the third one starts at 15 and ends at 20. let's try to sketch these up in this basic timeline i'm gonna use the red marker for the first interval it starts at 0 and will end at 30. let's use green for the second interval which will start at the 5 and end at 10 and let's use blue for the third interval which will start at 15 and end at 20. so let's mark these um a little bit more just for the sake of clarity it will be easier to see what is happening here so what we can see here is that the red interval will take up one room for the entirety of these 30 units and the green and the blue intervals will take up 1-1 and the blue intervals will take up 1-1 and the blue intervals will take up 1-1 rooms but since the green room will be released at the tenth unit the blue room can reuse it so even though they need one room basically they will only use one room and in combination with the red interval this means that it will only take two rooms in total for the entirety of the 30 units how can we formalize this logic at first we know that one meeting room is definitely needed because of the red meeting then by the fifth unit we need another meeting room that's two if there weren't any other meetings scheduled we would say that the answer is two but we have one more so since the second meeting ends before the third one started we know that nobody needs the room anymore and it can be reoccupied in other words when we put the new meeting into this timeline we have to ask will the previous meeting end before the next one starts if yes then we don't need an extra room if not then we have to keep digging for new rooms how can we keep track of if the previous meeting has ended before the new one starts we keep track of the minimum times when the meetings end for example for the red meeting it's going to be the third unit for the green meeting that's going to be the 10th unit so if we want to add the blue meeting here we want to see that it's already passed the green meeting and of course we need to know it as soon as possible keeping minimum value with fast retrieval the minimum priority key or heap comes to the rescue the minimum heap is a three-based data the minimum heap is a three-based data the minimum heap is a three-based data structure and its main benefit that it will always keep the lowest value in the root of the tree and all others order below that inserting a new element into this heap takes logarithmic time so it will be bigger of log n and reading the top element of the heap is constant time so it's big o of one the algorithm behind the mechanism of the heat structure is probably worth another video in itself so i'm not gonna go into details right now but let's try to construct this mini based on the example we know that the first meeting ends at the 30th unit so let's add 30 to the heap the next question is does the second meeting start after the previous one has ended no because it is overlapping so the second meeting starts at five but since red is still going on it is overlapping which means that the next meeting we want to keep an eye on is the one that ends at 10 so the second meeting has to be added to the heap and because the second meeting ends earlier than the first meeting it is going to be the new route for the heap the next question does this third meeting start after the previous one has ended and yes because the third meeting starts at 15 the second meeting ends at 10 so they are not overlapping with each other which means we can discard the previous meeting that has ended at 10 but we are still going to keep an eye on the minimum which is going to be 20. this means we have two rooms again and there are no other meetings okay but what is the time complexity for this the worst case scenario is that all of the intervals will work with each other and we have to make n inserts into this minimum heap where n will be the number of the intervals and also in the worst case we may have to discard the minimum value n times so the time complexity overall is going to be big o of n times log n where this n is going to be the number of the intervals and the login is going to be the time complexity for inserting a new element into the minimum heap and the space complexity is going to be bigger of n where n is going to be the number of intervals we may have to add the intervals into the minimum heap and times this example is very simple because all of the intervals are given in a sorted order in the first example you can see that the first interval starts at zero the second interval starts at five the third interval starts at 15 so it's kind of easy to put them into this timeline but if they weren't and there would be hundreds or thousands of intervals it wouldn't be so simple and we wouldn't be able to see the overlaps that easy so the first thing that we should do here is to sort the intervals by the start times okay i think this pretty much sums up the intuition for this problem we can jump into the code right now and see how that works out this is the class that we get from lead code when we open up this problem there will be one method here with the input parameter of an integer matrix which is basically a 2 by n matrix for the start and end times and the return type will be an integer that will tell us the number of meeting rooms required at the end of the intuition building phase i already mentioned that we should sort the intervals by their start time because it will be easier to see the overlaps so i'm gonna start with that i'm gonna sort the intervals and based on this lambda expression here i'm gonna take the first property which is the start time it is indexed by zero and sort based on that after that we can start building the priority key which is the minimum heap in java it is going to store integers i'm going to call it mpq as minimum priority queue and after that we can start by adding the end time for the very first interval so this is guaranteed to be there in the intervals because based on the constraints one interval is guaranteed in this matrix and after that we can start by iterating through the remaining interval starting from the first based on the index and we have to check whether this new intervals start time is after the minimum end time that we store in the priority queue we have to also make sure that the priority queue is not empty we don't want to get any accidental new pointer exceptions the height intervals start time is bigger or equal than the minimum priority queues top element which is going to be the peak if it is then we know that we can discard the element in the top of this minimum heap so let's get off get rid of this and after that we can replace it with the end time of this height interval so we already constructed this minimum priority key and at the very end of this algorithm we know how many meeting rooms we needed because it will be stored in the minimum priority queue and the size will tell us how many meeting rooms are necessary let's submit this to make sure it works and see how it performs on lead code so although it isn't the best performing solution it is definitely a great algorithm to know um but once again what will be the time and space complexity of this solution so sorting is going to take big o of n times log n time because there are n elements in this intervals of constructing this priority key adding a new element is going to be big o of log n worst case scenario we'll have to add all of them so it will be n times log n peaking the top element of the priority queue is going to be a constant time operation and removing the minimum element from this is going to be log n again but worst case scenario we have to remove all of them so it's going to be n times log n so in total the whole algorithm is going to be big o of n times log n but what about the space complexity as i've already mentioned the worst case scenario is that we have to add all of the intervals to this priority key which is going to be big o of n where n is the length of the intervals i hope this was helpful if it was please like and subscribe leave a suggestion or comment this was my very first video and i'm aware of all the editing mistakes made and i really hope i will have more time to spur for this little project because i really enjoy helping the community and solving problems but this format is definitely different than writing bye
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
260
Hello everyone, welcome back to Coding Makeover, today we are going to solve another question of Let's Co, question number 260. This is a single number 3 question in which two numbers will come once and the rest are all the numbers There are only two numbers, both are unique, then that will be our result. In the first approach, we can solve it with the help of dictionary which has key and value, that will become our name and the number is repeating as many times as the value. We will keep it in which we will find out which number has come how many times, one tu time, tu times, three one time, five one time , in which the result of 121325 [ in which the result of 121325 [ in which the result of 121325 is the complete result. Only the unique number of two will be canceled out, their result will have the same value Logic: Here we will sort the numbers into two groups, they will be the first to come out, the formula for this is that the result and its negative number will be equal to zero. Now we can see one zero is set in the second last here, now what we have to do is that again we have to divide all the numbers into two categories, in the first group whose second last is set This will be the number which we have to Have to return with high quality Did the Did the Did the number and will smoke the lowest admit card This is our bath of all three tests Now we submit the solution thank you for watching this video
Single Number III
single-number-iii
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. **Example 1:** **Input:** nums = \[1,2,1,3,2,5\] **Output:** \[3,5\] **Explanation: ** \[5, 3\] is also a valid answer. **Example 2:** **Input:** nums = \[-1,0\] **Output:** \[-1,0\] **Example 3:** **Input:** nums = \[0,1\] **Output:** \[1,0\] **Constraints:** * `2 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each integer in `nums` will appear twice, only two integers will appear once.
null
Array,Bit Manipulation
Medium
136,137
123
Hello hello guys welcome back to decades and this video will see the best time to buy and sell staff's problem specific from digit code reliable in so it's an order to solve this problem the first world best odi debut verification plus memorization the second one will be Divided by doing technique so latest video problem statement notice problem from you have very form which is the element is the price of giving day designer Gautam to complete your transactions and intuitive transaction the same time did you must stop now let us look at some point To stop this problem subscribe and subscribe the Channel Nav-Jeevan second that is the price of Nav-Jeevan second that is the price of Nav-Jeevan second that is the price of stock and different places where light maximum two transactions and want to front maximum profit which we can make in the stock and maximum par obscene bittu only know this is That We Can Talk To Retail Price For Profit 2132 Subscribe Institute Of 13202 subscribe The Channel subscribe The Video then subscribe to the Page Second Witch Will Be 500 Crack Mini Possible Combinations Of Violence Bill And You Can Only Make To Transaction Set Most So In This Is The Maximum Profit Welcome You Be Stopped At These Two Selected For Eggs In The Attack One And Selected For The Total Profit Exactly ₹500 You Profit Exactly ₹500 You Profit Exactly ₹500 You Understand The Problem Statement Promise Its System Maximum Profit In Most Transactions Per Transaction Nothing But You Can You Celebrate Center Cycle Boys setting stop making profit and loss is equal to one notification simple transaction setting stop this is not given up will have to celebrate in order to buy 10 top again ok so basically this cycle not in the country as you can see the first week in the Midst Of Width Of Bus Stop This Is Not Mean That Know The Giver Setting Stop This Is Not Solve This Problem You Can See A Very Logical Solution Celebs hush-hush Weddings Celebs hush-hush Weddings hush-hush Weddings hush-hush Weddings Pattern Similar For This 214 S Well But How Will You Decide Which Mins That You Choose And Which Maximum Solid Say Only One Transaction The You Will Be Making The Global Maximum 2002 Transactions For A Given Point Where You Can Stop This Number To The Doraemon the previous depart from the previous day you have water stock in this day you can here from here and you can skip 10 to lift salauddin v3 options and giving day but you can only to the depending on the best subscribe to the Page if you liked The Video then subscribe to the Will Come Under The State Will Not Be Talking Subscribe for Women In The Will Be Holding Talks In Fever State On I - 1st Turn On The Amazing Be Holding Talks In Fever State On I - 1st Turn On The Amazing Be Holding Talks In Fever State On I - 1st Turn On The Amazing Stock And They Can Go to the Best State Otherwise the Giver Not Doing Anything Like Doing So They Can Be Reduced It's OK Sorry for the Day in the State of the Country Will Be in the State Will Not Stop Doing This State of the Otherwise and Women in the Lost Hope You Understand This Transition Problem in the link for detail view Name on How to Solve Reducing Requirements Know If You Can See a Great Holiday Give Winners subscribe The Video then subscribe to The Amazing to subscribe the Video then subscribe to the Page if you liked The question call dayla in which indicated that will be bank of baroda east up to wheeler and to the self start price will have to the self and subscribe others sharing and you will be Making profits after completing one transaction in listed for women in total profit will also be - 2ND women in total profit will also be - 2ND women in total profit will also be - 2ND year will be no know you can see this will be very big problems subscribe The Channel Questions well known in this case gorgeous basic element in three states sweater Friendship status first is that we are sending gifts in the previous day when water bottle cap and mid something on the current affairs video will start here and there decision of the best all the best on Thursday just remember and subscribe the to remember what Are Currently Closed * R Equation Problem Date Means Victims To What Your Values ​​Are * R Equation Problem Date Means Victims To What Your Values ​​Are * R Equation Problem Date Means Victims To What Your Values ​​Are Calculated And So They Can Return Dwells In Order To Solve This Problem Of This Entry By Using Dynamic Programming In This Case - Jind 420 Repeating Problems - Jind 420 Repeating Problems - Jind 420 Repeating Problems But It Doesn't Work In The first subscribe to subscribe Free but on Thursday subscribe and subscribe the mode switch board The talk to the second and third division in the middle Log in hand which we shape button The first day price equal to two Som rate states different from rate states with surprise Same Day SIM Birthday Status of Different Not for This Thought Thursday The Video then subscribe to the Page if you liked The Video then subscribe to the Difference From This Point to the Number of Units and Repeating Problem Solve Different OK No Problem Solve This Problem W Singh multi-dimensional memorization W Singh multi-dimensional memorization W Singh multi-dimensional memorization are this is the most efficient approach using memorization so this will be fetching elements in which you have to the limits on 100MB maximum number of with a professor at least to take off but do not forget to subscribe the channel and time TECHNIQUES IN DO SUBSCRIBE MY CHANNEL SUBSCRIBE TRANSACTIONS BOIL * Single String TRANSACTIONS BOIL * Single String TRANSACTIONS BOIL * Single String End User Name Doing Service Key Blindly Correspondingly Value Which Will Be Net Maximum Profit Calculated Combining subscribe The Amazing Hit The Same That Next Day Thursday Subscribe The Amazing The subscribe and subscribe This is not two fancy beds This is not the most optimal approach but this is temple in terms of space so you can prove it will work No this is the question The video of the subscribe button subscribe divided into two parts After Mouni Roy from all possible points divided into two parts divide the left side and will monitor will take the right hand side effect from this to intellibriefs last point and go for only one transaction Noida the maximum profit from the transition from the transaction in Order to Find the Total Maximum Profit Transactions 1.12 Total Maximum Profit Transactions 1.12 Total Maximum Profit Transactions 1.12 Next Device Maximum Profit Transaction Maximum Profit and Loss Birth and Death for all points in the Maximum of all the calculated Subscribe Thank You Can Use This Technique Thank You Can Use This Technique Thank You Can Use This Technique Quad Divider Transaction How to You Perform Operation So in this will give the time dividing this point to fennel love you all the point to the laptop from to the point which starts from this point subscribe will not left side to maximum wave subscribe Video set to maximum to make profit 2012 Total Profit 320 Fan Ad Buddha Transaction Values ​​on the Left and Right and will Transaction Values ​​on the Left and Right and will Transaction Values ​​on the Left and Right and will calculate the maximum profits of force net Maximum of already calculated Maximum profit which will also be calculated for the points 100MB Maximum Already Subscribe through which will give the giver and debit the Right hand side this point is not very common logic which will solve this problem to find the value of quantum at once maximum profit there will obviously find minimum value for bank po and will find the value from this point notification subscribe Video Maximum Transaction Video Maximum Song From The First Elements Sexual From The Last Time From Left To Right The Name Of The First Indian To Win The Time It's Very Difficult To Solve Win From Left To Right Will Have To The Value Of Half Velvet Given Point Which Can Find The Profit Nine This Is The First Values Minimum Balance and Invalid Two Lips Beaten Way Can Find the Value of the Minimum Balance Subscribe to Thursday Person They Will Give You This Doesn't Give You But They Will Update You Not Giving More Profit From Right to Left With Nothing Against The Time Being Tattoo Right Wear Moving From Right To Left In Odisha The Right Hand Side Transaction Notification Iffy Already Know The Maximum Elements For The Giver 1.3 Loot The Maximum Elements For The Giver 1.3 Loot The Maximum Elements For The Giver 1.3 Loot The Profit Will Be To The Maximum Volume Set On Which Is The Current Events Which Will Give The Giver Point This point is the maximum person to switch on the giver bank to the minimum volume Minimum who won the left performance in the morning maintaining maximum value for there right toe function if you never understand why they are maintaining minimum value for electronics value for reproduction is solved on Thursday This problem at any given point to that point is maximum provided at the point where nothing but calculated for the president of the maximum profit id this point is subscribed - The left minimum ok soiur just read carefully again and you will come to - The left minimum ok soiur just read carefully again and you will come to - The left minimum ok soiur just read carefully again and you will come to know about and you can Just Right to Drive Very Helpful Similarly for the Second at One Point of Maximum Profit for the Transaction Raw to Make Maximum of the Value for the Side of Maximum Profit Subscribe - The Subscribe This Will Also Very Subscribe - The Subscribe This Will Also Very Subscribe - The Subscribe This Will Also Very Intuitive and Profit Subscribe Profit Maximum Slap Transaction Profit Plus Maximum Per Transaction Profit at a Given Point IS OK No Latest Go Through This Interval No Patience subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the world will visit Single Point Will Do Subscribe Button And Feet 2009 Latest Want To Be Next Point Which Is This 398 Istri Luto Maximum Profit After Taking Only Two Points From Bigg Boss To The Maximum Profit Which Was Previously Calculated Wishes Maximum Off Subscribe My Channel Subscribe Maximum Profit Subscribe Previously Maximum Values Which Will Give What Is The Current President Profit Person Then Which Is The Volume Minimum Wages For - 2 Minimum Wages For - 2 Minimum Wages For - 2 Quest To Okay Sorry But You Will Be Forgiven For The Next Point System Software This Point To That Point What Will Be The Festival Transaction Person To Maximum Already Calculated To The Current President Profit Will Be 2 - 20 For Celebs Subscribe To This Point And Then They Will Again Be Calculated Person The Current Profit Suvichar Net Profit - - Verb - Profit Suvichar Net Profit - - Verb - Profit Suvichar Net Profit - - Verb - 121 Kunwar Devendra The Calculated Admin Values ​​210 To Love You Updated With one Values ​​210 To Love You Updated With one Values ​​210 To Love You Updated With one indicating that even lower price and moving and you will give you will be amazed at the annual profit maximum Tweet - 134 annual profit maximum Tweet - 134 annual profit maximum Tweet - 134 2nd floor - One who knows the right way will be difficult to win porn quote Vikas Bank of the last day will not benefit Presence Will Not Be Able To Celebrate Her For The Last 1200 Subscribing To Beat Subscribe Will Start From This Thank You Will Be Ne Subscribe The Channel Please subscribe and subscribe Maximum 04 - 20 2012 Will Feeling This and subscribe Maximum 04 - 20 2012 Will Feeling This and subscribe Maximum 04 - 20 2012 Will Feeling This Point And Value Karo Lobby So Update Dusar Max Value Like Bid Folded In Value Van Adheen Will Update Religious Value Subscribe No Veer Will Maximum - Liquid Subscribe Now To 9 Maximum - Liquid Subscribe Now To 9 Maximum - Liquid Subscribe Now To 9 Will Again And Again With Maximum - The Video then subscribe to the Page if you liked The Video then tight hand side patiently indicating a word In a given point IE latest se I would like this point given due point volume maximum profit will be equal to the maximum profit from this point digestive withdrawal in from this point to point sirvi pati then knowledge for this profit subscribe The Channel Please subscribe and subscribe Do kid for each point Sundha profit will be finished with Rs 80 more profit will be initially three lines will be starting with this point one is this point 3 ok no way at this point the problem is maximum of the best profit from left to Right in the middle of the present in the laptop - 108 Atvir present in the laptop - 108 Atvir present in the laptop - 108 Atvir will not get updated with the maximum Already subscribe 9 is half cut this point the maximum value will be coming gas Maximo already calculated leukemia two plus 350 500 will give 500 like this will keep Repeating the values ​​and you will find that will be the values ​​and you will find that will be the values ​​and you will find that will be the maximum profit person 2018 201 9 The time complexity of producing state in which you can own Problem in description and subscribe the Channel subscribe The Channel Like this is the function is max profit in this Case Wear Give Enterprises Prohibition Na Dharai subscribe The Amazing Current Position in Its Wake Up Sid Subscribe Must Subscribe Notification Subscribe Channel Ko subscribe The Channel And subscribe The Amazing - Where All Play Store The Value Amazon Will Be Returning Others Will Process And Will Update And this electronic will return the problem servi calculating the time of northern subscribe minus one can another in the state in the northern states in the most obscure no fear in if directly can not skip will always be on its own so will always make this clip Call Not The Current President On The President Of So They Can't Be Under Current They Can Celebrate Their Bodies Through Themselves 1999 Click And Subscribe subscribe and subscribe the Video then subscribe to The Amazing Subscribe Now I'll Do The Preprocessing Forces Android Processing Udayveer Volume Maximum Profit And Saw A Very Simple To Enter And Hope You Are Able To Understand This Link For Similar Problems Will Be Present In The Food And Solution In Different Languages Subscribe Benefit From Like Share And Subscribe
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
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 **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
206
given the singly-linked list how can you given the singly-linked list how can you given the singly-linked list how can you reverse it recursively that's today's video let's get into it hi everyone my name is Steve today we'll go through a legal problem 206 reverse linked lists the solution that we're going through today is to reverse this linked list recursively this is the problem description let's just recap in one more time one two three four five now and when you want to reverse it the output to be five four three two one now so how can we do this recursively let's take a look we'll just use a short example one two three four now how can we reverse in this singly linked list recursively the output needs to be four three two one now let's just have a quick recap about the iterative solution if you want to have a detailed version just check out my other video which we published yesterday about the iterative solution but for now I just have a brief quick recap this is the iterative solution this is the actual code what we did is that we have two notes we initialize the two notes one is called previous used to be here and we then we have another node called cur the current node will just stand well assign hat to the current node and every time we go through this iteration there's a while loop you know inside the while loop there are four steps so that each time we'll just keep changing the color in those next pointer to point to the previous node and then keep iterating that's the way how we did it for the iterative solution I hope you can still recall that for the recursive solution it's very similar we write code to do this recursively for us let's take a look first one don't use a recursive function which is very common in a lot of recursive calls so here is our recursive function reverse then we'll take two parameters one is hat and the other is now what is the now I create a new hat this is the new hand that eventually we're going to return so the base case we'll take a look at this here this is um this is not only in the base case but also the corner case say for example what only a mount linked list where there's only one note which is now in that case in the recursive function what is that first watch at remembering every recursive function there must be an exit case right that's the base case when does the recursive function needs to return needs to exit out of this recursive call stack that is the base function so in this case hat equals two now in this case hat when we are given an outlet list an empty linked list or when we reached the very end of the last node of a none now linked list that's the case when we need to written that's the case when we need to return which is written new hat so that's why if say this hat is now and we'll take this now here and then we'll also call reverse function the new hat is also now so we first check if hat equals two now if that's the case what is written you have in this case new hat is awesome now that's it then what then so with the base case down with the Connor case then we'll talk about how we can do a regular case for even then empty and then not make lists how do you do this recursively well just basically to put the iterative function using the recursive way to write it that's it so instead of using previous current won't use a new hat or quite new hat still will use exactly the same four steps to go through the recursive call first we have initialized a new hat remember the four steps in the iterative function we have we create a temporary book on next this is exactly the same we have a temporary book on next how do we get the next which one is the next it is jackpot next we don't need a crib we don't need a crew note we just use hat dot next which is this one this is the next node then step two first with Christian cost and trees will break this link again why can we break this link and we worry about losing access to the rest of this link nest no because we have a temporary work on next which is the new hat of the second half of this LITTLEST right and this moment we can simply break this link how do we break that behind assigning the hat but next the pointer of the hat next plundered towards new hat that's how we did it we assign new hat - hat but next this line assign new hat - hat but next this line assign new hat - hat but next this line does two things or just one thing it's just - changing the has next pointer just - changing the has next pointer just - changing the has next pointer towards new head so that this one's next pointer is pointing to you the new hat and then this link is just a cut off right this is the second step what continue to do this for every single recursive call step three is what changement knew had to be had this is exactly the same as the innovative function how we went with that now this is the new hat and in the very end a new hat is going to be here on top of four and what just returned you hem that's going to become 421 so we'll keep moving new hat and this point had both new hair and hat are pointing at the node with value 1 since we have moved a new hat here and now hat could be moved to next this that last line of the for stamps hat could be moved to next this is the current status of this linked list it's broken apart into two parts one is headed by the new hat the other pan is headed by the hat then at this point instead of using a 1 we're using the recursive call this is the recursive function recursive meaning is going to call itself right we finished this first recursion then we'll call this recursive function itself which is reverse hat new hat this is the new hat well so this is the function itself so it's going to get into it yourself but this time the head and new hat is different previously had is here new hemisphere but now had is here in new hemisphere right so we'll keep calling this now we're entering the second recursion would cost app one of second recursion again we'll initialize a new temper become next this is the next one how do we get this next again that is does happen next this is next now what campus link off by assigning hats next pointer pointing towards new hat this is the second step continue now we'll move new habit of this hats position okay then move hat to next position so we'll keep doing this is the end of the second recursion well keep calling this recursive function until when until I had equals two now okay let's just go through there are two Manos what go through that real quick so that we can have a better understanding of how this simple lick the list with four knows how it goes through this recursive function now we'll start the third recursive call hat is not equal to now so it's not going to enter here well assign a terrible next is going to be this is going to be the new next now we break this link by an assignee hat next pointer into new hat and then we'll move new hat over here then hat is going to be next so this is the end of the third recursive call right third we close it's all finished now hat is here so he'll is still not now right hand is still not now so it's not going to come over here instead it's going to create a one more temporary book our next well break this link apart - Annie has next pointed towards new hat - Annie has next pointed towards new hat - Annie has next pointed towards new hat and then when we're do is well move new hat to your hats position and then hat will become next at this point the fourth when a cursive call is finished remember there are a total of four linked list nodes at the end of the fourth week urgent call hat is standing at the very now point that's the end the next pointer of the tail of the original linked list right at this point it's about to stand the fifth on recursive call in this case it's going to check here then is going to enter here because hat is now at this point right at that moment what are we going to do we're just going to return new hat that's it this is the new hat take a look here four three two one now this is the correct output that we are that we want to do with it that's it time complexity of this album is still om suppose the length of the linked list is n there are n those some of the time complexities oh and this time connected space complexity is going to be Olin because we need extra space for the cost act for the recursive cosmic at most it could go up to n Lambos so space complexity is o n as well now let's quickly put idea into the actual code using the recursive way let's see we copied this list node we'll just call it return reverse ad and then we'll implement private the helper function the recursive function called reverse so first as I said we need a base c'n base condition on the break condition for average for every recursive function it needs to have a break condition what about check is if had equals to you now what world to is will return new tab directly right that's the base condition and also the kana case whenever we reach the very end the next node of the tail node was just written the new hat that's it and then we'll have that four steps which is initialize a terrible or next which is hat dot next so since we have initialized a new variable to be the new head of the second part of the linked list what we can do is that we can break the hat dot next current link by assigning it to the new hat right and at this point this given original linked list is broken apart into two parts one is headed by new hat the other is headed by the original hat and then we want to do is what we want to do is well move new have to become the Hat and then hat will become the next so both of them will move towards the right that's it these are the four steps very similar to what we did in the iterative function again in the end were just three to reverse and the new head so what keep doing this remember both had a new hat they moved towards them right after this one recursive call stack so we'll move both of them towards the right someone just continued to call this recursive function reverse hat / a this recursive function reverse hat / a this recursive function reverse hat / a comment new hat so this is the recursive function itself now let's hit some min and see all right example 100% 90 yeah and see all right example 100% 90 yeah and see all right example 100% 90 yeah this is the recursive this is the yeah this is the recursive function if this video helps you to understand how they would curse a function - we could to reverse a singly function - we could to reverse a singly function - we could to reverse a singly linked the list of works please do me a favor and hit that like button just destroyed the like button and don't forget to subscribe to my channel and tap the little bound on vacations and that each time one I publish a new video you're not going to miss out on anything and we are right now going through a linked list serious after this will go through a tree series and after them will go through more advanced data structures to help everyone better prepare for their upcoming in the concluding interview questions that's it for today's video I'll see you guys in the next one
Reverse Linked List
reverse-linked-list
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[5,4,3,2,1\] **Example 2:** **Input:** head = \[1,2\] **Output:** \[2,1\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is the range `[0, 5000]`. * `-5000 <= Node.val <= 5000` **Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
null
Linked List,Recursion
Easy
92,156,234,2196,2236
1,646
200 Hello guys and I am now going to explain the list to the dairy challenge get maximum engine rated okay to question me de rakha your given in teacher has said are the norms for age plus one is generated and the following pet ok hai kuch complication de rakha meaning Initially it seems over-whelming Initially it seems over-whelming Initially it seems over-whelming that this is mid-2012 7102 1821 E Request OO that this is mid-2012 7102 1821 E Request OO that this is mid-2012 7102 1821 E Request OO Name Saheb Number Two * I plus one is equal Name Saheb Number Two * I plus one is equal Name Saheb Number Two * I plus one is equal to Nashik Two plus according to plus one Okay so tell me a little bit So they are continuously shooting that this What have you given but the type field to approach such problems better that I printed it is ok so I wrote it, I took it and looked at it and if you see it written then it can shine that what else is this, in reality nothing is happening anyway. In this, only this is what is there, * is you * is In this, only this is what is there, * is you * is In this, only this is what is there, * is you * is representing that China Indexes of The Amazing * * is China Indexes of The Amazing * * is China Indexes of The Amazing * * is representing and indexes is ok, so it means if there is even induction then make me Nav Cyber ​​Two and if there are more inductions then come Cyber ​​Two and if there are more inductions then come Cyber ​​Two and if there are more inductions then come * of class If you want to do 8 plus one, then okay, * of class If you want to do 8 plus one, then okay, * of class If you want to do 8 plus one, then okay, today I have given 10 to myself. I have kept it tied to one. Okay, now when I come to do, I want to divide it into pieces, I am making it, so I will post one here, okay. Till now this record is good meaning it is fine then in this case I will request then Vansh you have come, it is fine then I have to come and you have to write I plus one, it is fine so it has become you are fine, actually this side has come plus one. Okay, so in this way then this is very wow so forward to cigarette that point I have written five here and so it has more fiber 231 of 2036 in this I rather consume olives order so three plus points 372 okay then Back from this ancestral it was neither in one place I will write forecast for element node and so instead of note I will write and plus 5 this pimple two four is okay so what is 10:00 four is okay so what is 10:00 four is okay so what is 10:00 five okay to white I will write next copy I will order at 11:00 so what will happen in this case, the will order at 11:00 so what will happen in this case, the will order at 11:00 so what will happen in this case, the successful test of these two plus two is equal to five and the natives can fly z10 in that case will have to husband Daniel subscribe loot liya hai now I will do it is quite simple like WhatsApp Earning A that it seems like the browser is baked with his hands so first of all of course S 21 will be made that one pan is equal to zero a written 1580 ok name is made marital vector at number one plus one in question said That which n to inches plus one size business person will become not initialized number 1 120 name juice one is equal to two one ok and I am aloe vera result for me in the question rate and four hour which shine 11082 in this whatever is my maximum number return me. If it is okay to do the tax then Entries Contra Voucher because right now it increases initially, it is very small, it is okay, right, the point is equal to two, it is difficult-2 plus, okay, what I difficult-2 plus, okay, what I difficult-2 plus, okay, what I told you, on this side, one percent is in the backyard of minister percent two is. Equal to zero tapas tyaag karna hai Namaskar aaye equal to numbers IS by to go ki aapke khas episode 122 tab kya naam saaye equal to numbers by bittu plus norms this is back to plus one okay so that's it question is over return methods Every number of the question has to be checked after opening the kinnar number element, so to update the result, one thing we express is Om Namah Shivay, it is good, not based, I know, vitamin E result, let's color food and key table, play list that No differences it seems to be working fine hai ki accepted so text message ghar understood video achhi lagi ho to jupiter like thank you a
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
169
hey guys persistent programmer over here and today we're gonna do another really cool question majority element okay so given a size of given an array of size n find the majority element and what is this majority element well the majority element is a element that appears more than n over two times where n is the length of the array so let's look at this input where we have three elements in the array and we're gonna do n over 2 so 3 over 2 which gives us 1 point 5 so this is the threshold we need to compare against each of the frequencies in ireri so we can see that the frequency of 3 here is 2 which is greater than 1.5 so here is 2 which is greater than 1.5 so here is 2 which is greater than 1.5 so this element does qualify and the frequency of 2 is only 1 so 1 is less than 1.5 right so it does not qualify than 1.5 right so it does not qualify than 1.5 right so it does not qualify and this is really important for this question oops so this is really important when they say that you may assume that the array is non-empty and the majority array is non-empty and the majority array is non-empty and the majority element always exists so these are the exception conditions that we don't need to check for in this question and they're telling us that yes this there will be an element that is qualifies for this condition ok so yeah let's look at some solutions and discuss how we can solve this problem the first solution that immediately came to my mind when I saw this problem was to create a dictionary and map all the frequencies of each element so here we have 3 and 3 occurs twice so we can say it's frequency s 2 and then 2 occurs one time so it's frequency is 1 and then iterate over this map and check for the condition so we'll just check the values and see if it is greater than our threshold which is in this case 1.5 threshold which is in this case 1.5 threshold which is in this case 1.5 so let's look at another example here so we have an input array like this so for this array n is 7 and 7 over 2 is 3.5 so this array n is 7 and 7 over 2 is 3.5 so this array n is 7 and 7 over 2 is 3.5 so we're gonna compare against 3.5 and we're gonna compare against 3.5 and we're gonna compare against 3.5 and we can see that the occurrence of 2 is 4 so 4 is greater than 3.5 and this is how 4 is greater than 3.5 and this is how 4 is greater than 3.5 and this is how we'll get our answer so this solution is pretty straightforward we just create our dictionary and then iterate over the dictionary and return the element with our highest frequency and the time complexity for this is often okay let's quickly look at this code and then we can see how we can optimize this solution further great so I'm back in the code and the first thing I've done is I've created my threshold which is n over 2 so we're taking the length of the number array and dividing it by 2 and I've also created my frequency dictionary here and the next thing I did is I'm iterating over my nums array and I'm just populating the frequency of that number so if we see the first time the frequency is 1 and if we encounter it again we're just adding to that frequency ok and after all of that is done I'm iterating over each item in the dictionary and I'm just checking if that frequency is greater than the threshold that we defined up here so after doing that I'm just returning the digit and we know that the question says that there will always be an element which has a majority so that's why I did not put another return outside this for loop ok so let's go ahead and submit ok great so that works now instead of creating this additional space for this frequency dictionary is there a way we can optimize this space by just using our nums array so that is optimization we will look at next for it this solution great so the optimization that we are going to decide now is how to optimize the space for this algorithm like can we solve this problem in constant space and thus we're more sporting algorithm comes in handy and I will just walk through the high-level will just walk through the high-level will just walk through the high-level idea of what this algorithm means first before looking at the code so if we had a candidate profile like this where we had a B and then a so we can see here that okay well if I was at this position then my winner my winning candidate would be a with the majority of votes right and okay well let's say a has two votes and then if we're here we know that okay well B has two votes and this is a tie but our question says that the majority element always exists in this array so that's why this under this is very important and we know that the last element here this is the determining element that determines which candidate wins so okay so if these two were canceled and our winning candidate here is a well is there a way we can devise an algorithm to keep count of these candidates as we iterate through the array so that's essentially what the Moore's voting algorithm is trying to solve so let's look at another example here so here let's say our array looks like this and we have our first candidate a so our winning candidate at this point is a and well when I move to the next item in the array I see that well a has one vote and the next element is not a so when that happens I do a minus 1 here from my previous candidate and I can see that okay well B has one vote here and we will just shift our candidacy to B so for now we can say that B is our new candidate okay so that's fine so we add one counter to our B and then we add another counter and B has three votes now and then when we're back at this a while we do the same thing we minus one from here but these still has the two votes so in this case the majority is the candidate B here so that's the same method we will use to solve this problem so every time we see a different candidate we just minus one from our previous candidates count and if this brings us to a zero what does that tell us that means that candidates votes are no longer valid at that specific point so in this array if we cut that right here we had a zero over here because is both no longer matter as we have the same number of A's and B's right so that's the general idea to solve this algorithm now let me summarize what we need to do in our code before we look at the code so what we need to do is create a counter to do this minus one from the previous candidates frequency and what we're gonna do is we'll just start with this candidate as our majority candidate and then iterate through the array to find who is actually the majority candidate and then we're just gonna minus one if we see a next element that is not the same candidate other previous element and if the counter is zero then we move on to the next candidate because as I mentioned that means that the post bolts have balanced out okay so the time complexity for this is the same so it will be our fan and the space complexity will be done in place so we're not taking up any extra space we won't be creating a dictionary or map so that's why this is more efficient than our previous solution okay well if all of this makes sense then let's look at the code okay so I'm back in the cooler and what I've done is I just commented out with my previous solution with the dictionary and here I have the more optimized solution for this problem so what I've done first is I've initialized my count to zero and I just said the majority candidate to none initially and then as we iterate through our noms array what I'm doing is I am just setting the majority candidate to numb if the count is zero so in the first case what will happen is this majority candidate will be initialized to the first number in the array and then what we're doing is we're checking if the number is equal to the majority candidate then so what this means is if we have like three so if the next item is the same as the majority candidate then we just add account to that majority candidate right so we're it's like they got the boat so that's why we're increasing the count here and if it's a different I'll if it's a different candidate than we just - different candidate than we just - different candidate than we just - account so we're d-- commenting the account so we're d-- commenting the account so we're d-- commenting the count here and in while iterating through this route loop at any point if our count is zero that means we know that previous candidates votes doesn't matter anymore because there are in our boats from the new candidate so that's how it equal to zero and if we if that case happens and we're just setting the majority candidate to that next number in the array okay and lastly what we're doing is we're returning the majority can okay awesome so I have both these codes in the description below so check that out if you want to try it yourself okay let me submit this code awesome accepted I hope you enjoyed this video if you like my videos please subscribe to my channel alright happy coding guys
Majority Element
majority-element
Given an array `nums` of size `n`, return _the majority element_. The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** 3 **Example 2:** **Input:** nums = \[2,2,1,1,1,2,2\] **Output:** 2 **Constraints:** * `n == nums.length` * `1 <= n <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
null
Array,Hash Table,Divide and Conquer,Sorting,Counting
Easy
229,1102
376
hey everybody this is larry this is day three of the july lego day challenge uh hit the like button in the subscriber and join me on discord let me know what you think about this problem uh yeah happy sunday or saturday night depending on where you are this saturday night for me and the contest is in about two hours for the lead code so if you're doing that good luck if not uh which give me all your luck for now then all right let's go uh today's problem is rico sub sequence what uh okay it's a sequence where the difference between subsets of numbers are successive numbers are strictly alternating between positive and negative okay so it doesn't it so means that the numbers don't even matter it's just positive or negative okay and this is a subsequence not a okay i just want to make sure that subsequent does not stop away i've been messing that up lately as well just a few times so uh reading is kind of important okay oh wait that missed something the differences is negative uh positive or negative okay so the numbers do matter my fault um i thought that um for some reason i just started i yeah i don't know i didn't i missed a delta part so i still misread it but you know only like for 10 seconds so 20 seconds so it's okay so guys so basically you're trying to go up and down and up and down or something like this right um okay and the follow-up is gonna solve okay and the follow-up is gonna solve okay and the follow-up is gonna solve this in linear time um so basically there uh so my first instincts instinct is just basically um dynamic programming right and you can do with n is equal to a thousand dynamic programming is going to be quite fast enough if you do some n square thing where um this would be the biggest um uh or the yeah the longest sequence in the dag or something like that and there's like a or you know largest uh yeah longest path in the dag uh longest path in the dag is gonna be n square in a way you know in a without any context or without any like observation um that alone will give us an n square and a correct solution now can we get o of n right or if n probably requires some observation to make it a little bit better the um if i want to aim for oven and some of this as a hint knowing that there is a no event solution i might try to do two things right or a couple of things my ideas are greedy so i am something just live i quality obviously don't know it yet um though i do have the n square solution in the back of my head but if i need to but yeah my idea is maybe greedy will figure it out two is some kind of stacked bass mono uh mono stack type situation um because for every number we're basically i mean we can think about it from the dynamic programming solution right the longest path in the dag is that for every number um i know that i've been i hand waved over that part a little bit but for every number you draw a dag to the previous number and then the two graphs that you can do it with um or not two graphs sorry there's a duo right where you're reaching the current number let's say we have all right let me just put it here then going over the n squared solution real quick let's say for some number we draw a diagonal previous number if um you know there's two versions of the nine say right one is where we get to the nine and then the next number we want it to be increasing or we want the next number to be decreasing right and of course in that case if the next number is increasing that means that the previous number is um decreasing and so forth the other way around as well um so that means that for the here we can draw a dag to the previous one let's say we have a nine that is you know nine next number is increasing that means that the previous number is decreasing that means that there's an edge from nine to four um and from one to nine right so that's basically the idea behind this pro behind n square solution can i do an o of n so one thing that i would try to think about is you know given all the numbers that are smaller than 9 take the min of all those numbers right also i take the max of the or not the max of the value but the max of all the numbers all the things that are inside that number right so i think we can do it with a mono stack maybe um let's see right let's say we want the numbers increasing so um i think for that kind of thing we're trying to figure out the invariant right so here we have for example i think one thing i'm not super clear about is let's say we have something like one for um you know let's say one is equal to one of course and this is kind of like longest increasing subsequence almost from here uh four we have one oh sorry two we have a four and then three we have a nine right um and then now let's say we have a three okay i guess we do three here and then we do a binary search right so i guess in that sense actually yeah i mean i think this is now just you know of course the two you have to do both and then you have to alternate them and group tracking them but now i think we've reduced the problem from o of n squared to n log n by converting this to uh li s right which is longest increasing subsequence and as i said this is dp of course um or you know uh and of course there's an over n log n solution um which we kind of have hinted at here but i'm not going to go over that today because that's still not o of n right um also in that case some of this is a little bit better in that if that's the case i feel like medium's a little bit too easy for it uh or like too low of a rating for it's harder than a medium maybe um okay so is there something even better it's that so we want an increasing so we want something that's whatever and even here right we have we moved to seven but maybe that's okay i mean that's still going to be analog again i don't know that no and i don't know how the stack based solution would work because that's let's say we have one four and nine on the stack and then now the two comes in the two erasers it but then let's say we have another 10 next right well the 10 we actually won the 4 9 and 10. so i don't know that the stack would work so if i have to guess and some of this like it's cheating in the sense that i'm working from this um working backwards from the solution otherwise to be honest i probably would have been one happy with the n square and then maybe even happy to end like well definitely happy with the n log n um but o n i think we have to maybe make another um we have to make some sort of other um uh another observation or something like this right um hmm huh i'm trying to think about the linear solution um for this one and for those of you who might be joining me a little bit late or skip forward uh huh i don't know that i haven't but if you are looking for an n square or n log n we kind of have it we haven't implemented it but let's see right yeah there's sub forms how would you so the max is going to be i don't know huh i mean maybe there's a greedy thing that i'm not aware of but um linear time and i hope that this isn't a linear time based on the fact that you know the thing is you know linear sorting or something like that uh huh i'm not gonna lie i'm having i'm bringing out a bit um hmm don't know that i know this one no to be honest uh oh i guess there is i think i'm just overthinking it a little bit um because i think there is another dynamic programming thing where can i prove it though because basically the idea here is that looking at the four let's say we're going downwards right well if we're going down then that means that um well that means that our longest streak is gonna be down or we just take the previous one skipping this number right does that make sense hmm let me see i mean i think i have the idea to be honest but i'm trying to think about how to explain it and how to prove it um but basically the idea is almost like um like this idea of like digit dp right is because the things i have here are easy to prove for me um so that's why i would gravitate but maybe you have something like for a previous current and again you know that i like doing this though uh maybe only for competitive for real thing don't do it but yeah so that you have some like longest is equal to zero maybe one but whatever um yeah then current is equal to one just because you always have one sequence right um and then here uh rather maybe that's not it maybe what we want is best um uh positive and then that's negative right and maybe they're both one actually and then we don't need the longest and then here then you can we represent them in terms of you know like if the current one is bigger than the previous then what do we do right that means that we want to increase the um so best negative is equal to the previous best positive plus one and then the best positive we just kind of ignore it right we just keep on going um and then else if c is less than p then we do kind of the same but opposite maybe this is even wrong maybe i typed it too fast to be honest uh best positive is going to be best negative plus one and best negative right by skipping this number is this right i might have the signs wrong but um and then we just have to return max to best positive and best negative i feel like so that's my intuitive sense um but i definitely feel like if you're at home and you're like what is larry doing um uh how is he explaining this you're not wrong so i'm trying to think about it a little bit um this is right okay but uh 824 day streak let me gather my dots a little bit to kind of explain this but first of all this is dynamic programming and the way that i would maybe think about it instead of writing it this way is maybe we could rewrite it really quickly uh because i uh because the way that we write a little bit is um let's say get max last digit is positive or last delta is positive say um yeah then you have index and then you also say have another one get max last negative um okay i think i'm going to prove it by code so i don't know so now we want to return max of get max where the last number is positive of n minus 1 i get max last negative n minus 1 and n is equal to length of numbers obviously so here if index is equal to 0 we return 1 right um yeah and then that means that what does it mean when the last delta is positive right when the last num delta is positive then we want to look at the previous one that is negative right so the only two scenarios right um um hmm so basically we have two numbers right so previous number is equal to uh num sub index minus one say and current number is equal to num sub in index and then now if the current number is um hmm sorry friends i got an emergency message and you know i don't like to cut away so if you watch that sorry about that but yeah so now we want that if this is true then um yeah let's see best is equal to one because we always have at least one item if this is the case then what happens right then we want one to take the current max or um get max of last negative because now that you go to the so now we want to add an edge to it um oops right and then now else if the current is bigger than previous then what happens right well if that's the case then here we just oh i see okay i think there was a part that was missing right so if this one number is bigger than the previous number then uh positive of index minus one right and then just return best maybe this isn't even the right code but now i understand the logic um so i think this is the point where uh to be honest and this is very slow but it's very easy to kind of go into your intuition at least for me i lean on experience to kind of view out the exp but i had trouble understanding why this was the case so the reason why this is the case is because let's just have an example right let's just say you have an example where you have one uh actually just like this one right whatever let's say we have this case let's say we're um let's say we are here so the last num so we want to look for okay actually here because then the last number is a positive and then we're going here right so that means that we're looking for a previous number and there are only two cases right let's say this is a two well what does that mean or well okay let's say this is a seven what does that mean well that means that this is the case um and because this is the case we could just continue the streak and then the other example is that this is smaller right well we cannot continue the streak for obvious reason but we can inherit that streak what i mean by that is that so let's say just one two right you have this streak of one two and then in a greedy way what we're doing now is taking the four okay we say okay the four cannot add it here because then it's not a wrinkle subsequence but in a greedy kind of way four can be here right so you basically replace the one two with a one four here and that's basically the idea behind uh this other logic which we had from the other solution as well i'll put bring it back up real quick i'm really slow today sorry a little bit distracted one of my good friends is visiting me from abroad and gives a message to me like panicky uh i'm lost in new york situation so and so it's a little bit timely my apologies but hopefully so with this insight that's basically what this code does um i am usually i am going to uh expand this out and on you know and go over to the deep the how to do the dynamic programming part but that's this is really most of it to be honest um and of course the thing that i would say is that now you have to add memorization and stuff like that but this is really the idea right so now this is last one is negative so we want it to be positive so we have something like this uh did i mess this up hmm i might have messed this up actually that's negative here oh yeah because we the logic is the same but then when you inherit the last thing it would have to be negative so that's why this is the case um instead of positive sorry i um basically going just to be a little bit clearer just to do it again basically if you have a case where you have one two um what we did is we converted to one four with a four and now we're looking for a the next the last number to be decreasing right so that's basically what you're doing um and the next number is decreasing as well because now the four is now the peak instead of the rally right so that's basically the idea here um so yeah so usually i will do this but um i think today there's a lot of things going on this is the solution that i recommend um but with the explanation that we talked about um overriding over inheriting um and this is basically that code written in a different way let me just run it real quick um of course this is going to time out for bigger ends because this is not cached and of course maybe i will typo or something let's see if the previous is greater than here maybe that major signs wrong uh maybe i have the science one it is tricky to kind of get right now that i'm just confusing myself and to be honest i'm a little bit watching it because i'm uh trying to deal with this issue uh but okay maybe i'm just wrong in here but mostly due to either typo or something like that um so i apologize if this video is a little bit yucky but uh but i think the solution is to um you know look into here and then the idea that i would talk about um is just like i said if you have one um why you are able to maybe i had it right the first time maybe i confused myself a little bit actually by writing it uh well it's too bad i think i removed it by accident so um yeah okay but the idea is still that let's say if the last number is uh increasing then you basically want to use this to replace that number but keeping its either valley or the top or the bottom so that's basically the idea um i know this video is a kind of yucky um sorry about that i really gotta run um usually i have better time setting but this is long weekend and stuff like this everything's chaos so uh that's all i have for today uh let me know if you just explain uh this explanation is good enough for you if not ask some questions in the comments come to discord ask some questions happy to answer it i'll see you later stay good stay healthy to good mental health take care bye
Wiggle Subsequence
wiggle-subsequence
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. * For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. * In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`. **Example 1:** **Input:** nums = \[1,7,4,9,2,5\] **Output:** 6 **Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). **Example 2:** **Input:** nums = \[1,17,5,10,13,15,10,5,16,8\] **Output:** 7 **Explanation:** There are several subsequences that achieve this length. One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8). **Example 3:** **Input:** nums = \[1,2,3,4,5,6,7,8,9\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` **Follow up:** Could you solve this in `O(n)` time?
null
Array,Dynamic Programming,Greedy
Medium
2271
921
hey guys this is you sir how's it been going in this video I'm going to take a look at nine to one minimum add to make current is valid we're given a string and a string ends of left parenthesis and right parenthesis we add the minimal numbers of parentheses and so that the represent appearances are invalid well take a look at this because this one is invalid so we only need to add two left one right add the one more left parenthesis bat it to one and this one is three left Prentiss we add need add to add we need to add three references for this one is bad a zero this one is flatted two left right and two left so forth so obviously the minimum add actually because if only one pair is very rare one pair of friends is valid so actually if you remove the valid ones there will be an invalid print is left and to remove to make this valid we need to add the corresponding left or right four like this to four for invalid Prentiss when you ask for corresponding practice to make them better so the problem becomes we need to find the invalid print account while for the invalid Parente account it might be only one case that the right for this is put before left where it says right if you look through this array like this if you just take a look to the first one its left well of course it's invalid right because only one left for instance doesn't make anything now we have a right one it's valid because this is already a left one to the left and this will be valid and then we met the second right Prentiss there's no more left so it's invalid right and then this one is invalid and now that this one it of course is invalid so I think we could just keep track of how many unmatched left parenthesis and references are to make two to two - to get a result right so I'll say let - to get a result right so I'll say let - to get a result right so I'll say let invalid left:0 that in backing run it invalid left:0 that in backing run it invalid left:0 that in backing run it right to 0 this is the count of last Prentice okay Catholic or the right print this right let's just look through for lead character of s we need to f check if capture is left then it must be invalid because we're looking through from left to right if you met the left Prentiss is invalid I will just add the timing winning is Travis who so embedded +1 right now if Travis who so embedded +1 right now if Travis who so embedded +1 right now if it is white for instance what will happen right there is a problem we only check if invalid left count is zero now so it's it is zero if there's no left one we updated with one right if not because okay if it's zero it's not they were there will be one left - in the were there will be one left - in the were there will be one left - in the industry so what we update the invalid left town well - one and finally we will get what well - one and finally we will get what well - one and finally we will get what we will get the invalid left town plus invalid right count yeah that's all so bad simple let's try to some pool or accept it and the we use a lot of memory could this be any simpler head this is I think this is the simple simplest solution right so type of poorest linear we Travis all through all the characters space yeah we used two variables so it's constantly man I don't know why any better solution honest balance we track the balance of left string manage the number rice ring a string in Spanish which spans ero Plus every perfect is non negative balance the ideas come up with balance what is balanced number - this balance what is balanced number - this balance what is balanced number - this number of right I'm sorry is fat it if it's zero mm-hmm I'm sorry is fat it if it's zero mm-hmm I'm sorry is fat it if it's zero mm-hmm it's lost every perfect just non-negative matters about ideas come on if it is never negative say minus one ever negative it means okay we must add huh so answer your balance look through it balance plus 1 or minus 1 Oh a plus 1 is left right it becomes less more we form a the right bound right parenthesis it's minus 1 cool so and it is minus 1 when it is from balance the answer plus minus plus no please answer what is balance hmm I think they should leave this just be the same right I think the basic idea is the same so I ask please ask anyway I think we're basically the same so that's of this one we just did you count the left and right okay up see you next time bye
Minimum Add to Make Parentheses Valid
spiral-matrix-iii
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string. * For example, if `s = "())) "`, you can insert an opening parenthesis to be `"(**(**))) "` or a closing parenthesis to be `"())**)**) "`. Return _the minimum number of moves required to make_ `s` _valid_. **Example 1:** **Input:** s = "()) " **Output:** 1 **Example 2:** **Input:** s = "((( " **Output:** 3 **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'('` or `')'`.
null
Array,Matrix,Simulation
Medium
54,59
788
Oh 780 a rotated digits X is a good number if after rotating you two should buy individually by 180 degrees we can invite number tested it's different from X each stitches must be rotated we cannot choose to leave L know a number is valid if each digit remains a digit after the rotation 0 1 &amp; 8 will attach after the rotation 0 1 &amp; 8 will attach after the rotation 0 1 &amp; 8 will attach themselves to then 5-volt ace 2 5 8 2 &amp; themselves to then 5-volt ace 2 5 8 2 &amp; themselves to then 5-volt ace 2 5 8 2 &amp; 5 will taste each other 6 &amp; 9 OS or 5 will taste each other 6 &amp; 9 OS or 5 will taste each other 6 &amp; 9 OS or voltage at an arrest numbers to nab both rotations to any other number and become invalid now given a positive and how many numbers X from 1 to n are good they remain unchanged after voting you just won't take each stage in the video ok fine yeah so actually so I would say for this because this is easy right because this is easy and if I was incompetent or something and I see that the end is up to ten thousand then I would just do a proof force right but I think so I'm gonna do that but I would also say as an optimization if you get is or interview or something like that you want to talk about it then you could actually generate them digit one by one and only oh sorry I guess technically one two three four so 7 by so one digit at a time and then you going chop off on you don't have to consider was it like three four seven and then you just have to keep an additional variable for kind of to 0 and 1 and 8 because they need a number that is in a two five six or nine right and that's mostly I kind of did away but yeah but I'm gonna do it before us and then we're gonna play around with it yeah and then just you know for in times you go to was it one and you can't go and then you just if good okay yeah okay I'm bad at naming things I'm just gonna called just for now yeah good count and then just return care and clearly you have to declare cut and then now we'd start to just number is good if you digit is okay yeah okay so Wow X is greater than zero no why is your X you should have a lookup table maybe for this problem is okay oh yeah and then you need an additional ball for whether you rotated maybe so yeah okay so if Y is that is to a switch statement switch why it's good ID so we have case one so masuo one a so in this case this is okay so we actually just ignore those was a 2 + 2 5 6 &amp; 9 then ignore those was a 2 + 2 5 6 &amp; 9 then ignore those was a 2 + 2 5 6 &amp; 9 then this is good so we said voltina 0 true because you actually did you know you need at least one numbers to change and this would change that to be true and in the default case we were just want to return for us anyway we just add a tonight not sometimes I'm still in my Python mindset where I don't have to do have to did I do where I don't have too much McCoy right mister for come forth yes two different okay oh well I forgot to uh yeah okay whoops you symbol you know well different where we've all been yeah that's why I got time to me exceed it that's how I keep bugging pretty quickly though it's a little bit slow oh no did I don't well essentially that should be right but Wow I mean I think I just didn't declare a count miss suma those are big numbers that are confusing don't know what's wrong maybe I just watched it I mean I think that's reading an ad to me okay I mean it's still wrong but that's okay one and ten are not good numbers but you knew that why did I get seven foot ten that's two this is easy to debug do i I'm just really bad not declaring default overs today I don't know what my okay just silly mistake for this problem but otherwise is okay so yeah that's submitted silhouetting time yeah well it's oddly confident in this I missed like number but yeah went for this one I think this one is a test in kind of time complexity analysis or just and in that case given n is 10,000 each and in that case given n is 10,000 each and in that case given n is 10,000 each number has about five digits at most that means you only go into 50,000 that means you only go into 50,000 that means you only go into 50,000 operations ish like you know on order of operations per se but like that's not my work which is technically given the input number and then it is n log n is the complexity and technically and yeah and there's no of one extra space but technically if you want to say that n is the input size technically the complexity of this is actually n times 2 to the N and the reason is because you can represent n but just you know 8 bits sorry it bites I'm mixing numbers but yeah 4 bytes so that's kind of why but yeah so that's why half of this problem is easy you know why do so many downloads but it's an OK bar I mean it's four and you could even be trickier if you have to generate them and like the Bala feels like a hundred thousand what can you do it or million right n well obviously you cannot do this well actually maybe even you can maybe to a million maybe I'll be a little tight but like you know let's say a hundred million and you can't right so then you would have to kind of generate them attention by digit and in that case there'll be like seven to the ten or something like that so maybe that is a little bit tricky to kind of do the math white or like such that uh you know 2092 million maybe that's fast enough but I by the way yeah that's what I have for this problem kind of queue it's okay I mean it's like it's right it's aplomb so yeah that's all I have for this one yeah cool love so mystical just decorations of stuff i'm i don't know maybe i'm too used to languages but it doesn't matter I don't know but switching back and forth on languages maybe the reason why I mean yeah I mean I think one thing that I would put maybe just make sure you the rotation stuff because I don't know if you could do else we turn to return floors in that way having one thing is just to make sure that you have to see two five six nine at least once and that's what I have here I mean I obviously don't have to coach I don't know but that's the only place that I see that maybe is a little bit you have to be careful about yeah
Rotated Digits
minimize-max-distance-to-gas-station
An integer `x` is a **good** if after rotating each digit individually by 180 degrees, we get a valid number that is different from `x`. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: * `0`, `1`, and `8` rotate to themselves, * `2` and `5` rotate to each other (in this case they are rotated in a different direction, in other words, `2` or `5` gets mirrored), * `6` and `9` rotate to each other, and * the rest of the numbers do not rotate to any other number and become invalid. Given an integer `n`, return _the number of **good** integers in the range_ `[1, n]`. **Example 1:** **Input:** n = 10 **Output:** 4 **Explanation:** There are four good numbers in the range \[1, 10\] : 2, 5, 6, 9. Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. **Example 2:** **Input:** n = 1 **Output:** 0 **Example 3:** **Input:** n = 2 **Output:** 1 **Constraints:** * `1 <= n <= 104`
Use a binary search. We'll binary search the monotone function "possible(D) = can we use K or less gas stations to ensure each adjacent distance between gas stations is at most D?"
Array,Binary Search
Hard
907
994
Hello hello everybody welcome to my channel today.the problem is his writing and today.the problem is his writing and today.the problem is his writing and oranges in every cell can have one of the value sabse zor divya 1000 restaurant and welcome to lotus on every minute android 4.2 and subscribe is this is impossible 4.2 and subscribe is this is impossible 4.2 and subscribe is this is impossible turn on this problem example for This is the first and the subscribe 22 2008 This dish to will be protein in the first made at the time Mile Siswan Minut 98100 Orange Thursday subscribe to the Page if you liked The Video then subscribe to the Channel subscribe The Channel Please subscribe And subscribe The Amazing spider-man 2 Minutes This All Will The Amazing spider-man 2 Minutes This All Will The Amazing spider-man 2 Minutes This All Will Be That Married Time Left In Here Is To 9 Withdraw From This Channel Recently Got In Dishas Range Suv Vidhi Edison This Is Already Done Services Only The Edison For International Exhibition And Different Series Of The state of this one is the fans and subscribe and share and subscribe to that is behavior initial state to take medicine and Buddhist to first wife rotating air rot in the jobcentre orange is show describe a lot in this to first subscribe The Video then subscribe to I am soft and hotspot of this test case will be why I am so let's take another example which exam is rocky problem a sorry waste is not possible to roll so let's describe channel subscribe in this pound inch and will always be that speed of hina duck Answer Bhi Happy Returns - How Will Solve This Problem Returns - How Will Solve This Problem Returns - How Will Solve This Problem First Of All Will Count How Many Price Oranges Will Have Ever Get Lost In The Present Which Countries Where In Too Variable Subscribe nx100 In This Great Benefit Total 6 and 9 We Need to Do Subscribe Traversal Video then subscribe to the Page if you liked The Video then subscribe to 200 First Maintain Why Initially I Will Initial Ice Cubes Wedding All The Orange Juice Protein And Safar Ke Will Get 0 Sudesh Experts And Present Let's And Subscribe Now Believe On This Are Orange And It's All The Formation Words Orange Yes Sorry For Network Like For Directions After Rather Direction Tractor Cheese Live With 0 90 Number One And A Minus One To Ma0 A Fan Of The Last 20 - And This Is Vivek Us A Fan Of The Last 20 - And This Is Vivek Us A Fan Of The Last 20 - And This Is Vivek Us For Wedding Plus Creative Director Ne This Network Solid Direction 200 F Sweet Words and Phrases of Activities Edison Many Members Vikram One Forced to Switch Puberty 851 Will Give No Assurance to Be a Next Will Go to the Question Will Go to the Element Will Find the First World Will Withdraw pre-2005 pre-2005 pre-2005 mein aa hai to hair one hair raw one hair in one hair and S&amp; hair in one hair and S&amp; hair in one hair and S&amp; P 500 script will be deleted and you will welcome more than 500 way market S2 will update S2 and observed This Entry in India This Entry Namak You Will Continue for Subscribe - 105 Withdrawal Time Will for Subscribe - 105 Withdrawal Time Will for Subscribe - 105 Withdrawal Time Will Tell U Ka Vikas Bindh Jeevan Lakhs Atithi Soft For 1000 151 We Will Do You Do To The What Is The Condition Of WWE Champion And We Are Already Done With All Differences Like All The Price Oranges Already Roadshow Will Have Differ 400 A Hairy Jacod I Have Written To First Time Doing Some Weird Scanning And 10 And Lag Increase Protein And Will Be Adding Deposits Of The Orange I To Stronger Cheese Coordinate* Runner U Will Never Intended Coordinate* Runner U Will Never Intended Coordinate* Runner U Will Never Intended For Getting Ready To Attack Interviewer At A Press Conference On Thursday Will Not Defined By Its Coordinates Loop Top Bottom Subscribe Like Subscribe To Vitamin A This Loop Slows In First Year Boys In Not Increasingly Checking The 100000 Right Side And Subscribe And Share Thank You Inductive Is And Marketed Like Subscribe And Is Non Rotting And Will Decrease subscribe The Channel subscribe our Channel And subscribe The Amazing Uprising Turn On This Week 201 0lx Take Another Example Here Behave second example because like there is no recent cases from it zoom liquid compiling samriddhi code the city has accepted so what is the time complexity of this is 100 time complexity is like and processing all readers element show is opposite van is web portal and orange is orange Sales 100 Time Complexity Of An Where Is The Number Of Sales In Every Day I Am Secure Thank You Feel Like A Soldier Hit The Like Button Fuel Subsidy Sharing Comment Section Thanks For Watching
Rotting Oranges
prison-cells-after-n-days
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`. **Example 1:** **Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\] **Output:** 4 **Example 2:** **Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\] **Output:** -1 **Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. **Example 3:** **Input:** grid = \[\[0,2\]\] **Output:** 0 **Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 10` * `grid[i][j]` is `0`, `1`, or `2`.
null
Array,Hash Table,Math,Bit Manipulation
Medium
null
1,470
so this problem here is leak code id 1470 and this is shuffle the array so given the array of nums consisting of two times n elements in the form x1 x2 and then at the midpoint it starts at one y two uh return the array in the form x one y two x two y two so we're kind of like interweaving the first half and the second half of the array so basically i wanna go through this really quick so let's try to get the output from this test case just so that we can better understand what they're even asking so right off the bat um we're given an n and there are two n elements in here so we actually want to split this in half so we always want to split this in half so it's always going to be an even number of elements so it could be split evenly because they're going to be two n elements so it's always even we want to interweave these two halves so the result array is going to be this is our result array uh we want to take the first from here and then put them in so it's going to be 2 3. then we want to take the second from the first half and the second from the second half so it would be 5 4 and then we want to take the third from the first half and the third from the second half so it'll be 1 7 and if we look at this how we derived it this is actually the output for this test case that we copied so i just want to explain like what is happening so how do we do this so we're going to actually create a result array and our result array we know is going to be length 2 times n but actually we can just simply say uh nums.length simply say uh nums.length simply say uh nums.length because that's going to be the size of it so let's do that and let's return it because we know we're going to and what do we want to fill this up so now i will say one thing uh we are actually using linear space here so we are using for this result although some people don't count the result as extra space but we are using the length of nums uh amount of space so there is a constant space solution but it involves like a 20-bit binary integers and a 20-bit binary integers and a 20-bit binary integers and putting one number from one-half in the putting one number from one-half in the putting one number from one-half in the left side and a number yeah it's just it's confusing so i'm just going to do it this way this is the easiest way to remember and this is how we're going to do it so basically what do we want to go up to n and the reason why is because this is half of the array and at each point we're gonna put two numbers in so we just have to go up to n so i'm gonna go for in i equals zero and like so and then i is less than n so we're gonna loop n times basically we want to fill not only the so at index 0 we not only want to fill this 2 but we don't also want to fill this 3. so basically what we can do to represent that is we can go 2 times i and at i equals 0 this will just be 0. so this will be the even numbers so this will be the 2 the 5 and the 1 in this output so every even number we want to put the number that's just at i because we want to go in the order of the first half so then now filling the second number we want to go 2 times i plus 1. so this is going to be every odd number so i equals 0 this is going to be 2 times i which is 0 plus 1 which is 1. and then we want to fill this with the first number in the second half so see this half right here the 347 we want to fill the first one with the 3. so this is going to be that n which is 3 so n plus i so basically this is like saying every even number is going to be the order of the first half and then every odd number is going to be the order of the second half that's kind of like how i describe it and this is just a straightforward way to do it and fill up this rest so let's go ahead and run this and we'll see um we actually oh yeah that's because i'm assigning it to res i hope somebody caught that so we're gonna actually uh we want it we want to get it from nums so this is how we do that and if we run this uh we'll see that we get accepted and we submit this and we'll see we have 100 run time so talking about time and space complexity as i said so we have time and we have space is linear because we are creating extra space for the length of nums and some people don't count the output array of space so you could say it's constant but i don't know there is a way to truly get constant space is what i'm trying to say and time is o of n as well because we are ultimately accessing n elements so yeah just pretty straightforward this is one of the easier ones i hope you guys enjoyed and thank you for watching as always i appreciate it
Shuffle the Array
tweet-counts-per-frequency
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\]. **Example 2:** **Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4 **Output:** \[1,4,2,3,3,2,4,1\] **Example 3:** **Input:** nums = \[1,1,2,2\], n = 2 **Output:** \[1,2,1,2\] **Constraints:** * `1 <= n <= 500` * `nums.length == 2n` * `1 <= nums[i] <= 10^3`
null
Hash Table,Binary Search,Design,Sorting,Ordered Set
Medium
null
526
E Agri Baby Pump Co Default Comment Wednesday Free of Cost January 1954 Channel Soft Stimulus Problem Yes-Yes Arrangement at Soft Stimulus Problem Yes-Yes Arrangement at Soft Stimulus Problem Yes-Yes Arrangement at SIDBI Question and Definition of These Leaders from Middle Arrangement for Every Side The Full Form of ID EP 155 Let's Understand with the Help of Kar 2017 problem 2012 decree given in this remedy that this is the sleep foundation 100 gram piece minister ok tell me let's call heads and focused example solve Welcome to The Amazing Shabban come to hand to come on started slowly by politicians and possible this For the number of combination for the formation of women member and so will be there the true meaning of to real tutorial 30 A to Z to Congress Jabalpur city related to real 53.22 in 212 me related to real 53.22 in 212 me related to real 53.22 in 212 me also successful six for the basic mission editor simplicity Vithu Mauli E Enjoyed A Tu So Let's Char Digit What Are The Different Solution Feature Available First One Will Be New Approach Will Be Call Getting All The Permissions Supports Difficult To Give In The Oil Setting On Computer Monitor Embassy In Checking For Information Weather The Given To Cash Also And not so will be chatting with want to sona let's take one come true *ka mohan *ka mohan *ka mohan that when nothing but for millions of physical two to two and aapke sunao ki bihar to check with position but index is given is 30 given one does not possible Sleep for one night This is possible Schedule arrangement for two years Back to Saudi Arabia Switzerland Travel condition Specialty Hi to 10 worst condition is nothing but form of is divisible by I am afan So did they Number is divisible by indices Next can also be given equal To Indian state of 0512 is divisible by one please like this the invisible bittu no but reverse kidneys password reset in the condition which means one is the inactive subscribe The particular number 16 2011 to this condition this side effect please also through the 172 if those arrangement. Sohan Seervi Returning 2392 Stop This Way Read This Beautiful Arrangement Was Not But How To Return Member Of Medical Arrangements For The Formation Are You To Color Invents But Did Not The Case With Any Co Decree All The Best All The Combination All Permissions And Not Different Kidney Free So Similar For Anything Different From Safar Nahi That Approach Time To Objective Of Interactive That Is Vikas Vihar To Create And More Informations And E Have Different Rooms Space Complexities That Bigg Boss BTS Reaction To Calculate Developer Missions This Quantity Let's See How They Can Reduce Type of Kshatriya our second approach taken to approach will be backtracking in will be taking all the members from one to two and will be taken with varieties divisible by portion and note and is the question is divisible by political number and not saying this they will also checking Key Channel Free Number For A Particular Position And Anti Shatter Number Is Not Well And Will Stop Calculating The Formation Swift Care Number Airtel Particular Question Relates With The Help Of And Example Of Board Select Cmo Office To Sahi Earliest One This One Of The Formation Of Physical Second So Information Vacancy Date Position Will Be Warned Come To Amrik Sodhi Not Divisible By Two Is Not Visible Best Hans For Doing This For Everything Will Be Checking Weather This Particular Combination Is Possible And Not So Here This Is Not Possible To Its So Examination Year Will Be Calculated in all the form actions where this position is not equal 3 has been calculated and hence the number of formation subjects related Will be reduced In this year this aunt's will be wife inspector real 200 in english also android user time complexity for most of the cases so let's see how they can control the contraction using back rakhi hair railways payment is equal to zero this vivek what is the one Between how to return home and combinations of possible only dutiful arrangements and passwords Amazing fonts Next in this will be keeping track of mother did not exist or not so definitely lies with fonts for that I am and we gas calling [ __ ] that I am and we gas calling [ __ ] that I am and we gas calling [ __ ] yes man earring Inch Plus One Range Development Wear Generating Up To Embrace Of Bubbles Even In Next Which Give Any Problem I Your Show 10 Akhtar And Brett Lee Stuart Swift Is Recreating We Were The Shield To Calculate Isi Mitti Ne Parameters Of Income Of That In The First Indian To Be calculated and activities nothing but for this account with passing all rate related play list dacoit next and read needs redoing and account a parlor cancellation complete next week declaring and calculate mitra hai be taking parameter seedhi for som will b s n l n ujjain inform them Will be india limited ok alerted royal look for it in the and 1kw oneplus one big boss and is a's family tree will be setting and condition soegi accept in opposition has not returned by respectful number he visited of i that departmental falls upon it's not good to Find a that aapke khand play list in condition this and further in condition thing and position were percentage of oo in the side of any political 204 let's percentage position who is equal to zero hence office collection itself is satisfied and also setting that was leaving and Visited turn off I will support you in next will be calculating message particular number hokar subah dance number sony xperia entry meeting and position to ₹15 internet number meeting and position to ₹15 internet number meeting and position to ₹15 internet number a big salute to calculate off self work in the same position will be in preventing the next question And Libido Vijay Pal Singh C Mystery Turn On Meter Middle School Work 1919 Modified Next Chief Making This A Small Quantity Use Remedy And Only Numbers That I Think These Pilots How To Write Capital Member Condition Novel Also Intermediate Account Yesterday Morning Triveni Simple Solution That When Someone Jain Vikram Great Gambler Till Life Definition Of All Of The Lambs And Satisfying This Particular Condition Hands At Particular Formation It Is This Time And Condition 100MB In Preventing Details From Soen Hair Tips Position Greater Than In These Dates For Have A Plus Recording Want 's member solution let's run record organization 's member solution let's run record organization 's member solution let's run record organization meerut 's side back incident sis youth self 's side back incident sis youth self 's side back incident sis youth self and a game fighting against that for it's quite certain code that awadhi status mention this dynasty click on submit that which such and submission and accepted 100 in that They can solve this problem using back tracking by restricting the number of pharmacy subjects related Are hope you understand this problem till hide so gas I hope you like this video please click on like button and don't forget to subscribe to have been active In Both LinkedIn Instagram Platforms And Abroad In The Rings In Edition Bluetooth You Can Join And Biscuit Community Issi Cord Tak Samridh And Isi Want To Help Others So Let's Get Benefits From Your Knowledge Delhi Road Wheeler Description Box Us Dashrath Is Video Gas Benefit Subscribe &amp; See Video Gas Benefit Subscribe &amp; See Video Gas Benefit Subscribe &amp; See Thank you in next video
Beautiful Arrangement
beautiful-arrangement
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true: * `perm[i]` is divisible by `i`. * `i` is divisible by `perm[i]`. Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_. **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** The first beautiful arrangement is \[1,2\]: - perm\[1\] = 1 is divisible by i = 1 - perm\[2\] = 2 is divisible by i = 2 The second beautiful arrangement is \[2,1\]: - perm\[1\] = 2 is divisible by i = 1 - i = 2 is divisible by perm\[2\] = 1 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 15`
null
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
667
864
hey everybody this is Larry this is still me and Lisbon um yeah doing a lead copy for the fight I guess today's program is 864 shortest map to get all keys uh hopefully soon we'll return to normal schedule for a little bit uh okay so this is a problem that I haven't saw before so that's an excited exciting thing to do uh though maybe the name of the problem gave it gives it away a little bit but we'll see so the shortest path to get our keys okay so yeah oh just day by day okay I didn't really read all the details I'm not gonna lie because no one can read that fast I kind of just skipped ahead I just it just occurred to me to get all keys part and then I look I saw the grid I was like it seems like it's gonna be um what's it called traveling salesperson bomb or ham path or something like this I guess it's tsp because empath is unrated but um yeah so then I was like well that's not going to be Gucci uh and it's not quite that right it's to get all keys uh yeah so and I was like well in those cases at least in the most General uh example uh it's gonna be exponential right and if it's gonna be exponential then the constraints have to be pretty tight so this is why I scrolled straight down the constraint I said okay well if the constraints is six it should be okay um okay so basically this dirty by Dirty uh good size so that's gonna be 900 times 32 for 2 to the six is should be good enough right what is that's like well that's less than 100 Cube or what why did I say jump to 100 it is less than 100 Cube which is a million so yeah so we're doing good on time complexity or in the number of states and then we're only visiting up down left right so there's only four so then so yeah so that should be good enough for me to kind of get go going and that's what I'm gonna do uh but the idea is that uh you just basically keep state right so State instead of just the location which is X and Y you also want to keep um a set say a set of keys that you currently own right and a set of keys that you currently own um you can obviously represent them with a set but I'm gonna use bid mask because it's just more natural to me uh especially for six items uh there's almost six keys and the locks don't really matter you don't you just have to acquire all the keys you don't have to acquire all the locks um it's just that the locks determines where you can go right uh at least that's my understanding so yeah oh and then in fact that's the explanation example one so yeah so we're pretty good here so yeah let's uh let's see what is the other thing so if there's a store employing so we can do something like uh just to pass the starting point right and then I guess that's the only thing we need and the keys are ABCDEF and ABCD I just goes up to F right so yeah and we've tried to determine how many keys okay so I mean I'm with keys is the lower case or uppercase okay lowercase is key so then we can just do just count the number of keys because it's not a keyword that's actually maybe surprising but if I can write this a little bit cleaner but I it is fine I think uh you only do that all the time three times anymore Okay so that's the number of keys so then yeah so then we start um over breakfast search really uh on this new graph of uh x y and keys right type it correctly right uh and I mean you know and this is just but we also want to set up like a distance thing multi-dimensional uh multi-dimensional things always kind of multi-dimensional things always kind of multi-dimensional things always kind of is a little bit tricky it seems like in Pipeline and I always have to like just be a little bit careful oh yeah okay so now x y um and the distance as you go to press of X my mask oops it would be helpful if I could type the m okay thank you m uh but yeah I'm going to set up the directions which is still up down left right and then yeah um yeah I mean we can if mask is to go to and this is just 2 to the power of keys that's really or it is and this is to the power keys of minus one uh as I said I'm using bit mask I'm not going to go over a bit mask in this video but suffice to say that it is basically um a representation of a set right uh basically each bit can be true or false representing whether the corresponding letter A to F is the key a to F is um that we acquired it right so yeah X Y plus d y and then the new mask is equal to um mask if well let's make sure that it is it within bound first uh then maybe we'll move the new mask this way and then if to do realistic grid of N X and Y now we have to uh do some maths well not maths but just uh passing say so if this is a key and then we just obtain it so that's nice right I mean key string is the ABCDEF right okay right and then otherwise and oh yeah lock string which is just I mean I'll type it out but you can also you know use your imagination on how to write this a little bit better okay so a little bit of N X and Y is in Lux and so this is the index right so if mask so we have if we have the key then we can go if we do not then we cannot go away so that means that if this bit mask as you go to zero uh then we have to continue we cannot hopefully that's right I mean don't take yeah I mean you're seeing what I'm doing live and if you watch enough of it you'll realize that I make a lot of mistakes so don't you know uh yeah and then now that this is all good and done we can do the BFS point right yeah and it's NY and mask and then pass up and accept it nxny and mask is uh and mask is equal to D plus one and then other way and we return negative one if it's not possible yeah oh I forgot the other thing that we have to terminate which is that the walls the head obviously is you go to uh continue right foreign test cases uh is that good are we Gucci I don't know let's give a summary I think the idea is right maybe we have some implementation silliness oh no it's a good time out because we didn't terminate early I'm trying far huh uh let's take a look why is that why does that tie me out oh I'm dumb I forgot to um I forgot to do the breakfast search for that is a critical part wow new mistake hues new mistake here right so uh if D plus one is less than basophonics and Y and mask uh then we do this stuff or alternatively we can just do the opposite of this WOW Larry doesn't now do BFS as we were talking about right so uh somehow we've got the other ones correctly but yeah there you go maybe I went a little bit I wouldn't say I went a little bit too fast but I was just there's a lot of things going on so it's easy to forget things because I forgot uh like this and yeah there's like four things to do though that one should right uh but yeah um what is complexity here right it's gonna be all of art plus c but with another Factor but I'm just gonna say that first so this is R times C because that is you know breakfast search that's the number of cells that's the number of nodes that's the number of edges because number of edges is four times whatever kind of right uh but it's also gonna be times two to the K where K is the number of keys and this is not just only here is that theory again I guess so yeah um that's pretty much it uh that's the time and space in the worst case uh though I think a lot of those states are not visitable so you can maybe make some optimization based on that um but yeah um that's all I have for this one let me know what you think stay good stay healthy to get mental health I'll see y'all later take care bye
Shortest Path to Get All Keys
image-overlap
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some `1 <= k <= 6`, there is exactly one lowercase and one uppercase letter of the first `k` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return _the lowest number of moves to acquire all keys_. If it is impossible, return `-1`. **Example 1:** **Input:** grid = \[ "@.a.. ", "###.# ", "b.A.B "\] **Output:** 8 **Explanation:** Note that the goal is to obtain all the keys not to open all the locks. **Example 2:** **Input:** grid = \[ "@..aA ", "..B#. ", "....b "\] **Output:** 6 **Example 3:** **Input:** grid = \[ "@Aa "\] **Output:** -1 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 30` * `grid[i][j]` is either an English letter, `'.'`, `'#'`, or `'@'`. * The number of keys in the grid is in the range `[1, 6]`. * Each key in the grid is **unique**. * Each key in the grid has a matching lock.
null
Array,Matrix
Medium
null
81
Hello hello friends today jasveer voot previous song setting 9th medium question hum kya hai amazon means that we who and subscribe to the channel to that sugar or us kya game banta hai an increase pregnant we have to duplicate shiv from this subject Chinese element like this element appears in the best means if you have not subscribed to the element then please subscribe because tha ke wallpaper from that networking is good ok I first few words pimples decide again called one my number is ok one The person is I have cleared the account and accounting middle element how many time set videos in the past so now what will we do in this and enter further now I have said that people will take let's know let's run below is the bike price loop to Amazon one two three four five six Kabir will subscribe the value of seven six digit i, in this way now put this number here first, then its number is number 19 i for number 34, Akshay lives here, this is our number which is right from our number, what to do here now. What will we do with this account, this lieutenant two, we will add plus time to the account, okay and the value of five means what does it mean, we got to know that we should also see that means that this element has died, so again. In this it will also be related to the number, again it will come under this group that the value is also equal to one and this boys number is equal to one. Yes, then we will check again that the value of the account was the value of the account which was improved for the first time, everything is fine. The value of the account is laddu, this water is an ad, so what can I say, a rally of great use, someone will do the treatment, bye-bye, it someone will do the treatment, bye-bye, it someone will do the treatment, bye-bye, it is ok, and the bank also prevents IPL, the value of the account, why will the idol increase, ok, this means even in the media. It's gone, this is our number, this number is valve ok, so how many times has it been cleared, cancer is happening, now I again got the news that it will go, is it still ok, what is the name of this two Robert, this time this condition will be cured, messages from the village. Already this has happened twice in our darkness, now if these traditional things will not satisfy then what will we do, conditions will be imposed from those places, what will we write in the form of help, which is our account, great update, Hi Dad, will be heard, okay, so I returned to that village. And we will keep the equivalent from here, now we must have come from here, so it means that this element, turn off this element that after shifting the address, what is this, but this achieve, this girl is fine and when this limit is less than here. So this is the scheme, this device number is more, now it is two, which is the circle of railway index, it has been touched, so we will use this software, then again the value of high will go, now our IV is the same, the value of the account. Will check that the number is turned on so it is found, what is the number we have but and the name has been assigned, now this one, this outer condition will be satisfied, okay, what will we do in this, we will put a mark that the outer one is in good condition for that. This will mark the bell, what will we do here, which is our number, which is the meeting at very o'clock, we will give it to Gram Fennel, it is fine and the value of the account will go, the account was created on equal to two, but we saw those shortcomings and what did we do on Now which feather has come, we must have got this condition tip that the number record length is fine, now what happened, will the edition run outside, what have we done here, the number is called the number of Mata Suhag, what have we made different to it, is there any special one? We have become white spiders, now what has become of our number, what has become of our phone number, what has become of the value of the account by mixing something, now the value of the law will be measured, so look carefully at the hair and the number is honorable, use it once, then for that we have to work. Pt is in Ayurveda India, it just means that first it is fine here, then again I have gone to look, checked this is the loop and the second idli sandwich, the subscribe number is this number, this channel has been subscribed, now that I felt like the factory and the i20. Now the type will be impressed, in this position there is number 11, okay this number, after using the number for some other purpose and subscribe, from here, we will take out the length of this post, its length LED notification, its length is returned 500 This is how we will do and what we have seen in this is that we will chat elements right after so how did it get its time thanks to this okay and the specific Oppo A37 is okay this way what we did is we modified the same Hey we There is no ad or anything in it, if element national is mixed in it, then this is what is qualified, this remedy has been received and this point and this is what I have written to you here, according to this thing, what is the tiger pin number? For this, we will send the loudest that if I ride a bicycle then subscribe My eyes have to be looted, I will check, I request to number, this is it, then we will give 12 cycles, the account value is Hussain, it is okay if electronic, we will cook for 10 more minutes, but if it is FD account statement. What will we do? We will do 914, okay? Out of that, we will make admission form for the IS intense pain limit and it will be cleared from here through quantity printing machine. Okay, and if our mum son is not equal to the number, we will put a white sign on the number. Will finally give Bigg Boss increment and have also added why not be a fan of this video channel Time to subscribe our Channel press The Light a
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
190
hey guys persistent programmer here and welcome back to my channel so in this channel we solve a lot of algorithms and go over really quick questions so if you haven't subscribed already go ahead and hit the Subscribe button smash that like button because that helps me create this content for you guys so without further Ado let's go ahead and look at today's problem we are given a 32-bit unsigned problem we are given a 32-bit unsigned problem we are given a 32-bit unsigned integer and what we need to do is reverse um the bits we are given so if we have an input like this what we need to do is reverse all of this so that it returns this output here so we're literally going to take each bit and reverse it so let's look at how we can solve this problem so we know that we need to return a result variable right so we are going to go ahead and create that result variable we'll say res equals zero so this is what we have done we have created a place for our result now we also need a temporary variable um to hold the values that we are shifting so we will say temp is zero and we are going to need a way to iterate through um all our binary digits here and to do that we know we will use some kind of loop right so I can go ahead and say we will use a for Loop so far I in range 0 to 32 we know that we need to iterate over all these um bits so that we are able to change um and reverse the values so this is our first step we need to do is we need to interrogate each of these bits to see whether it's a zero or one and in bitshift offer operations the easiest way to do this is and something by one right so if I add 0 by 1 I will know whether it's a zero or one because the only case I will get a one is if it is a one and one will give me a one so we can use the end operator to do this so okay very good we have found out that this is a zero so I've used the end operator now what I need to do is position this last bit here um to the front so how do I do that right so to do that I've created this temporary integer here and we will need to move this for this case we will need to move this 31 times forward right because this is at the 32 32nd position so let me write out the code so it looks it makes sense how we are doing this so first thing I will do is perform this find out what this last bit is right so to find out that I can call this the least significant bit so LSB is going to be um equal to Ben so this is our input here n and we are going to times it by one okay so we have our last significant bit which is good and we know from the result of this whether it's a zero or one now we want to set the temporary bit here so we'll say temp is going to be um equal to so we will take our last significant bit and we are going to move it forward so we are going to take this and move it forward so we will do this and how do we know what is how many places do we need to move it forward right so to get that answer we can take our uh 32 bits that we know is that is the number there is and we will minus it with I sorry I made a mistake here this should be 31. because we are at the 32 position already so we need to move it 31 times forward so this should be 31 uh minus I so in the first iteration I is 0 so we know that okay from the 32 position we need to move it forward 31 times to be at the first position here all right so now we have our 10 variables set up so we have the order correct now all we need to do is put this in the result right so we need to move this from here to our result so I can say that to do this we use our or condition so I will say result is going to be equal to the whatever is in the result already which is zero because that's what I've initialized it with so it will say result or uh our temp so I will say result and temp so we are taking our temp value and we are using the or condition to or it with the result so this will give us because we because if you do an or condition you are taking that same value and putting it over here last thing we need to do is process our next value here in the N right so how do we do that how do we uh say like okay we're done with this last significant bit what we want to do is process the next one here so okay maybe I should make this more clear here so we have we are Ending by one here right so I can say that okay if I have all these um these bits to process and I'm done with this one all I can say is okay let me um right shift the end so what that will do is remove this and we are going to process again with and with one this last uh bit here which is what we want to do so we will say n is equal to and right shift by one so this is how we are getting to that last bit and the last thing we are going to do is return the result so I will return res here okay let's give this a run okay awesome accepted and submit yay success
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
1,184
Hello everyone so this is the next question distance between bus stops a bus from a stops number from 0 to a small form circle not the distance between pairs of next stops distance at a i distance between the stops number i and i psv Basically, we have to return the shortest distance from the start point to the destination point. Firstly, we can apply the circular method in this and if we want to go even simpler then we can directly return only one distance from the start point to the destination point. Let us take out the sum up to and the remaining sum will be taken by the total of the sum. If we compare the minimum with the remaining sum, we will return the minimum of the two, like in this example, distance tooth 4 and Starting is from zero to one and its distance is one so ok take another example, some summation yes, starting is zero and destination is two and what is its summation 1 + 2 that will be and what is its summation 1 + 2 that will be and what is its summation 1 + 2 that will be and as much as remaining Like total, how much is the total sum, then 4 + 3 7 8 9 how much is the total sum, then 4 + 3 7 8 9 how much is the total sum, then 4 + 3 7 8 9 10, if total is 10, then 10 - 3, how much is the seven, then 10, if total is 10, then 10 - 3, how much is the seven, then 10, if total is 10, then 10 - 3, how much is the seven, then three and which of the seven is the minimum, we will return it. Done So for this we can do this, first of all we define an int sum or the total sum will be of the circular loop which we will assign from zero and there will be an int which will show us the minimum distance or distance between starting. Point and destination will be the point, then we would define it with A and write the same. This is done. First we will check. If we assume that we have given this first, like the starting point is one and the destination, if we have given zero then just If there is an opposite, then for that we can do that if start is greater than destination then we will swap start and destination. This will mean that we will not get confused if starting is if we apply a for loop from the start point. So it will take it from the initial point, if the start point itself is getting bigger then it is swapping it and after swapping, the starting point will be minimum and then we can apply a for loop from I A I to Start I. Lesson destination and aa plus i plus is happening like how to know that start if start is bigger or destination is bigger then we do aa minus i plus so we do this it will be easier than this method that we Before doing the swap itself, we are doing the initial check so that there is not much problem, then the sum plus equal to this one distance, the distance of the position will continue till the destination and then we will put another for loop in which the whole sum will be like I equal. Size of distance from t zero to i lesson distance t okt size and i plus pis and what will happen in this, we will store the sum total in this and the same method will be same, only all the elements are being added in it, distance of eight and at the And we will take the remaining which is equal to sum of total minus sum and just in return we will do this, return the minimum of both which is minimum and return minimum of ama sum so sum is a distance which is from start to destination. The sum of is being added and R is the remaining from the total which is like th 4 is a remaining then its value is then which will be minimum among the two and will return this sum is initially defined from zero and all the rest Correct so let's run the code ok so all the test cases have passed all the test cases have been accepted so this is the right answer thank you
Distance Between Bus Stops
car-pooling
A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given `start` and `destination` stops. **Example 1:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 1 **Output:** 1 **Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1. **Example 2:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 2 **Output:** 3 **Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3. **Example 3:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 3 **Output:** 4 **Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4. **Constraints:** * `1 <= n <= 10^4` * `distance.length == n` * `0 <= start, destination < n` * `0 <= distance[i] <= 10^4`
Sort the pickup and dropoff events by location, then process them in order.
Array,Sorting,Heap (Priority Queue),Simulation,Prefix Sum
Medium
253
229
uh hey everybody this is larry uh so i don't usually do this but um i'm gonna do the explanation first and then you can watch myself with live later uh in general for the most part uh i know what i'm doing but this time i actually ran it um actually i still kind of did mostly what i wanted to do but i did do it way too um i went to a hiccup so and you could see it watch it live after uh this but uh but yeah i just want to do an explanation in the beginning um yeah hit the like button hit the subscribe button join me on discord and today we're going to go over today's prom majority element for day 22 of the september daily challenge so the first the pre-record set that i would think the pre-record set that i would think the pre-record set that i would think that i think you should know is about the bullet more majority algorithm uh there's a link here i'll link it in the comments and yeah and then the idea is that we extend it from going over n over two times two and over three times uh so that's pretty much it and the idea is basically extending um and you know when you watch me solve it live i actually explore some of these ideas and thought process so i definitely recommend uh staying for that uh if you want to see the live thought process of a problem that i haven't solved or um i don't think i've ever solved this uh before so or even looked seen it before so it is new to me but basically the idea is that having two candidates it's um we're gonna go and so to convert it from n over two to n over three we use two candidates instead uh and having two accountants as well instead of one count and the idea behind baltimore is that you know you have this kind of uh majority thing where you just count the number of elements that in a way you count the delta of the number of elements that's in it uh in a candidate minus the number of um the number of uh votes that is for non-candidates right votes that is for non-candidates right votes that is for non-candidates right uh it's a tricky way and that and the majority algorithm works only if uh these elements exist which is why we do a second scan later but so how does this generalize to one dirt instead of one half well you know it starts up the same uh for when if we when we get a vote uh and it's for a candidate that we already have then we just increment the row uh otherwise you know we kick one of these people out um or we attempted to kick one of these people out or we just decrement both of them the key point to notice and which i didn't during the video is that um this only happens half the time because it would require both uh chem one and count two is not zero so if one of these is zero that means that it only that row only counted half the time um so from that you get uh that's the only invariant that you need to solve this problem and then that's how you have uh the candidates uh at the end of this you would have candid one and two in the thing in the variable and then you have to do a final loop because you have to assume that they assist and then you just check that uh it reaches one third um so this is a very short explanation uh for sure uh i go into a little bit more detail when i solve it live but i just want to kind of go over the code because it's a longer video today for that reason uh because i made a typo but i thought the album was wrong so it happens um and yeah so the complexity of this will be linear time because uh we do over one work per element all everything i highlight is all one and all this is obviously all one so this is going to be of n times uh for complexity we only have four variables five variables six variables something like that so constant space as well which is the requirement that is needed for this um yeah as i said this is not a uh an algorithm that i've seen very often even in the majority case uh let alone the one dirt case i don't know what that means but uh so you can take as you it mean both on interview or competitive um yeah that's all i have uh hit the like button hit the subscribe button uh join me on discord and you could watch me actually solving this live next hey everybody this is larry this is day 22nd of the ditko daily challenge uh hit the like button the subscribe button join me on discord and let's get solving this problem live majority element two okay i guess it's probably similar to the first one with uh the broiler more algorithm uh that's what i'm going to uh i don't like so uh um so yeah so i do solve this live so sometimes i'm gonna run into some hiccups uh so bear with me for a second i don't think i've used this before uh or this problem before uh i'm gonna put a link here uh i just googled it real quick uh but that is the algorithm that you should know uh as a prerequisite for this uh but and you know i mean i don't know how practical it is when do we use but it is just kind of something that i figured i would need um but i haven't know how to solve this before but my guess is that uh given that n over three uh you know by pigeonhole or whatever um at most it's going to have two elements right because if similar to um because if you have more than three elements that appear more than n over three times then you have more than 100 which is obviously not possible so from that um we can just maybe keep track of some counter and then figure out what are the possible uh ones i'm so i'm not gonna lie for this problem um i haven't thought this through and i haven't seen this a similar problem before other than knowing that it's boiling more so and i'm not well i'm not that practice on this farm so bear with me and let's kind of work for it together uh that'll be a fun challenge uh for today so let's go for it uh so for x and nums so okay so what is how would i think about this right so you so on the two people brought a more algorithm if i remember correctly and hopefully i do otherwise um otherwise something will be tricky is that basically you're trying to find the delta of um of one element and everything else right so yeah so and what i mean by that is that um and some of this is pigeonholed but basically let's say you have uh and i'm just explaining to two people or two uh two elem or uh majority version which is n over two version um which is that if you have something that you know let's say you have uh 15 elements right what you're looking for is something that appears eight times so that means that if it appears eight times then or more then you have um a candidate that a that has uh that would end up with plus one at the end right because it shows up eight times and so forth um so yes i think that's what i'm going to do with a similar method of uh but it can tr instead of doing one candidate i'm going to have two candidates and yeah um i think the thing i have to think about that i'm a little bit uh hung up on right now is just figuring out what happens when you find an element that isn't uh one of the two candidates right so basically you have candidate let's say you have uh the first candidate one you have candidate two uh let's say you have something that appears like some random x right uh do you decrement from the first one or and the second one or just the first one or just the second one right um well you know that if x appears what that means is that okay well maybe it'll be easier if i work out a case so basically let's say uh let's say we have 15 elements or 15 votes right uh let's say can they one already have four votes and candidate two only have two or so let's say yeah now you're voting for a third candidate larry or i don't know uh then what does that mean that means that in order for candidate one to have one third of the row it would decrement by one and so is this one is that reasonable i don't know i'm gonna play about so the tricky part for this is just the visualization is already relatively ups i don't know i wouldn't say obscure it just doesn't come up damn often this algorithm um even in competitive so the visualization is going to help but let's um i'm going to play around with sometimes it helps with uh people have different visualization techniques and i urge that you find the visualization technique that works best for you uh sometimes uh i have pen and paper already uh and that's what i'm gonna use um and sometimes i just write very short snippet of code uh that simulates what i want and then kind of use print statement or something like that to kind of visualize what that means for me so i'm gonna let's uh let's get started on that so let's say we have candidates one is equal to say none right it doesn't really matter um candidates well okay and it's two is you go to none count one is equal to zero count two is equal to zero right so okay so if count 1 is 0 then we want to assign candidate 1 to x and then count 1 is equal to 1. i mean this is just similar to the original um for the more majority algorithm so i'm just writing it out and then kind of visualizing what that means is as uh and try to figure out what the invariance could be right um okay oh actually i have to make sure that it's not one of the candidates he uh um usually i mean this is the k i think this is the order i do it in for two uh for majority ran over two but i think that in this case it may not make sense so uh so if this is equal to candidate one then count one l if else if candidate two uh you increment by one um let's just say and then just continue make it easy um and then else this is a new number right so we either put it in or this is a uh we have to subtract from uh count one and count two uh okay is that okay enough hm uh i think this one will be really illustrated uh is it straight sorry i can't even english right now uh it will show us it'll help us visualize the most so yeah so now we return can it uh okay so results is to go to empty list if count one is greater than zero and we still start append candidates one if count two is greater than zero we sell starter pen candidates two and then just return results uh i don't think this so this is not finally this is not what the quick uh this is not right yet um because we still should do a pass to vertified uh that they're the majority or the one third majority but i just want to see real quick what this gives us uh so this gives us two uh again that's because of the rotification step right um this looks okay but i want to see for visualization i wanted to see the progression of uh the states as we go through them uh and this one is a little bit tricky to do because we have continued statements but we're going to try oops okay so yeah put one in there that's one two three and put it three okay three one three two and then now whatever you see a two um goes to two zero and now 2 over ticks to be honest i'm not that confident about it even though this seems ok so let's go do a for loop again for x and nums um if x is equal to candidates 1 um let's just do let's reset the count real quick i think that should be okay uh and then we just vertified that if now in this case it's up greater than zero is and over three four exactly right so uh let's just say target and then we'll do the math okay so this gives us okay so let's um so usually i so in a normal setting i'm going to play around with more different test cases uh let's actually do that real quick uh but for the most part um yeah i'm going to try to think through different scenarios different ordering of the stuff uh but in the interest of time i'm just going to submit just to kind of see um just to see uh how that goes so yeah i didn't actually consummate that one but okay i'm gonna submit and if we get a wrong answer that's okay because then now i can see what the situation is okay uh because ways right now i'm still trying to understand the problem and that's part of the learning is that uh depends on what you want to practice for right if i want to practice for a contest and i want to practice for correctness um then i am going to you know just think for these different cases for now uh i'm just practicing learning this thing so i'm still trying to figure out cases that um you know in time efficient way just like what am i doing right hey everybody uh so usually uh this is gonna be a live uh recording um and it was a live recording but i in inserted this kind of quick disclaimer because uh so apparently what i did was i had a typo uh and if you follow a full you'll see it so um so i'm gonna put a link for you to skip to the end where i explain the uh complexity and stuff like that or you could watch me try to solve it or try other techniques uh and try to visualize the problem for the next like 20 minutes uh that's my bad whoops sometimes it happens the best of us so i hope that you also learn from that if you like anyway thank you so okay so in this case that is very clear why uh this is my current algorithm is that right because uh for the ones it drops off because there are enough unique elements which actually should be in the case i at least try really quick uh one is clearly the answer but because we have nine um the three four five six will delete the answers from these so i think now it um now i have to think about how this generalized so my generalization attempt was not good or it was not accurate um now i wonder if you know we just do it one at a time because i think the thing we want is that uh so what does that mean when one none will come in that means that i'm thinking just in general maybe that i need to double everything so that's my thought process right now and why did i say that and maybe the constant isn't right for doubling but what i mean is that when a rule comes in uh what does this do to it right so your target needs to be this number of numbers over three and when a nine volt comes in that means that um that means for every two rows that isn't your number it cancels out your previous row right so that's how i would think about it and from that um that was just there did i just had a typo i think maybe this is a typo as well but so that's actually pretty bad i don't know if i just noticed it or whatever but how did that uh and that one my answer so well huh did i just get really lucky on a typo uh now something's weird what did i change how come my answer is really well uh that's awkward well this should definitely be one regardless um but i think now instead of uh incremented by one it should be you go to buy two because every two votes that you oh sorry every one vote that you get will get cancelled by two votes so which so that you can actually do plus one for the count of number of rows and then oh this is two and then subtract a half every time you just get another row but um but uh just to make it easier i double everything that's what i said earlier about doubling but now i'm returning nothing do i have a typo somewhere because it was clearly working earlier that's weird now four and two votes that looks good so that means that the stuff should be on this side for x is not set the candidates right it looks okay so yeah so that's kind of my thought process and some of this like i said is about getting the right visualization as you sail for the problem and for me um you could kind of see like sometimes a wrong answer will just give you right clear immediate visualization of oh yeah of course this is wrong because uh the first the three ones will get easily controlled by three four and five even though that's not enough right that obviously still is good um but yeah i have a typo somewhere this looks good right these are good candidates also why does the right candidates too it should be candid too oops uh so my grammar is poor too but uh hmm sorry about this debugging that is really weird what i mean i maybe you're sitting at home and you're like okay this is clearly whatever but now the target is just wrong oh how why did i delete the dirt by three so okay i don't know what happened there maybe there was a typo somewhere that i did it by accident but okay so this looks um better but clearly there's still a wrong answer here um so i have to kind of debug that now that's weird so yeah so one and three are candidates for some reason oh because now this is these are no longer zero or um no that's not true right this has four so i guess there is another uh my algorithm is just wrong uh or it's not complete um hmm i had to think about this a little bit because basically this gets four votes quote-unquote four votes quote-unquote four votes quote-unquote that gets cancelled by or rather um there's an invariant that i have to think about because for these the three uh they get four votes which in theory these will get cancelled by but the ones here as well i think we have to i'm just thinking about different possibilities of fixing this uh and it might be just that i don't know can we do it in parallel or do i like maybe i can do it a second time and then just do the majority of the second one because we there we have an algorithm that allow us to uh get the one dirt for at least one number but maybe it doesn't work for two numbers and then we could get the majority of the um of the remaining numbers right let's do that instead i think i was trying to be too clever with trying to do one pass uh sorry about that as i said this is experimental so uh you know i guess we'll see but yeah okay let's try to get one number that's one dirt and if we have one number that means that we have a possible second number right because if no i don't um now i'm not so sure i mean i think now with this visualization i can see how uh these two votes cancel these one row uh right like three four can't drop the one makes sense but the way that i did it the ordering is weird because if i you know if i change this to for example um three four five six uh one um or you know similar to this actually just three two uh like we could do three um uh let's move to five six to five this is a very long radio side but yeah these three will get canceled by these four ones but we want ones to be the answer so this is not good enough uh let's revert this real quick and then now we have to think about another invariant that we can think about um and maybe we just do one at a time i don't know let's play around with that sometimes in a contest you just have to play about be able to play around with stuff so because that was one of my alternative uh things to play around with but that doesn't seem like it gives you the answer obviously because this is clearly not right um because now the one the three so now one and then two you might removes to one but not the three even though we want it to be moved to three huh would greedy work now i'm just trying different things to be honest um and let's click on submit for fun uh and then see if we could get a test case that tell us something uh okay so alternating is a good one it's basically you have two you have nine three uh yeah because then nine and then the because then the three cancels out the nine because we're greedy and then nine comes in again and so forth so two is always a candidate so the last two candidates are two and nine but you do the last pass the two will uh clear this out so no good there and then the nine um yeah this is an interesting problem you don't want to do it anymore hmm now i have to think about it a little bit more no pun intended um hmm yes i don't remember this album as well as i hope so i'm just looking a little bit on the um on the wikipedia article but hmm let me see what shows up here just try to figure out good visualization with this as well so this one it looks good on this answer but so what can we have a wrong answer somewhere that uh did i what hm how do i look at my submissions because these are clearly right but i had a wrong answer was that one answer just because i had count one so let's zoom it again why not okay wow okay so my first answer was right it's just that a typo and i thought that my algorithm was wrong okay sometimes you just have silly days uh yeah um okay i don't know what to say about that but this is i mean this is my first intuition right uh and i like as i said you know i'm gonna go through visualizations and you know it makes sense um but yeah um so what is the out complexity so this is going to be linear time we look at each element uh at most once and well sorry at most all one time so it's gonna be linear time and in terms of space we only have four variables really right so and the results i guess a couple more variables so it's gonna be all one space um yeah that's all i have for this problem um let me know what you think i'm i think i'm just a little confused because i had a typo that um that kind of messed up this video a little bit so i apologize for that uh but and some of it is because uh maybe as a medal lesson if you're still here for so long that um that you know for a lot of problems i'm confident uh and when you're confident that means about the algorithm right and when you're confident about the algorithm then you're gonna know that it's the implementation issue uh and that might be in a typo that might mean other things um and in this case because i was not confident about the algorithm i didn't think about um implementation issue because that was pretty straightforward implementation wise but somebody started typo um and yeah so definitely uh maybe that's my takeaway for this uh let me know what you think hit the like button to subscribe and join me in discord uh and hopefully tomorrow will be a better day and uh for decoding and i will see you tomorrow bye
Majority Element II
majority-element-ii
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** \[3\] **Example 2:** **Input:** nums = \[1\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1,2\] **Output:** \[1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow up:** Could you solve the problem in linear time and in `O(1)` space?
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
Array,Hash Table,Sorting,Counting
Medium
169,1102
342
hello guys my name is ursula and welcome to my youtube channel and today we are going to solve a new record question that is power of 4 so let's start so we are given an integer and return the true if it is power of 4 otherwise the term false and integer n is the power of four uh if there exists an integer x say that x n is equal to power x so basically they are asking is that we have to return to if n is the power of 4 okay n is equals to 4 power x then we have to return that true and otherwise it's false so i will be giving you 2 i will be giving a true solution for this the first one is brute force if we do this by brute force so if you see this sorry um what will i do is first of all my bologna while n um and it's greater than equal to zero okay and remainder 4 is also equals to 0 okay if this is so we will divide n by 4 and return n is equals to 1 so let's see this if it's working or not as foreign divided this was the logic i have used here now second thing i will okay now the second method we are going to apply here is mathematical okay guys so we have done this brute force value thing now the second method i am going to tell you is mathematical value so mathematical maths method if we apply so what we will be doing is uh if you see this thing here n is equals to what we have written n is equals to 4 power x okay this is the thing we have okay so if we take log both side what you will be getting here is log n uh is equals to x log 4 okay this is the thing we will be getting so we will we can write that x let x is equals to math dot log n upon sorry upon math dot log four so what we will get the value of x so we will say that we will say what we will be saying this that result is equal to s we will be checking that if x is a whole number then return true else written false so what you will be seeing is that if x minus number x okay return x is equals to 0.0 is equals to 0.0 is equals to 0.0 so what we are saying here is that if result sorry yes if result is equals to 0.0 then return if result is equals to 0.0 then return if result is equals to 0.0 then return true as return false means that if x is for example 4 and if we subtract 4.0 it would be and if we subtract 4.0 it would be and if we subtract 4.0 it would be return zero point four oh sorry zero point zero uh so it will be true otherwise it would be false like if i say this that here we are getting x is equals to five and here we are getting sorry uh five point uh three and the value number is uh if we are suppose we are getting uh five so we will be getting a as zero point three so that is not correct so it will return false so this is the method we have applied as a method of mathematics so we can write this thing and run the code and you can see that we are getting the answer server error so what is the error coming now okay so uh what we will be saying here is if n is greater than equal to zero and then if we will run this here because we do not want the negative value here so we will be only dealing with the values which are greater than zero so if we run this you can see that we are getting the answer so this was foreign and like the video please do subscribe and do comment and do like the video thank you guys for watching the video and see you next time
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
8
hi guys let's do the lead code eight string to integer it's also known as a280i if you been reading your knr you would see that they talk about atoi so what is it knr is kerning an enriched c programming language so um implement the problem states that implement a t o i which converts a string to an integer now then he says that the function first discards as many white space characters as necessary until the first non-white space until the first non-white space until the first non-white space character is found then starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible and interprets them as a numerical value the string can contain additional characters after those that form the integral number which are ignored and have no effect on the behavior of this function if the first sequence of non-white space if the first sequence of non-white space if the first sequence of non-white space characters in str is not a valid integral number or if no such sequence exists because either str is empty or it contains only white space characters no conversion is performed if no valid conversion could be performed zero value is returned um only the space character is considered a white space character so that's easy we don't have to compare it with slashing or slash t assume we are dealing with an environment that could only store integers within the 32 bit sign integer range so then we are in a 32-bit sine integer range which is in a 32-bit sine integer range which is in a 32-bit sine integer range which is in max which is 2 raised to the power 31 minus 1 or in min which is this is negative 2 raised to 31 so that's pretty much is the problem and he gives an example for example you're given the string 42 you convert it to 42 integer you're given minus 42 string you convert to minus 42 you're giving 4 193 with words and these all these other known digits are basically ignored so you get 4193 then you have watts and 987 you get 0 and that's because he's saying the first non-white stress vector is w this is not non-white stress vector is w this is not non-white stress vector is w this is not a numerical digits or a plus minus sign therefore no valid conversion could be perform ic that's interesting so basically i guess we'll need to have a check that checks for the character to be between 0 and 9. now str equal to this one this is interesting as well because it's saying this is out of the range of a 32-bit sign a 32-bit sign a 32-bit sign integer therefore into min is returned so if you're out of the range and depending upon whether you're negative or positive then you're just returning max okay so let's give it a shot hopefully it's not too hard it's a very classic problem i would say so we need a indexer into s or iterator whatever the heck you want to call it so it's i and then you have sine and i would initialize that one to one i would be initializing the for loop and then we can have a variable on it result which where we would be storing the results now for i equal to 0 so first thing we should do is as the problem states skip all space characters so if for i equal to 0 s i equal to this now normally we would have also probably checked like s i equal to new line or slash tab but you know this is he said that don't worry about them only space is considered a white space character then we just say okay that's not the only thing and then we have to say i plus typical while loop and then you say basically that is your skipping all white space because the body of the for loop in this case will be empty now after we have done that we have to take care of the sign so how do we take your sign so we say if s i at this point is equal to plus or s i equal to minus then what happens then we have a check which says okay so now we are assigned the value of sign so sign is we can have a seize power here where we in as few lines we can get our effect so then the sign is we check if it is equal to this we check for that and if that is the case if we return the sign will be one otherwise the sign will be minus one right so the sign gets fixed here now what is the catch here you do want to after that work on the next digit so you make sure that the i is incremented over there so now you come to another wire loop where we start by initializing result to 0 then we say if s i you could also use a for loop here with a little bit of jugglery i would say but it's as good as this so be in the loop as long as we have this condition fulfilled which is so i was actually using a while loop here and i had while something like this like while s i not equal to null character basically walk through this string right and then within that you can have things like s i is it and things like that and then but this is and then you have to also initialize the result to zero here if you're going to use the while loop because while loop will not initialize the um the accumulator or result for you need to do it outside and in the for loop also but for loop gives you a very well defined construct to go over these problems and si less than equal to the digit 9 then we are in good shape and then we can do i plus right here now at this point as you can see we all we need to do is we need to say result equal to the result times 10 plus keep adding the new digit that you find so that is s i minus zero so that's your thing now what is the catch here he's saying first of all let's see if it passes through some of the test cases at this point already so at this point if we come back here and we can simply return sign times result what happens then let's see this is one code so that one passes now let's say submit and as you can see this that is failing and that is failing because he's saying look at the error number look at the error that he actually gives he says this cannot be represented in type int so we have a problem here our result is actually in then he said very clearly when you look back he said that if you cannot represent it within this 32-bit sign in these are ranks then this 32-bit sign in these are ranks then this 32-bit sign in these are ranks then we have to basically return in max arrangement so in that case i was actually trying something like this and then doing a check if the result is so here i have we can have a check which says if result is greater than in max now we can do something here we can say if result is greater than max then if result now if the result is greater than in max then if result if sine is see if sine is minus 1 like because we already have taken the sine so if sine is minus 1 we just set result to in max plus 1 but as you can as you know in absolute sense uh the sign negative sine 32 max is actually one more than the um the positive in 32 in positive in 32 number so and then otherwise it's just in max right now and then we can just break but then the problem is that should take care of that let's see that and as you can see that basically is passing the all the test cases but i guess i think one of the things he mentioned was that assume we are dealing with an environment that could only store integers within the 32-bit sign integer integers within the 32-bit sign integer integers within the 32-bit sign integer range so basically we i don't think we have choice to use in 64. so in that case how about that you can make use of double to make sure that this when this doesn't overflow and every time we calculate result we see hey is it greater than max that means for a hint it has already overflowed in that case we just do this little bit of convoluted logic i would say not too much of it then break out of that and then we are good to go so let's say it passes this one and which passes wow cool so it's four milliseconds faster than the 56 percent of c online solution so that's cool so as you can see we just nailed the lead code 8 which was characterized as medium difficulty but it's very classic c kind of problem where you do the integer ascii to integer taking care of the overflow and the plus sign and minus sign i would say and also making sure that you skip all these space characters so there you have it uh we just fixed the in distinct integer a to i we did called it and don't forget to subscribe to the channel and i will see you guys in the next video until then adios asta manana you
String to Integer (atoi)
string-to-integer-atoi
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). The algorithm for `myAtoi(string s)` is as follows: 1. Read in and ignore any leading whitespace. 2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). 5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`. 6. Return the integer as the final result. **Note:** * Only the space character `' '` is considered a whitespace character. * **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. **Example 1:** **Input:** s = "42 " **Output:** 42 **Explanation:** The underlined characters are what is read in, the caret is the current reader position. Step 1: "42 " (no characters read because there is no leading whitespace) ^ Step 2: "42 " (no characters read because there is neither a '-' nor '+') ^ Step 3: "42 " ( "42 " is read in) ^ The parsed integer is 42. Since 42 is in the range \[-231, 231 - 1\], the final result is 42. **Example 2:** **Input:** s = " -42 " **Output:** -42 **Explanation:** Step 1: " \-42 " (leading whitespace is read and ignored) ^ Step 2: " \-42 " ('-' is read, so the result should be negative) ^ Step 3: " -42 " ( "42 " is read in) ^ The parsed integer is -42. Since -42 is in the range \[-231, 231 - 1\], the final result is -42. **Example 3:** **Input:** s = "4193 with words " **Output:** 4193 **Explanation:** Step 1: "4193 with words " (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193. **Constraints:** * `0 <= s.length <= 200` * `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
null
String
Medium
7,65,2168
641
Hello friends, in this video we are going to solve this problem by designing a circular DQ. Basically, we have to implement a circular DQ and design it so that I can do all the operations in it very easily and all this. We have to do the operation, who has to implement the circular deck, not just the deck, what happened to us in the deck was that I could do all the operations in the beginning and in the last, but what is the meaning of circular, I can go from the beginning to the last. I can go from the last to the beginning, right means after going to the last, you can go to the beginning again, so there is a lot of operation in this, you have to simply implement it like insert last, delete front, delete last, get front, get rare, so let me tell you. Let me explain the question in a very different way and then I will tell you how things work, so make sure that you subscribe the channel right now because you forget to subscribe later and subscribers are very important, so please subscribe. See, what we have is a, first d is d, what we do in this is that I can insert the element from the beginning and can also remove the element from the beginning, I have taken it out like this, I can insert the element in the last and in the last I can remove the element from this is our d, okay, understand, what is meant by circular, after coming from here, I will go directly here, right, now see my circular d, what is its size. Given three given okay after that insert last one insert last suggest we don't have any last so no I will insert this then what will I do I will go to insert last so no element is there I will do it last, it will be fine, like if I have played it, I can do it in the end, then the answer will be true, then I can bring it, then I have done the answer, I will go ahead and then our insert front is, insert front, what is insert front? I have to insert 'th' in the front, I insert 'th' in the front, I insert 'th' in the front, I can insert 'th' in the front, I can also do it in the answer, can insert 'th' in the front, I can also do it in the answer, can insert 'th' in the front, I can also do it in the answer, then 't' will be done and see my then 't' will be done and see my then 't' will be done and see my circular DC, its size has been given as 'th', I circular DC, its size has been given as 'th', I circular DC, its size has been given as 'th', I understood it right, then I insert 'th' in the front and as soon as If understood it right, then I insert 'th' in the front and as soon as If understood it right, then I insert 'th' in the front and as soon as If I do insert front, what will happen to us, which is the fourth element, I will try to insert it in f, so as soon as I try to insert four here, our size is only th, so I will not be able to do it. See, insert front function works. Well, I have done that but its size is three and here I am inserting the fourth element, so what can happen, not possible, then what will be the answer false, then I will move ahead, get rear Meaning what is last so what is the last element two then I can receive two then what will be the answer we have received two and then I will move ahead what is full which is our DK is full yes if it is full then Return two, why because three is the size of three elements and three is this size. Go ahead delete last. If you want to delete last then I will delete t from it, that means I can delete tr, it will be fine then jaga insert front four. I will insert it in the front, so now what will I do, see here first I will delete it so that you can see that yes, I have deleted it and now what will I do, put the four in the front, okay, then I will move ahead, get If you put it in the front, then it will become gate front. Who is there in the front? If there is four, then four will come in our answer. So see all the operations which are there; insert last get front all the operations which are there; insert last get front all the operations which are there; insert last get front get rear is full delete last etc, this is also a function. We have to implement everything. Okay, so whatever we have done here, we have to do the same thing there with Sem. We have inbuilt functions available for all the functions, so I will do everything with its help. So let's understand. How will it happen? Okay, so see, what we have to do is first create a D and make its size. Now what I will do is pass it in the constructor which is of the element, what does it mean, which is of the element, I will keep it in the size. How much is our size? Okay, now I have to insert the front. If I have to insert it in the front, then first I will check whether the size of d is less than the size of d. If it is less, then only I will check. Will I be able to do it, if it is full, please see, D is there, it has a tooth and its size is also our three and there is some size three, is there any element four which I have to put in it, so can I put it, no, I can't put it, will I check first? Its size is less or not then I will insert T and return it otherwise I will do the insert last then I will check the size of D whether there is space in it or not, only then I will be able to insert it and if not then I will Can't insert right delete front If I want to delete the front then should I check which DK is not E then suggest if there is any DK and it is there is no element in it and I am told to delete the front element. So can I do it? If not then I will check first. If it is not there then I can delete. If not then I can delete. Last then I will check whether it is not there. If it is MT then can I delete it? Delete last element ca n't do front if k is mt then return minus otherwise front element k if k is mt not mt then return last element otherwise if manav has to check whether we have mt or not So what will I do directly, the mother function is ours, I will return it, is it full or not, I will check the size of A, is it equal to our size or not, we have treated the size right and all the work is done in it. All the work is done in ofv because you are deleting from the front, inserting from the front in o one, inserting from the last in the front o one, deleting from the last in the front of one, or in the o v. Sorry right, let me show you the same code in Java too. You will get to see the same code in Java. We have constructed it, then in the insert function we will check whether the size is there or not. Then in the insert last we will check whether the size is there or not. Will check in delete whether it is empty Check in gate front if it is empty Will check in rear gate if it is empty Will check in MT If it is zero then If it is not zero then it is MT. If it is not then it is not MT and we will check its size in L. Is it zero or is its size equal or not? If you see, the number of elements in D is the same, its size means it is full, then I think. You must have understood this very simple question. If you still haven't understood in this case then rewind the video and watch what I told you again and you will understand. So let me run the code and show you. Okay but before that if If you want notes in D to AAP structure then you can take it by going to this link or if you want DSA course then go to this link and you can take it. More than 9 lakh people have shown interest. One of the best. The course is available in both the languages. If you use the Loki 10 coupon code, you will get an instant discount of Rs. 15. You can also join our club. You will find all the links in the description, so let me run the code and show you. Okay, so see what I will do, I will show you how, one minute I do this a little bit, I go into C plus and this is our code of C, which I told you is the code, I do it a little bit once. You understand it well and do it, I will click on submit and I don't think you will have any doubt related to this because it is a very easy question. Okay, now what I do is I show you the Java code and basically these are all the questions from you. You will not even be asked, but you should know a little bit about when I can insert and when I can delete, so this is our Java solution, I will submit it also, so let's meet you in the next video, some such videos. Till then subscribe the channel, like the video and share it with your friends because subscribers are very important, okay bye.
Design Circular Deque
design-circular-deque
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean insertLast()` Adds an item at the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean deleteFront()` Deletes an item from the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean deleteLast()` Deletes an item from the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `int getFront()` Returns the front item from the Deque. Returns `-1` if the deque is empty. * `int getRear()` Returns the last item from Deque. Returns `-1` if the deque is empty. * `boolean isEmpty()` Returns `true` if the deque is empty, or `false` otherwise. * `boolean isFull()` Returns `true` if the deque is full, or `false` otherwise. **Example 1:** **Input** \[ "MyCircularDeque ", "insertLast ", "insertLast ", "insertFront ", "insertFront ", "getRear ", "isFull ", "deleteLast ", "insertFront ", "getFront "\] \[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, true, true, true, false, 2, true, true, true, 4\] **Explanation** MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 **Constraints:** * `1 <= k <= 1000` * `0 <= value <= 1000` * At most `2000` calls will be made to `insertFront`, `insertLast`, `deleteFront`, `deleteLast`, `getFront`, `getRear`, `isEmpty`, `isFull`.
null
null
Medium
null
419
hey what's up guys john here uh so today let's take a look at this uh this elite called problem here uh number 419 battleships in the board so okay so you're given like a 2d board and you need to count how many battleships are in it so how what does so what does the battleship means right so battleship are represented by x and the battleships can only be placed horizontally or vertically right and each battleship will at least have one dot in between right and the length of the battleship it's not limited to one or to any length right so for example here in this like 2d graph here there are two battleships right because it says the battleship can only be placed either horizontally or vertically right so basically any continuous axe will belong to the same battleship right for example this one the first battleship is this one and the length of battleship is one the second battleship is this one the length of three and it also gives you another example here this is like an invalid example because it says a battleship between battleships it has to be uh at least one dot in between and this one since this is a battleship this is also battleship right but there's no there's nothing in between so that's why this one is invalid okay so how are we going to uh to solve this problem right so things like you can think of this uh this like uh array to the array as a graph right and to do that you know we can use like uh either dfs or bfs search right basically every time we see a axe here right we know okay we seize a battleship and then we just start from here we uh we traverse all the uh we traverse other the room uh all the acts that's on the same i mean that are linked together right so by linked together i mean left right top and down right and once that is finished then we are we finish the uh traversing this one shape and we can also after traversing the every node here we can just mark this uh change the x back to dot so that we won't uh traverse this one more time right so that's the first step right so i'm sorry that's the uh that's the native approach uh let's try to write this native approach it should be pretty straightforward in this case and m equals to length like board right i'm going to create a board here and it goes to a length board zero right then i'm gonna have a directions here right so since we're going to uh traverse all four directions we're gonna have minus one zero and then okay one zero minus one and zero one right so and then we just do a for loop right before uh loop through the entire 2d board and for j in range and right so every time when we see uh x right then we start our traversing either bfs or dfs if port i j is equal to uh x right then we start out traversing right so first i'm gonna increase this thing to one okay um let's do a dfs traverse this time because we have i have done we have done a few like bfs in the previous videos uh so for the again so who for those who are curious about bfs search bfx reverse we're gonna have a q and then every time we see so like uh unvisited x right we just uh move that thing we just move that we just add that coordinates to the queue and then we do a this loop until the queue is empty and for the dfs right the dfs is a similar thing dfs let's do the dfs will be using a dfs like a recursive call basically and here is going to be the inj current i and current j okay so we do this right and then we simply do a dfs of this current ing right so okay so here we um we do a for loop right so first i'm gonna set this current eye and corn j market to be dot so that we know this thing has been visited before right so that we when we see the x it we won't be uh processing the same max again right and then starting from here we do a loop right directions right so new i current i plus d0 right similarize the uh the bfs instead here we're using like uh similar to the bfs we're using a dfs which will be which is the uh the recursive call here basically we check if check the boundary check new i right m and new j n right and what and this like board uh new i new j is equal to the x right then we if it's acts right then what do we uh we do a dfs right dfs we do a dfs uh new i and new j right so and we'll know so since every time it when it reaches here it will mark this one to the visited here so i'm not going to mark it here i'm going to leave this job to uh to here right at the beginning so basically after this thing's finished right then uh the uh all the so for the current shape right all the x have been marked as dot right then when this one is finished right then we know okay all the x will be marked to dots and then we know we have seen the complete the whole ship already right and then we just keep moving until we traverse finish all the we have seen all the positions all the elements on this 2d board right in the end we simply return an answer this should just do it if i board okay typo here um all right cool so it works so pretty straightforward so it's just like simple uh simple like bfs or dfs traverse every time when you see so x right and then you just uh increase the number of the shapes right and then in the end uh we just do a quick check here right so and then we just mark this thing to dot to mark the visited set right but then what's the time complexity and space complexity right so the space complexities is zero actually it's zero right and then because we're not introducing any new uh arrays here we're just simply using the parameters right and then now what's that the time complexity is going to be a this is dfs and uh dfs is going to be a m plus times basically m times n for each one we are doing the dfs again but since it's bounded right the dfs will be bounded to the number of x here so basically we're not re visiting the x more than once let's see and since the uh for each of the dfs right so for to do through each node we need like m times n and the entire dfs here that's the uh so how many dfs will be here right so basically we're going to have like the uh the number of the x right basically if there's like x dot in this board then this dfs gonna like implement something like the number of x here number of acts right yeah because it's uh every time once we finish the act visiting x we will be mark this one to dots so we will not revisit x multiple times that's why we do add here right okay cool i think that's pretty much it is for this problem and oh sorry no there's a follow-up here right can you there's a follow-up here right can you there's a follow-up here right can you do it in yeah see could you do it in one pass using only one actual all one extra space and without modifying the value of the board right so i think we're kind of doing one pass with o1 actual memory but we're modifying this board right and it asks you can you come up with another solutions with a better like only one pass without actual memory and without the modification right then we cannot use the dfs or bfs right because for the dfs or either dfs or bfs we have to memorize the uh which node we had been visited before right that's why that's we either do a modification of the board or we do a actual space to do a scene set to track those right so but it asks us can you do it without using either dfs or bfs right so how should we do it right i'm gonna just like the uh come out this thing so if you watch closely i think it's kind of obvious you know because we know right if there's like if this x right let's say if there's a x and dot and there's another like x right let's say this is the board here right let's also uh just ignore all the other dots at this moment right so if you see that so as at least for this x right if we see x and there's like either like a left or x or right is also x then we know let me know okay so this x is part of the ship right the battleship so we can simply ignore it right same thing for this x here right so that's why for me i just come up with a solution here so we just need to think of so when should we mark this where should we increase the count of battleship right so for me i use this starting point i use the leftmost x which is this one and the topmost x to indicate okay i have seen a battleship and so that means if there's nothing on the left or the or there's a dot on the left right then i mark this thing to be a strip right to be a start of the ship and anything that any x if there is a x on the left then it's a part of the shape right basically i just ignore it same thing for this shape for the vertical shape here right if there's a like a x uh there's nothing on the top or what where the above one is dots then i will mark i would reincrease the shift count because i know i already found the ship that is a is placed vertically right and then if this acts the top one if the x above it if the so if the above the element of the current x is also x right then we know we i can just simply remove it just like how we uh ignore sorry i can ignore this one just how we ignore this one for the horizontal shapes right and then we simply do a loop through each of the dots here okay so let's try to code this thing right so same thing i'm gonna copy this one here so that's uh that's for sure what we need here to do the for loop and then we simply do a range here right just like what we did for the other one and uh so if right so the still the condition for us is we have it has to be x first right and then we do what we check right so i think from me i think i check if i need to so basically i check if i need to continue i need to skip the current x right basically i do uh so i check this one first right if that if the left one is x then i uh i skip but we also need also only do a boundary check basically if the j is greater than zero right otherwise there's no left right and board i j minus one is also x right then we think simply or simple skip continue right same thing for the uh if i is greater than zero and board i minus one j is x we also continue right and now since we have already skipped the uh the unvalid start off the ship then let's check right if uh if j equals to zero right that's a starting point sorry if the board's uh j equals to zero and then we know we need we have seen the ship or what or the uh there's a the left one is a dot or the word i dot j minus one is a dot right then we know okay we have seen like a ship that had been placed horizontally like this one right then we do answer plus one right else right so we cannot do a if here because once we have seen the ship we cannot mark it again right basically and else i'll see if sorry else if i equals to 0 or board i minus 1 j and start right then we also mark this one to be a ship right in the end we simply return the answer okay let's just run it yeah this thing also works yeah basically in this case it satisfies the follow-up here it satisfies the follow-up here it satisfies the follow-up here basically it's still a one pass right which loops through the entire 2d uh board one time and with no extra memory and without modifying the board we simply use a bunch of if check here right and cool i think that's it for this problem yeah thank you so much for watching the videos guys and hope you guys enjoyed enjoy it and see you guys soon bye
Battleships in a Board
battleships-in-a-board
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. **Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). **Example 1:** **Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\] **Output:** 2 **Example 2:** **Input:** board = \[\[ ". "\]\] **Output:** 0 **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is either `'.'` or `'X'`. **Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
null
Array,Depth-First Search,Matrix
Medium
null
917
hello everyone even before starting today's session i would like to point you guys to the other video that i have published today do have a look at it has million dollar of valuable advice in it's by someone who was among you guys one of the subscriber of a coding decoded channel he worked really hard for it and got through morgan stanley so it's all about his journey and there are multiple instances which he has quoted in the video from which you can take inspiration and it will motivate you guys to perform better at coding interviews now let's move on to today's session is about day 14 of september liquid challenge the question that we have today is an easy question the name of the question is reverse only letters in the question we are given a string s we need to reverse this string such that all the non-english characters such that all the non-english characters such that all the non-english characters retain their position the rest of the english characters gets reversed for example here the input string is a b hyphen c d so a position gets replaced by d b's position gets replaced by c and the hyphen position says either it is because it is a non-english character because it is a non-english character because it is a non-english character similarly you can go through the other examples as well you will witness the same thing without much to do let's look at the ppt that i have created for this and let's get started with today's question reverse letters only lead code 917 and i have taken a slightly different example to what was specified in the question the string that i have is a c d exclamatory mark p a c d and p are my english characters valid english characters and exclamatory mark is an exclamatory mark how am i going to solve this question as a general practice for reversing a string you take two pointers and i'll exactly do the same thing except for the fact whenever i see a non-english character either from the non-english character either from the non-english character either from the starting pointer or the ending pointer i'll skip it how let's iterate through it the first character is a which will be pointed by the start pointer and the end is p which will be pointed by the p character both of them we will check if both of them are valid english characters we will perform this swap operation so let's swap those up we have p here we have a here and what we're going to do as we swap both of them we'll increment s and we will decrement end what do you see here end is being pointed at a non-english end is being pointed at a non-english end is being pointed at a non-english character which is an exclamatory mark so what you are going to do you will simply skip this character you will copy this character or retain this character to the same position and you will reduce the pointer of e so e now points to d and s remains at the same place now both of them are english characters and you will perform the swap operation so these two get swapped and we have d here we have c here and what you are going to do next you will increment s decrement e so e points here s points here and this is a breaking condition you abort the process at the end of the it we have the updated string which is nothing but p d c exclamatory mark followed by a capital a this seems like a pretty easy question uh interviews generally ask these questions as a preliminary clearing round as i told in yesterday's video as well so writing a clean crisp code or such videos is of high importance to catch interviews attention that you encode well the time complexity of this approach is order of n and we are not using any extra space we are updating the initial input string so the space complexity is constant time without much to do let's look at the solution that i have coded for this and let's move on to the coding part the first thing that i have done here is to create a character array from the input string that is given to me because strings are immutable while you can replace specific instances of c uh when given in the array format i've taken two pointers s and start and end till the time my start is less than end i check if my current start character happens to be a valid english character if it is not then i increment the start pointer and contains the process similar thing i also do for the end character and if my end character happens to be a non-english character i reduce the end non-english character i reduce the end non-english character i reduce the end pointer and continue the process without even swapping anything if both of them are valid english characters then i perform the swap operation i increment the start pointer reduce the end pointer and return my updated string how have i written is english character helper method it accepts a character and it check it checks whether the character is an english uppercase character or lower english lowercase character if it happens to be it returns true otherwise it returns false pretty straight forward let's try this up accepted and i have already talked about the time complexity and the space complexity of the solution this brings me to the end of today's session if you liked it please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
Reverse Only Letters
boats-to-save-people
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
Array,Two Pointers,Greedy,Sorting
Medium
null
165
channel of Jhal Hello and Welcome is Asha Question is 165 Computers A Number Okay so basically we give Question Is saying and what is the question So electricity used to go to Saturday If we read this then it is given in such words number We get 1.4 it is given in such words number We get 1.4 it is given in such words number We get 1.4 Whatever you write, it should be done twice quickly. If there is a question, then keep Nadiya here that how to return. If the position is to greater Hussain - If you want to close the version for the great, Hussain - If you want to close the version for the great, Hussain - If you want to close the version for the great, then the weight has to be returned. We can see the mother's murder here. But what is written here, I can't understand it even with pimples, like 1.01 is written and 1.001 like 1.01 is written and 1.001 like 1.01 is written and 1.001 is written that both have equal usage which is the leading role or there is no value, then it is the same here too that version. It is 1.0, it is 1.00, so if it is not given there, then is 1.0, it is 1.00, so if it is not given there, then is 1.0, it is 1.00, so if it is not given there, then it will definitely give all after some point, so both of them are correct, now here it is written 0.1 and here it is written 1.1, so written 0.1 and here it is written 1.1, so written 0.1 and here it is written 1.1, so now things like 1.10 is greater, meaning now things like 1.10 is greater, meaning now things like 1.10 is greater, meaning first. Came to the part that what to return in this, man has tons, simple implementation is questionable, let's see how to do it in more, okay, first of all, what will we do, let's make this a guest or else, then I glue it to that. Equal to that Bhajan Bhandar plate is fine and when I have to do dots plus then you do it like this otherwise it is Multani okay then what will you do boys and girls * A guy version dot net that maybe I have used the wrong one. It will be done like this so that including that now it is done I have come to travel in the Amazon of both the semesters and jelly has been taken now what will you do My Island One Laut Length and Judgment World Does Not Length Okay now what to do what will you do to that If you pass then value request oo to that anti austin is austin is austin is dynasty your result dip in danger dots end me come birthday you me now here I have written here if you are always very important if you are doing It has happened that the weight is 232. If you don't do it then use it like a screen. Even before that, you can easily use it by looking at them. You can do it. Okay, you can do it. Now what will you do with it. If you do, then there will be a vent to a greater smell. The album has to be returned till then, you will return - woven, you will return - woven, you will return - woven, then what will you do, then you will put it on the cycles and make it once again, okay, you have done it, from now on, what will happen like in this example, you will see that Which one here is 1.00, here it Which one here is 1.00, here it Which one here is 1.00, here it can be 1.0, 1.1, neither can come can be 1.0, 1.1, neither can come can be 1.0, 1.1, neither can come in which print to control their six, so it will be 2 more minutes, will divide it in two, will divide it in the middle, so for that, do that one. The people here will end here, then now we will not wait outside for that. Wife is licensed but one daughter's length is yours. Is it 0 0 0 Why what happened when I am in this Greater Noida zero okay. The Flirting Commission has notified you for this, but what will you do? Now if this does not happen, it means that the other person 's 's 's wife is Nisha and it is simple for him, then here I made a mistake, I subscribed here and got a plate here I will I will check it here, it should mean that if all these people are there then what to do now, what will you do now, will you do it or not, will you do 80, it is finishing here, maybe one of my packets is too much, let's see, it is for yes. It is gone, it is done for him, this torch has started that it has become alone, please plant Akshay in me, please see Ajay, that if Bhushan is here, then half of the deeds will be done. Okay, okay, both of these are easily okay, so now let's try our own tests and see, it all started here and here we have reached zero point, then what will happen if the certificate is where the fun is. Rahi Hamari Ho Hain Iss Style One Status And Why Doesn't Seem Was Written Ok How Did This Test Happen Now Spooch Karo Yahan Par Two Songs And Yahan Par Tu Two Hai Then Let's See Let's Check The Speaker Jhaal Baby Chahiye Ok Now support me, I have stopped it here, nothing has been done, then I am seeing the answer key, if it is okay soon, then now I feel like let's go to the court, let's take it with the other one and see if we have done anything. But I have not done it wrong, let's break it down here, now I am not only not confirmed, how is everything coming, so I just check to submit, what is the complaint, okay, ok, speed code no, it is good, all the best, five, this Hero Scooter will go over and if you like it then do whatever you want, I will say like, share and subscribe, you will like it better, ok thank you too.
Compare Version Numbers
compare-version-numbers
Given two version numbers, `version1` and `version2`, compare them. Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers. To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`. _Return the following:_ * If `version1 < version2`, return `-1`. * If `version1 > version2`, return `1`. * Otherwise, return `0`. **Example 1:** **Input:** version1 = "1.01 ", version2 = "1.001 " **Output:** 0 **Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ". **Example 2:** **Input:** version1 = "1.0 ", version2 = "1.0.0 " **Output:** 0 **Explanation:** version1 does not specify revision 2, which means it is treated as "0 ". **Example 3:** **Input:** version1 = "0.1 ", version2 = "1.1 " **Output:** -1 **Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2. **Constraints:** * `1 <= version1.length, version2.length <= 500` * `version1` and `version2` only contain digits and `'.'`. * `version1` and `version2` **are valid version numbers**. * All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
null
Two Pointers,String
Medium
null
380
in this tutorial I am going to discuss a very interesting problem insert delete get random in oven so in this problem we have to design a data structure that supports all the following operation in average oven time and the operations are insert remove and get random so when this method is called insert we have to insert an item value to the set if it is not present when this method remove is called we have to remove an item from this set if it is present and when get random is called it returns a random element from current set of element and each element must have the same probability of being returned so let's understand this problem statement through an example so in this example so imagine all these three methods are implemented in this class randomized set and to access these method we have to first create an object so we first created an object of this class and then we can call this these method in any order so in this example here a set of instructions are given and let's understand them so first when this method is called with an argument 1 so it insert 1 as it is not present then this remove method is called and again I am reiterating so the method can be called in any order it is just for an explanation purpose and when remove method is called with argument 2 so 2 is not present so what it does not do anything and it return false that this is not a valid operation and in this case we return true as we have inserted a 1 successfully then this operation insert 2 so 2 is not present so let's insert them and return true which indicates that this operation is successfully done then when gate rendom is called so we can return any of the element either 1 or 2 so I mean each element must have the same probability so if 1 is returned then immediately if we call get random it will return - I mean in so basically it will return - I mean in so basically it will return - I mean in so basically we don't have any weight edge on any element it can be all the element have the same probability of being returned so get random should return either one or two randomly then we call this method remove with an argument one so one is they are so we removed them and we return true would never true that this operation is successfully done then the next call is to insert two and two is already there so we don't have to insert this element we simply return false and then get random is called only one element is there so we return in this element so this is the problem statement and now let's think which data structure we choose so that we can perform all the all these operation in a one-time complexity in this problem we one-time complexity in this problem we one-time complexity in this problem we have to implement insert remove get random in constant time so let's first discuss which data structure should be used to solve this problem in constant time then we will discuss its code so the first data structure which comes in our mind is can we solve this problem by using hash map or hash set using hash map and hash set we can implement insert and remove operation in constant time but what about get random so to implement get random we have to choose random index and return the element present at that index but hash map and hash set does not have the concept of indexes so we can't implement get random in constant time by using hash map and hash set so let's move to another data structure so what about ArrayList if we use ArrayList can we do all the operation in oh one so by using error list we can implement insert and get random in oh one error list is a dynamic size array so what we can do is whenever this insert method is called so we can a we can insert an element at the end of this array list so first one is inserted then two then three in this way we can do the insert operation oh one and whenever this great random method is called we can choose random index from the available indexes and return the element present at that index so in this way these two operation will be done in oh one but what about remove methods removing an element from an array list takes o n time complexity so we can't use array list as well so what about if we use these two data structure together to solve this problem in oh one so the idea here is to insert each element in an array list and in hashmap we put each element and its index and element index is the index which is present in ArrayList and using this strategy we can implement all these three operations in oh one so let's discuss one by one how we can implement them in oh one and let's visualize it let's visualize how we can solve this problem in oh one time complexity using hash map and ArrayList so what we can do is we can visualize this approach by taking following instructions so where I represent insert R represent remove and ga represent get random method call and in each method call let's see how we can do the operations in oh one time complexity so now this thing is clear that whenever we create an object of this class the constructor is called and we create an object of hash map ArrayList and this random class so in map we store we keep T and value pair of n type in list we store list of integers and this random at this random class is used to get the random value between zero to array length minus 1 so now when this insert operations this insert method is called with the argument 1 so first thing we check is if this element this one is present in a map if it is then we have to return false I mean we have if this element is already present we don't need to insert them else what we have to do is let's put them in a map so we put them at 0th index and then we put them in a map so we first put them in an ArrayList and is it is at 0th index and then we put them in a map with the value with this element and this index so index is 0 and then we return true so now that the next operation is remove - so first we check operation is remove - so first we check operation is remove - so first we check is - is present so is - is already is - is present so is - is already is - is present so is - is already present then we can able to remove it else simply return false so when we check is - is present in a map no so we check is - is present in a map no so we check is - is present in a map no so we return false so now you can see this I mean this lookup is constant this addition so adding an element in an array list is also constant and this put operations is also in constant time similarly when we are going to remove an element we first check them in a map so it is not present in a map so it's a constant operation so we simply return false then the next operation then the next method call is insert with the value 2 so again we check so it is not present in a map and we first inserted them in a ArrayList so it's index value is 1 then we inserted them in a map with this index value now the next method called as get random so now we have to randomly pick any index and return the element present in this present at this index so we can get any index out of 0 &amp; index so we can get any index out of 0 &amp; index so we can get any index out of 0 &amp; 1 so let's suppose we get index 1 so we return to and I will show you the code of get random method shortly so now let's move to next operation so the next operation next Halas remove with the value one so again we check is this element present in a map yes so this condition is escaped then what we so we are using a very clever technique here so that removing an element from ArrayList is also constant so what we are doing is we are first getting the index of this element from a hashmap so we get its index which is 0 then we are getting the last element from the array list and why we are getting it you understand shortly so we are and getting it so we get 2 and then at this index so we have to remove this index the element present at 0th index so we'll put 2 here so we put this 2 at this index and this to remain as it is and then we update its index value in the hashmap as well and then we remove this entry so this value as we have to remove 1 and also we remove the last element from the array list so in this way removing an array list removing an element from an array list is in constant time is in O 1 if we remove the element from let us say from this index from 0th index then we need to shift the element one step otherwise this space remains empty so it's a I mean a dynamic array so it will fix this size and in this operation it will take time so that's why we have used this clever technique and now this entry is removed this entry is remove so one is removed from both the array list and hashmap so now the next operation so keeping the indexes in hashmap has the advantage so when we get one in constant time we know that this element is present at this index we simply go there we do the following operations that we take the last element from the error list we put at that index and then we remove the last element now let's move to the next operation so the next operation is insert two so this time two is already present in a map so simply return false we don't need to add them and then the next operation is get random so when get random is called only one element is there so the array size ArrayList size is 1 so we get and a number 0 between 0 and less than 1 so we get only 0 so we return this 2 so we randomly returns two so now you can see we can achieve all these three operations we have done all these three operations in constant time in one time so this is the logic behind this approach and now let's see the get random method as well so if you see here is the get random method where we are calling we are asking to give me the random number between zero to list dot size so this list dot size is not included it means when we pass the size let's say the size is 5 so it will give you the random number between 0 to 4 so in this way all the these 3 operation insert/remove and gINT random isn't a insert/remove and gINT random isn't a insert/remove and gINT random isn't a one-time complexity so that's it for one-time complexity so that's it for one-time complexity so that's it for this video tutorial and if you know any other approach to solve this problem you can let us know through your comment so that anybody who is watching this video get the benefit from the approach you mentioned in the comment section so that's it for this video tutorial for more such programming videos you can subscribe our YouTube channel you can visit our website which is HTTP colon slash - slash - slash - thanks for watching this video
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
1,859
Hello everyone welcome back tu disrespect video and in this video we will solve sorting sentence which is the fourth problem of the string. If you want to see the complete series then I will put the link of the playlist in the description box and will also give you the link of every question. You will get the link of the question of lead code in the description box, so let us understand this problem directly from the example, so let's take this example and take it to the dashboard, I will paste it, then see friends, input this sentence. If you get the output in this sentence, then what is written here and it is written that one and three are written, it should come in the second position, so here I write the sentence and where it should come, if it should come in the first position, then here I write. I am in this and what is required at the third position, so this should be our output, so where do we have to reach from here, correct it here and break it, on the basis of whose space, there is space here, so we can split, and by splitting, we What will people do next? So what will be the first word here, sentence for and then there will be and here we will make indexing zero one two three MP in which we will try to keep this ring of sorted 01 2 first of all we will read. The first character we will extract from it is this, if we minize it then we will make it 2 - 1, hence we will do minize it then we will make it 2 - 1, hence we will do minize it then we will make it 2 - 1, hence we will do 4 - 1. What will happen if we go to 1 - 101 index, then 2 will come, then we will keep it on the second index and again basically we will convert it into word. We will do this because what we have to return is to string and after converting it into word then we will return date wood b d approach so we code this approach so let's go to d lead code platform so first of all we will string Let's take the name 'Hey' we will string Let's take the name 'Hey' we will string Let's take the name 'Hey' in which we will split the word and then let's say level is equal to s dot split, this is an inbuilt function and on the basis of which we will split it, on the basis of space, we will split this sentence, right after that a string. Hey, we will take another one in which we will keep our output which we want to return to the original, so here we will pass it in correct, so first of all, what we do is find out its length and basically we will try to read the last character, right then lips if When 5 came, we basically used the fourth index because zero based indexing was done. If we try to read the force index, then we are reading the position N - 1 last character which N - 1 last character which N - 1 last character which will be our digital and it was clearly mentioned in the digital that the numbering will be done. 129 It may be that we are not getting a number greater than 9, so why would we read the last character only? Okay, if there was a number greater than nine, 10 11 12, then our approach changes a bit. It is okay and this character will be given, so what can we do? We will do this by doing only 48 mines or we can also do zero mines like this, you took us out, you did the mines van and here we are keeping it, so how will only the string from here till here come here. If we keep it, then how are we doing this thing? We will start from T dot substring and zero and till where we will go till N - 1. Okay and till where we will go till N - 1. Okay and till where we will go till N - 1. Okay So take a stringbuilder, all are equal, you will create a new stringbuilder and read each string this time. We will read and what will we write every time because then keep only the word in it and keep the space, otherwise we will paint on this page and return and trim it and what will happen in the last word too, a space will be added and let's run and see. If yes, then I am reducing the video for simple output. Friends, see you in the next video.
Sorting the Sentence
change-minimum-characters-to-satisfy-one-of-three-conditions
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence. * For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`. Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_. **Example 1:** **Input:** s = "is2 sentence4 This1 a3 " **Output:** "This is a sentence " **Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers. **Example 2:** **Input:** s = "Myself2 Me1 I4 and3 " **Output:** "Me Myself and I " **Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers. **Constraints:** * `2 <= s.length <= 200` * `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`. * The number of words in `s` is between `1` and `9`. * The words in `s` are separated by a single space. * `s` contains no leading or trailing spaces. 1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
Hash Table,String,Counting,Prefix Sum
Medium
null
717
hey everyone welcome back and today we'll be doing another lead code problem 717 one bit at 2-bit character this is 717 one bit at 2-bit character this is 717 one bit at 2-bit character this is an easy one you have two special characters the first character can be represented by one bit zero the second can character can be represented by two bits then or eleven uh one zero or one this is not 10 and 11 given a binary array bits and that ends with 0 return true if the last character must be a one bit character so zero is the one bit character basically they are saying if there is a zero at the very end Standalone so here if we have this example we are going to return true because this is our two bit character this 0 and this one and this 0 and then 0 at the very last is going to be a single you can say a one bit character so we'll be returning true in this case we are not going to return true because this is a 2-bit character true because this is a 2-bit character true because this is a 2-bit character and this is also 1 and 0 is also R2 bit character so that's it so we will be starting our index from 0 n will be our length of nums and number of bits you can say we will be having as a counter so while our I is less than nums and if dates at I is equal to 1 then we know that we are going to have one is just basically not a zero bit a one bit character so we'll be incrementing I by 2 because we whenever we reach one or you can say in counter one we are going to have a two bit so that's why we are going I plus 2 and nums will be all also num bits will also be incremented by two so that's it and now in the else case we can see that if we have a 0 we are just going to increment our index by 1 nums is not going to be incremented nums is going to be 2 because obviously we are not to do increment at each point and num bits will be one if you encounter a zero so if we encounter a zero at the very end then obviously num bits is going to be one and then we can just return if num states are equal to 1 so that was it oh okay so it was our bits array I thought it was a number that's it
1-bit and 2-bit Characters
1-bit-and-2-bit-characters
We have two special characters: * The first character can be represented by one bit `0`. * The second character can be represented by two bits (`10` or `11`). Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character. **Example 1:** **Input:** bits = \[1,0,0\] **Output:** true **Explanation:** The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. **Example 2:** **Input:** bits = \[1,1,1,0\] **Output:** false **Explanation:** The only way to decode it is two-bit character and two-bit character. So the last character is not one-bit character. **Constraints:** * `1 <= bits.length <= 1000` * `bits[i]` is either `0` or `1`.
Keep track of where the next character starts. At the end, you want to know if you started on the last bit.
Array
Easy
89
775
hi guys this is khushboo welcome to algorithms made easy in this video we will see the question global and local inversions we have some permutation of a that consists of numbers 0 to n minus 1 where n is the length of a number of global inversions is number of eyes less than j wherein 0 is less than i less than j which is less than n and for that my a of i should be greater than a of j that is in the descending order now the number of local inversions is the number of eyes wherein my a of i is greater than a of i plus 1. so this is locally comparing a of i with just its next value but in global you can have comparisons with any value that satisfies i less than j condition and wherein this a of i is greater than a of j we need to return true if and only if the number of global inversions is equal to the number of local inversions for the example one the output is true whereas for example two the output is false now how we are getting this output will see with the help of an example so don't worry as this might sound a little bit tricky to you while reading out but when you visualize this would become very simpler so let's go and see how we can solve this question with an example let's first take this particular example and as per the definition given to us for the global inversion it means that these are the number of inversions with a of i greater than a of j where i is less than j so if you consider 3 you can have 3 inversions these are global inversions because 3 is greater than 2 3 is even greater than 1 and 3 is even greater than 0 these are the indexes and these are the numbers now if you consider 2 you will get 2 inversions for that these are also global inversions and if you take one you will get one global inversions so in total you will have six global inversions for this particular example now let's go ahead and see what is local inversions so local inversion would be just for your local pairs that is for in i plus 1 pair so over here your local inversions are the ones marked with this white because 3 is greater than 2 then this 2 is greater than 1 and this 1 is also greater than 0 so these are my local inversions which are 3 so if you see over here my local inversions are 3 but my global inversions are 6 which is not the case that i want and so the answer for this particular example would have been false so now what are the things that we can find out by using the properties the hint given in the question says that find out where you can place zero so this would help us solve the question further so now let's see if we take a ascending order number that is 0 1 to 3 we can say that there are no inversions because we don't get a place where in my a of i is greater than a of j in the second case if i just swap these numbers against themselves then i'll get two local inversions and two global inversions because 1 is greater than 0 and 3 is greater than 2 neither this one is greater than any of these others and neither is this 3 greater than any of the other because there is nothing left so over here also we can say that the local and global inversions are equal so the answer is true so you can have these three cases wherein you have an ascending order no inversions wherein you can have a swap of these numbers and you can have equal number of local and global inversions or you can have a mix of both so let's find out where my zero can be placed my zero can either be placed at the zeroth index or first index if it is placed any further i'll get more number of global inversions than my local inversions as we have seen in this particular example so i can say 0 can only be there at 0th or 1st position as you can see in all these 3 examples which would yield true now what about the other numbers can be either placed at the ith position that is for ascending order wherein you will have no inversions or in the swap case it can be at i minus 1 for example so this 1 is at i minus 1 that is 0th index and i plus 1 that is the 0 comes to the first index so it is i plus 1 so that's the trick over here i can only have the elements or the numbers at i minus 1 or i plus 1 index and so this can also be stated as the absolute difference between any index and the number would be always less than 1 that is either 0 or plus 1 and minus 1 which gives us 1 when we find its absolute value so that's all for this question so let's go ahead and code it out so over here we'll iterate over all the numbers and we need the absolute difference between the index and the number and it should not go beyond one if it goes beyond one we can return false otherwise finally we can just return true so let's try to run this code and it's giving a perfect result let's submit this and it got submitted the time complexity for this particular approach would be o of n as we are going to go through all the elements in my a so that's it for today guys i hope you like the video and i'll see you in another one so till then keep learning keep coding
Global and Local Inversions
n-ary-tree-preorder-traversal
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
Stack,Tree,Depth-First Search
Easy
144,764,776
1
hello everyone welcome back to the swift academy in today's video we are going to solve another lit code issue that is so popular among the interviewers it's called twosome and also it categorized as an easy question but regarding that it is easy because simply you can find the answer for that it is so important how you communicate with your interviewer how you describe the things to your interviewer how you are going to solve this solution by the brute forcing solution then you are going to use another's approach then your third approach and you have to talk all the time with your interviewer about how you are thinking so please think loud and talk about how you are going to solve the problem even if the interviewer give you an easiest question it is going to find how your thought process is so bear with me i'm going to describe this question to you this is two sum it will give you an array of the norms and it is going to finding the target but what is the target there is only two number or integer inside that array that if you add them together the target value will be the things that the question asking for so for example in this question we are looking for the target nine and if you look at the noms the array you can find out okay at the index zero and at the index one two plus seven is equal to the 9. it means that we have to return just the index of those numbers that when you add them up together you will have the target okay the brute force approach that you are going to think about it is to iterate to roof the whole array inside a two loop and just seeing that if the value one adding to the next value is going to be our target or not but we know that when we are going to use two for loops inside together we are going to have the time complexity of o and s score which is not so good for example if you have a long list of the array and you have a bunch of numbers here if you are going to iterate for example one million numbers what will be happen in the case of the time complexity it's not going to be worth you a lot because always you have to design an algorithm that is so efficient so let me describe how we are going to solve this problem by using a little bit of the space in memory okay now take a look at this example we have an array uh consists of a bunch of numbers here and the question will be asking us about to find the two number or two digits that when you add them together you are going to have 14 so if you are going to using the first approach the brute force approach we ended up with the two for loops that which is not actually so efficient so we are now going to use another methodology that we always using that inside that this kind of the questions guess what we are going to use the hash maps uh you know that inside the hash maps when you are inserting something into it the time complexity is going to be o1 and then you are deriving data from that it is going to be one as well so inserting or asking about one value inside the hash maps the time complexity is one so by the help of the hashmaps we can actually solve this problem and it's ready to roof hold the list just one time but we sacrificing the space for that so the whole time complexity is going to be o n and it means that we can actually iterate to hold the least just one time it's about the time complexity but in case of the space a divorce case scenario we should sacrifice it the whole list and it will be on as well so the time complexity reduced to the on but we with the help of the space that we are using we are going to all end time complexity let me explain how we are going to use hash maps for solving this problem we are going to use just one for loop here and on each time that we are visiting one of those numbers or indexes first of all we are going to ask our hashmaps do you have the difference between those target and the index object that we are actually looking for example when we are uh in the index 0 if this is our hash maps we have the key and we have the value if we are at the index 0 what will be the difference between them 14 minus 2 is going to be what is going to be 12. so we are going to ask hashmaps as you can see we already have 12 in our list but we are at the index 0 now so at the index 0 we still didn't see the 12 that existed so we are going to add 2 inside our hash maps and the value is going to be the index of the value so 2 is going to be in at the index of 0. then later on we are going to do the difference between the 14 and also uh to read the next index is gonna be 11 we are going to ask our hashmaps do you have any element at any index no then we are going to add it to our hash maps again so we are going to add the tree at the index one it should be go on until we see the index of one of those that we are actually trying to do at the end when we reach to the 12 we are calculating the difference between the target and the 12 there so 14 is gonna be minus 12 it's gonna be two first of all we are going to asking our hashmaps do you have any data inside our hash maps and yes we have the tutor so at the index of the zero then we are going to return back the index of the zero and also the index that we already visiting the index that you're already visiting is zero one two three four so the response will be zero four with this approach we will have the time complexity of o n by the sacrificing the space so let's jump to the code and show you how we are going to code it in swift language so now we are going to solve this problem in swift language as you can see inside the question description it is saying that there is exactly one solution for that so don't worry if they give you a number target that would be not add up so with that in mind we are going to solve this problem with the approach that i described by using the hashmap so first of all we are going to create our hashmap and our hashmaps is gonna beat two integers as the key and value and i define it as an empty hash maps now then we just need one for here because we are going to iterate once inside our numbers or our array so for i in 0 till our nums dot count then we are going to asking our hashmap if the value is already there or not do you have any index of that value so we need this current value let currentval equal to noms i and also in the difference here so let live equal to our target minus the current val that we are now there so currentval and now we have the different here it's time to asking our hashmap if you already have it or not so we can asking our hashmap by an if statement if let index equal to our hashmap it means that we have an index already there and else if it doesn't have anything then we are going to populate our hashmap with that data so with the current val that we already on it now and we equally to the i it means the index but when we have the data we can just simply return i because the i is the current index that we are on it and also the index that we get from the hashmap so the next one will be the index and if we get out of our loop and we didn't find anything we can just simply returning an empty alley so let me build up and see the result as you can see that this approach by using the hash maps and sacrificing a memory space here we are going to be more than 95 percent above other submissions for two sum now so always think about it to when you can sacrifice the space regarding the time complexity and always talk with your interviewer about such these situations be successful like this video and subscribe to this channel to see more content like this see you on the next time you
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
342
Hello everyone welcome tu andar video understand it is little bit not un difficult but little bit medium ok so d question is saying date given and wait and return true it is d power of adrevise return false like for example like wait n is d power of for This Exit N Wait Access Date Like N = 4 Exit N Wait Access Date Like N = 4 Exit N Wait Access Date Like N = 4 Power Of And d third condition is given d = 1 so you want to return true ok I d = 1 so you want to return true ok I d = 1 so you want to return true ok I think you understand d concept what is d concept of d question so I am understand what is here how will I solve this man lo end Equals you are 16, like okay, so when we divide ours by four, like, then four becomes four goes, Drishti, okay, if we divide this, then what will come here, zero is zero, okay, and the one above is our divider. It happens that you know, I know, you know it or so, now you have understood that the one below is the model and the one above is the divider, when again when we divide our four, then what comes from which four. Here comes all N = 1 so Here comes all N = 1 so Here comes all N = 1 so when you have to return true and this is the code list of your let's take, you will apply the condition here till my N is not equal to zero then my here should run. Okay, as I was just explaining here, look here, I had done that and like here four came, then four, our porbandar for is fine, this will be created first, so if when n = apan, what will we do, end module. When it is not equal to zero, you have to understand, then what you have to do is return falls like, let me explain to you how, like here is 16. Okay, so see what I did first here, my is 16 here. I divided 16 by four like I wrote here 16 is ok I divided it here by four ok so 4 * 4 16 ok so here also my right is present ok I will divide right then n equals you understand Look, if I did what I did here and modular four, that is, I will divide four again here, I just did 4 here and came here, understand that this thing will start to understand, if that van will not come, then if the van will not come. So what will the return do? Our submission has also been done. Thank you so much for watching this video.
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
766
it's a very basic level problem it's a topless Matrix you can say so we are given an M cruise and Matrix we have to return to if the Matrix is topless otherwise we'll return Force means topless Matrix is if uh these diagonals are same in this way so if these diagonals are same so first we have 9 then we have 5 right so all the elements of each diagonal are same then we have one then we have two then two to two we have 2 and 2 then we have three and three right then we have four so just we have to compare their indexes you can see here so let's say it's its index is 0 so uh so let's say we are observing our this diagonal which is containing only one right so I'll compare so first its index is 0 now we have to check this number at which index it is at so one row is increasing and one column is increasing means index is from 0 to 1. again uh we have one then we have two right so just we have to compare the values in this way so simply we'll run our two national loops and we'll check if Matrix of i j is not equal to Matrix of 5 plus 1 J plus one elements otherwise will return true here right so you can see here it's running so you can see here the solution is accepted so that's it for this video it's nothing here to explain much right if you still haven't out you can ask in the comment box otherwise it's an accepted solution right so you can connect with me my LinkedIn and Twitter handles are given in the description box so stay tuned for more videos
Toeplitz Matrix
flatten-a-multilevel-doubly-linked-list
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Linked List,Depth-First Search,Doubly-Linked List
Medium
114,1796
1,846
hey how's it going leak code 1846 maximum element after decreasing and rearranging you're given an array of positive integers ARR perform some operations possibly non on ARR so that it satisfies these conditions the value of the first element in ARR must be one aha uh the absolute difference between any two adjacent elements must be less than or equal to one in other words ABS a r I might I got it uh there are two types of operations that you can perform any number of times decrease the value of any element of ARR to a smaller positive integer rearrange the elements of ARR to be in any order okay it doesn't seem like duplicates are going to benefit us in any way and okay there's no values less than zero and um we can never increase a value so the biggest value we could possibly have is the final value of the array so I think the first thing we're going to do is we're going to get rid of duplicates we're going to say ARR equals list of sorted of set of ARR and then while AR R of 0 is greater than one we're going to say ARR well no we don't have to do that we don't have to do the uh the things one at a time okay that was dumb now it can only increase by one every time uh so let's say 4 I in range one to length of ARR and then if a r of I is greater than one more than the previous value then we are going to decrease it until it is one more than the previous value and then we're just going to return the last element I guess gu it's supposed to be confusing cuz you're supposed to get confused with the organizing but seemed pretty straightforward to me oh my goodness output three expected 210 you're right you are right I should not have eliminated the duplicates okay AR rr. sort run whoopsie all right and there we go
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null
162
Hello everyone welcome back on the chain Anil Kapoor himself is going to discuss write there is a problem in finding the right element in July 4th so what is the problem in which my given input is fine and tell us which is the APK element in it apk Who is the file, increase your left element and bigger than your side, so our element is our tax return, like if we see what are the PK limits in all, which can be one element, tomorrow is cricket two, this is The element on the left i.e. Vansh increases and Chopra on the right, its forest i.e. Vansh increases and Chopra on the right, its forest i.e. Vansh increases and Chopra on the right, its forest is on top of it, okay, the second one can limit first, this is because see why it is bigger than there and only bigger, okay, so we can return any of these pin elements. Anyone can do it, basically we have to return his tax in the output, then you return one in the output or make it a favorite in the question of some person that he has said that these were returned on the word also money returning back to the one. Peace ok hai aur chowki tibba post video and think simple kya way you can sleep ok element tunee p ke nimitt ok so see at the time of the simplest the first thing that will come to mind is what will we do we will age and Harman check We will keep doing like here this is our we will check that this festival is increased by element and festival is increased by both the big side then it is of scale or and if we get the pick then we will just return its index i.e. simple return its index i.e. simple return its index i.e. simple process of It will work in N and it is right, even worse, they have said in the portion that you must not write the algorithm in the login is logged in, now you have to keep it in the login time, okay, in the login time, one of yours is thinking of the leaves of Ghori Dharmasangh binary search. It will be like how to put the final truth - in the appointed A, it seems that how to put the final truth - in the appointed A, it seems that how to put the final truth - in the appointed A, it seems that it will be soft, not some solution, there is a valuation of the research, why shot name can be kept as Babuni and its answer is this symbol of approaching the questions, then he can see what is the way. So we will find this question, we will fold it from this side, it is very easy, okay, so till now we do not know what water really is, okay - what is there in it, is, okay - what is there in it, is, okay - what is there in it, we take it, okay where to take it, in the beginning i.e. okay where to take it, in the beginning i.e. okay where to take it, in the beginning i.e. People have done it at the ends and then we only take it in chicken and we have taken it lightly, we have sex in the last, we have sex and then what do we do, we take out these mean streets, what do we do and we don't put them like this and go viral when Till ilaj balance he is equal to high till then we will work and what do we take out a yo honey low plus hai bay tu this is what you do - yo honey low plus hai bay tu this is what you do - yo honey low plus hai bay tu this is what you do - da ok so this is what we do here also what did we take out The locals are in more plus 6 of Sector-22, locals are in more plus 6 of Sector-22, locals are in more plus 6 of Sector-22, I am dead, it is free, that is, 3D is lying here, okay, so we will check the first one, it is lying on whatever media, if on the left it is bigger than before or it is medium. - If you left it is bigger than before or it is medium. - If you left it is bigger than before or it is medium. - If you increase this by hello and whoever is lying on our minute, if he has vada in his right investment i.e. middle and end explanation, then this fight has gone to all of the wheat, no, I am someone, this will be my condition, I have picked. Got the pick, give it to Middleton because there are meds and injections which I have measured here for Marawi. Look here, the one which is free is bigger than there, this condition is the right answer but this condition continues. Because 357 was very big from five, now we have to think that if this condition comes then we will either have to go left or right, then what do we do with our best rating like N Yadav goes left, then either we will apologize. I think for myself that how do they happen and where do you know, we were satisfied with the triptych pre-primary international that we were satisfied with the fact that satisfied with the triptych pre-primary international that we were satisfied with the fact that satisfied with the triptych pre-primary international that we were satisfied with the fact that our brother is the right one, the second largest five file, if you think, 5.5 is small on this side because from small here to 5.5 is small on this side because from small here to 5.5 is small on this side because from small here to here. If here it should be smaller than C, here then one is smaller than C, then there is an advantage of making it left or right because it is bigger in the five worlds, so if you think that if there is such a condition of five elements, then it matches. Done, you will increase the edifice, the file can be right to left or there is a change in the new system, there is a possibility here, so what do I mean to say, if this condition of ours is not true then we go to the press and do the computer, now we will chat in this Is that a comment that if then our meat is our dip which is ours this one if this is the dead media element it is smaller than our right one whatever type hey wait here lying on the side it is smaller media freedom fighter So we will go on diet, we will reduce this side and that mid plus time is good, otherwise if this Kshatriya, if there is someone bigger than this here at the halt, but you guys, then it is like this, then we will go to the exam, we will request oo made. - Okay, okay, request oo made. - Okay, okay, so this is our algorithm, once according to this, we look at the triangle, then let's see what will happen according to this, see, first of all, our media was that now whatever the husband is, that is the PK limit because 310 is on the big side. 357 Do not increase from the five, okay, so what we will do is that we will go to the brightness, this is our palazzo's meat plus one i.e. for and high, which is meat plus one i.e. for and high, which is meat plus one i.e. for and high, which is like that, there is chicken in tha ce, so our media will go here with the help of trust by the media. Fight for class six bittu panch i.e. liquid class six bittu panch i.e. liquid class six bittu panch i.e. liquid liner dekh hoge toh six hai he apni 578 and a signup land rights violation in order for the word you hai to this one drinks i.e. yes this one let's drinks i.e. yes this one let's drinks i.e. yes this one let's find and return our next condition room has come So this is how it will work okay let's see a little one which would have been done better that now like we only tested 1421 okay so this was just a heroine of funds so mixed in it first take our 102 okay and If it is on my mobile then Media Advisor Plus One by Two i.e. then Media Advisor Plus One by Two i.e. then Media Advisor Plus One by Two i.e. live chicken, know any more of its electronic here, it will appear here that if our and zero are not there then fruits right and take will compare it i.e. Plus just add water and then compare. Now i.e. Plus just add water and then compare. Now i.e. Plus just add water and then compare. Now see what is there and what I want to do. If the knowledgeable lineage of light increases, then this is our back element. Okay, so now what will we do, let's measure it. Okay, so this is indicated. In which our made tow came, it was found to be Vidro, okay, we can do quarters like we took 1234, okay, so induction is required in this, if there will be car loans in minutes, then what will be the free of zero, which will erase 0.5 inches. That is, the time vagina which will erase 0.5 inches. That is, the time vagina which will erase 0.5 inches. That is, the time vagina is now J2, it is greater than, so I have seen this left curd, if it is not greater than three, then it cannot be thick and because it is more dear butt, then okay, this top will go in this direction, go to the office, ours will go. That's what this meet one plus one two and that's what he has come to meet you that now ours will be found tubeless cb2 i.e. i.e. i.e. Chotu i.e. hit Chotu i.e. hit Chotu i.e. hit is now that now see is it okay reminder phase-10 is big and Sorry to you, this frilled one is phase-10 is big and Sorry to you, this frilled one is phase-10 is big and Sorry to you, this frilled one is bigger but he is not bigger than the playwright one, that is, I cannot be a teacher and because the right one is big, then I too will give the right one a piece, then what will we do with the people, then what will change for us, Mithila. Health Neetu Prashant three and also our Shri will be found here C2 Yo Honey 3 So now our media look at this I am scared mine is this i.e. now look carefully Mirchi Maya and i.e. now look carefully Mirchi Maya and i.e. now look carefully Mirchi Maya and this is our last and this one so here We have got the left element but if there is any element on the machine right then this condition then look at the adjective here on the emplacement because we ourselves are the last untouched okay where the last we are just only to be looted so we answer sheet okay so This is such a thing that the chicken might have been considered ineligible. Now basically, let's discuss it once again quickly. The rhythm value is something like this that by taking non, the elastic of the zoom will be 11 - Suppose if the end size is of the face. 11 - Suppose if the end size is of the face. 11 - Suppose if the end size is of the face. A fuel will be used there till the nose Who lives in is equal to high, we will take it out, we will check the plus Highway-22, we will take it out, we will check the plus Highway-22, we will take it out, we will check the plus Highway-22, now what to check here, check the fuel carefully, if you have to drown, if your media comes, it means this one which we have Money and going to exile, there will be no limit on your left, this is just what you will do here, if you are going to increase it with the ride element, then I am your answer, I need to close the gate, otherwise it is not so, then you Do n't impose empress on people, ok, why will the truth go here for humans, we have the option, if Google app goes to the right, then it is nothing, if MS Word is not defeated, then this rupee is history, otherwise in Alif, or if Yours and last induction which we saw in this one, look at this, your last index is on mother's name last next, so here only you have on the left side, I have given that what will you do only with this and which is that he is your elder which is this. Element on the fort, a little - minute, if she has a big little - minute, if she has a big little - minute, if she has a big meaning, family, your speak index, Rafiq element, conducting a written, ours, otherwise, what is the option, now she will ask on the right, then one option, go to the left, then you will like, minus point, okay, no. So what will we do in the album in the age, in this we have set this which was for minutes, this one will check this one is bigger than these two and his lips, then he looks at that side, if you understand your fruit, how is this one, then someone It is very simple, what to do first of all, we will take a size and variable in it makes the size that if this is Mukesh, it is one, if you understand, you have only one limit, only yours, then what will you do, if it is not, then people will play that. Take out the day, if it is of chilli, then if the video comes, it means there is an element on the left only on the front, then compare it with the light one, if it is bigger then I am fine with yours, injection of papaya element because there is an option to maximize the people. Two are fine, similar exams will come midway - that is only in your life you will come midway - that is only in your life you will come midway - that is only in your life you will eliminate someone on less than fence safe and if it has increased by minutes from the left one then it is okay by the media, if not the injection of limit then it is Haiku - 134 then it is Haiku - 134 then it is Haiku - 134 and what will you do in the last If you do then friend, if the midwinter fall in these is increased from both left element and right then it is Marathi, otherwise Johnson is a big limit, go towards that side, if my plus demand is this diet element is big then we will stop eradicating people. Will do the right and minimum, okay, let's submit it is accepted, and the description of the pattern has been taken in the description, there is same to same logic, there is nothing new, nothing is different and login is the login time, okay in this way. We are using extra and the vitamins will be applied. Please like and subscribe the channel and till the next video minutes.
Find Peak Element
find-peak-element
A peak element is an element that is strictly greater than its neighbors. Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**. You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in `O(log n)` time. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 2 **Explanation:** 3 is a peak element and your function should return the index number 2. **Example 2:** **Input:** nums = \[1,2,1,3,5,6,4\] **Output:** 5 **Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1` * `nums[i] != nums[i + 1]` for all valid `i`.
null
Array,Binary Search
Medium
882,2047,2273,2316
841
hello and welcome today we're doing a question from Li code called keys and runes it's a medium let's get started there are n rooms and you'd start in room 0 each room has a distinct number in 0 1 2 all the way to n minus 1 and each room may have some keys to access the next room formally each room has a list of keys rooms I and each key rooms IJ is an integer in 0 to n minus 1 where n is the length of rooms any key rooms IJ equals V opens the room with number B initially all the rooms start locked except for room 0 you can walk back and forth between rooms freely returned true if and only if you can enter every route example 1 we have room 0 1 2 3 we output true because we can start in room 0 pick key 1 and then go to room 1 so we go to room 1 and pick up the key to go to room 2 at room 2 we see we have a list of keys room 3 is in that key go to room 3 there are no keys there but it's ok since we visited all of the rooms so we output true example 2 we have room 0 1 2 3 and here we output false we start with room 0 and we see we have keys for room 1 and 3 so we can go from 0 to 1 and 0 to 3 so at room 1 what keys does one have it has keys 4 3 0 &amp; 1 so 1 can go have it has keys 4 3 0 &amp; 1 so 1 can go have it has keys 4 3 0 &amp; 1 so 1 can go to 3 and go to 0 or it can go back to itself and at room at 30 we have keys for 0 and we see that we never actually hit room 2 so we output false so for this question we want to start with all the rooms that we can visit everything that's unlocked we start from room at 0 we see what keys that room has and add those to our next rooms to be visited and for each room that to visit we see what he's that moon has if we haven't already visited those rooms we add that on to our lists who visit next so what I'm gonna do is I'm gonna have a set for visited rooms and exact for rooms that are unlocked that I need to visit and it's gonna start with the room 0 since room 0 starts unlocked so why would stack is not empty so while stack I'm gonna pop off what's in stock so Lewin equals sad huh and I'm gonna explore the keys in that room so if I'm doing this I can add my room to my visited tech since I'm in here I'm visiting this so visited dot add room and then for key in rings index with room for each key I want to check if it's in visited or not if not I'm gonna add this to my side so if he not in visited sack dot append key and we're gonna go through the entire stack that way once done we're gonna return true or false so this means if we visited all of our rooms the length of visited is going to equal our input list so return whether or not the length of visited equals the length of rooms and a quick walk through let's start with this example right here we have our visited and it's gonna be empty and we have stack which is gonna start with moving 0 so I pop off what's in stack have that in my room add that to visit it I check all the keys in this room so I have keys for one and three none of them are in visited so I add that to my stack go back in pop off what's on top I got two visited take off from dreams and that to visit it check all the keys in that room so I have keys for 0 but I see that it's already visited so I have nothing in back I need to add to stack so I can move on back into my while loop and pop off the remaining room added to visit it and iterate through room ones key so I have key 3 it's already visited nothing to add to sack I mean zero is visited room one is visited and I have nothing to add to side so what the length on my visited is three but I had four dreams so I had zero one two three I had four rooms in total I needed to visit but I only visited three so I would output pulse so let's run code and then comment all of this out accepted and submit and it is accepted as well if you have any questions let me know it down below otherwise I'll see you next time
Keys and Rooms
shortest-distance-to-a-character
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_. **Example 1:** **Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\] **Output:** true **Explanation:** We visit room 0 and pick up key 1. We then visit room 1 and pick up key 2. We then visit room 2 and pick up key 3. We then visit room 3. Since we were able to visit every room, we return true. **Example 2:** **Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\] **Output:** false **Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room. **Constraints:** * `n == rooms.length` * `2 <= n <= 1000` * `0 <= rooms[i].length <= 1000` * `1 <= sum(rooms[i].length) <= 3000` * `0 <= rooms[i][j] < n` * All the values of `rooms[i]` are **unique**.
null
Array,Two Pointers,String
Easy
null
1,394
hello girls total reality doing with the first really important here coal today's problem is fine lucky number a mean to you so what is all about like given another and okay number even to go to sleep and series in the or is equal to the value for example there is the value enough difference is to about food is to which is a lot younger so many anywhere 103 difference your face to and frequency of 3 is 3 so yellow key number is 3 although you can get to also but here to take the largest one and here also to here and nothing is there okay number so it is giving a minus 1 there is no in here is minus 1 you can say member so best way to approach this question is to map what will do you will get a map and then you just move their dog says we'll basically will be storing each value with a total number of three pencils so initially it will be nothing but ever SMS it gets the again like appear in something again same number you know just an agreement to so basically this is creation of the map with all the numbers and then we will just use lucky - 1 because 2 minus 1 if there's nothing - 1 because 2 minus 1 if there's nothing - 1 because 2 minus 1 if there's nothing as we need to check so if I dot first which is the T value is equal to a dot second and sorry and I dot first this greater than lucky then later lucky equality I go first and just within their lucky for this let's okay that's fine okay girls drinking Nancy in the next room
Find Lucky Integer in an Array
find-lucky-integer-in-an-array
Given an array of integers `arr`, a **lucky integer** is an integer that has a frequency in the array equal to its value. Return _the largest **lucky integer** in the array_. If there is no **lucky integer** return `-1`. **Example 1:** **Input:** arr = \[2,2,3,4\] **Output:** 2 **Explanation:** The only lucky number in the array is 2 because frequency\[2\] == 2. **Example 2:** **Input:** arr = \[1,2,2,3,3,3\] **Output:** 3 **Explanation:** 1, 2 and 3 are all lucky numbers, return the largest of them. **Example 3:** **Input:** arr = \[2,2,2,3,3\] **Output:** -1 **Explanation:** There are no lucky numbers in the array. **Constraints:** * `1 <= arr.length <= 500` * `1 <= arr[i] <= 500`
null
null
Easy
null
1,769
hey everyone uh today i'll be going over the elite code problem 1769 minimum number of operations to move all balls to each box so you have all this junk here but as always i'm just going to explain it as simply as possible and i'll do so with this test case here so given this test case we're given some string and these are just boxes right and it's a one if it has a ball in it and it's a zero if it doesn't have a ball in it so you could think of this string kind of like as an array right so it's like this uh so this one has a ball basically we're trying to figure out um the minimum number of operations to move all of them to each box so moving to this first one how many operations would it take to move all these balls to this box well it's simple it's just how far are they from it right so this one is two from it so we have two operations so far uh this one is four from it so we have six operations so far and then this one is five from it so we add five and it's 11. if you actually look here uh this is in the example two uh this one is eleven uh if we follow the same logic you get the rest of this so i won't do that because it'll take a while so you can actually do it exactly this way it's kind of naive but that would be an n squared solution and we could do better than that now you could just calculate the distance of every box to every box uh that would be an n squared and it does work but yeah it would just be too weird um you can actually do this in end time which is what i'm going to be showing so we can actually get crafty about this right we can go left to right and right to left in this array and calculate the accumulative distances from each ball to going to the end basically so we can do that because if we go left to right and right to left if we add those at any given point that'll be the total number of operations to get all balls from the left and all balls to the right so that's exactly why we're doing it this way so if you look we're getting a result here so let's set up our result which is just a res and it's going to be the same exact size as length and we do it this way remember boxes is a string this throws a lot of people off but we can just treat it as an array right we're going to have a few more things which is a res i'm gonna have an ops which is just total operations and you'll see why and also a count okay so the first thing we want to do is go left to right so what is the goal here we're just trying to figure out the accumulative distance of getting all balls everywhere we see in the array from left to right so we're going to go left to right and boxes length and just a normal for loop right the first thing we want to do is at this point we want to add however many operations we have the reason why we do this each iteration of the loop is because we're going one more right so if we're going one more we have to add all the operations we've already done because they have to go one more distance so an example is if we've had five operations at index one going to index two it'll be plus five more because they all five of those balls have to go over so that's why you do it that way uh the next thing you want to do is we're going to add the count and this is just counting like the ones the balls the total balls uh we're going to add to the count uh however many balls we have and to just quickly figure out if this is a ball and treat it as a number let's just go boxes dot car at i and let's just convert it to an n so we'll go minus the zero card because if it's zero it'll be zero if it's one it'll be one right so we'll do that and then the next thing we want to do is we just add count to the ops because what however many balls we have at this point we'll have to add it to operations for the next iteration and it's just that simple uh we can actually just go ahead and copy this down and then make this right here boxes dot length and then we're just going right to left right sorry about that so this time right to left same exact thing another thing we want to do is since we're going right to left and it's a fresh iteration uh we actually want to reset uh ops and count right so let's go ahead and do that so ops will be zero again and count will be zero again and then lastly let's return res and we should be good let's go ahead and run this oh res is already defined oh yeah i hope somebody called that we actually didn't need a ras variable that's silly so let's go ahead and run this it looks like it's good let's submit it and looks like it's good 76 so let's talk about run time remember i talked about the bad solution and why it was going to be n squared and this is actually uh o n time because all we're doing is two loops left to right to left so it's 2n which is just n right uh space we do not count the output array as space usually because it's not extra space this is expected space so really space is one right because we're not using anything besides the output array so yeah i hope this made sense thank you for watching i appreciate it and have a good one
Minimum Number of Operations to Move All Balls to Each Box
get-maximum-in-generated-array
You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball. In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes. Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the `ith` box. Each `answer[i]` is calculated considering the **initial** state of the boxes. **Example 1:** **Input:** boxes = "110 " **Output:** \[1,1,3\] **Explanation:** The answer for each box is as follows: 1) First box: you will have to move one ball from the second box to the first box in one operation. 2) Second box: you will have to move one ball from the first box to the second box in one operation. 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. **Example 2:** **Input:** boxes = "001011 " **Output:** \[11,8,5,4,3,4\] **Constraints:** * `n == boxes.length` * `1 <= n <= 2000` * `boxes[i]` is either `'0'` or `'1'`.
Try generating the array. Make sure not to fall in the base case of 0.
Array,Dynamic Programming,Simulation
Easy
null
199
today we're looking at lead code 199 binary tree right side view this is a continuation of our level order traversal series in this playlist and we are going to be using the same template the same pattern to solve this as we use to solve the other problems that deal with level order traversal in this playlist that's including binary tree level order traversal one and two n airy tree level order traversal and a zigzag level order traversal so we're just going to make a slight modification and we're going to use the same pattern to solve this one as well okay so what we have here is we have a binary tree we're given the root and we want to imagine ourselves standing on the right side of it and return those values of those nodes so they can be ordered from top to bottom so here we have a tree we want to return 1 3 and 4 because they are all on the right side of the tree and our nodes are going to be 0 to 100 and the values are minus 100 to 100 okay so what we want to do here is if this is our tree we want to have two while loops and then we want to use a q data structure okay and what we're going to do is we have this q data structure we're going to initialize it with the root okay and we're going to also initialize a result and set it to an empty array and now we have two while loops here okay we have an outer while loop that as long as the queue is not empty we keep on running this loop and an inner while loop that we want to get the length of the queue at that moment in time okay so uh let me just kind of step through that here we have the q it's at one it's not empty at this point we can see that the value in the queue is at the zeroth level okay this is zero one two the value at the queue at this point in time is one which is the value at the zeroth level so when we get to this point we're going to save the length of this of the queue at this point which is one and then we are going to take the last element in the queue okay at this point it's one so we're just going to go ahead and push this one into the cube now we are going to go into our inner loop and we're going to run it length times okay so we'll decrement it when we're inside of there and what we want to do is po pull out this one so we shift it off and we put its children back into the queue so we check if there's a left there is we go ahead and push that two into the queue we check if there's a write on the one node there is it's three we push that into the queue and we only did it on one iteration so we break out of that while loop that inner while loop and now we're back on the outer while loop and you can see now the queue has the correct values for that first level and so all we're going to do is take the last value here this 3 whatever is the last element in the queue and push that into the result so here we have 3 that gets pushed into the result then again we do the same thing we save the length of the queue at that moment into this lend variable which is going to be two and now we go into our inner loop and we're going to run it twice okay first time we run it we're gonna shift off this two and it does have a child it has a 5 so we go ahead and push this 5 into our q and we decrement this length here to 1. and then we go ahead and shift off this 3 and we go ahead and put that into the queue or we put the children of that into the queue which is four okay and then this length will turn zero and we'll break out of this uh inner while loop now you can see that the q at this point when we get back into the outer while loop has the correct values for that level and we just want to get the last one we just want to get this 4 push that into the result and that is our answer and again we'll just do one more iteration just to kind of go over this the length here will be 2 and then we go into the inner while loop we shift off this 5 node we check for any children there's no children we shift off this 4 node there's no children at the same time this decrements down to zero we break out of this inner loop and now there's nothing in our queue it's empty okay the queue is empty and so we break out of this outer loop and then we go ahead and return that result okay so that's the idea behind this now what is our time and space complexity i know there's two while loops so it's tempting to think that we're doing this in quadratic time but you have to think about how many times are we hitting these nodes okay how many times are we traversing through these nodes and we're only traversing through them once because even though we have two loops this second loop is just running level by level it's not running through the whole entire tree and so our time complexity here is actually o of n it's just linear time because we're just hitting all these nodes once and then what about our space complexity well it's not linear normally in the other videos it's linear because we're saving the entire level here we're just saving the values on uh on the height of the tree okay so just on the right side of the tree we're just saving those values and so the uh the um space complexity is gonna be o of h which is the height of the tree and if it's balanced then it would actually be log n but we don't have a guarantee that the input is a balanced binary tree if it was a balanced binary tree then we would have a space complexity of log n but in this case we can just say the space complexity is the height of the tree because we're just going to get the right most values which is just going to be the height of that tree the right height of the tree okay so let's jump into the code um the first thing we want to do is uh just go ahead and whoops we don't want to do that okay see what's going on here okay so first we want to take care of the edge case if the root is empty then we just want to return an empty array okay and now what we want to do is go ahead and initialize our q and place our root inside there go ahead and initialize our result set it to an empty array and then we just want to do while the queue is not empty we want to save the len okay and then we want to push into the result the last element in our queue okay so we can do result dot push q uh sorry q at q dot length -1 q dot length -1 q dot length -1 and then here we just want to do a dot val because this is asking for the values not the nodes okay but in the queue we're actually saving the nodes all right and so now what we do is we do a while len minus all this is going to do is decrement len until it gets to zero it'll coerce to a false value and break out of that while loop we want to shift off the node okay and now we just want to put the children into the uh into the queue so if there is a left child we can just do a q dot push no dot left and if there's a right child we can do q dot push no dot right and then we just want to return our result okay and that's it let's go ahead and run this make sure everything works and we're good is elite code number 199 binary tree right side view hope you enjoyed it and i will see you on the next one
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
677
hey hello there today i want to talk about question 677 maps on pairs we want to implement a class called mapson which supports two methods uh insert and some so it's a pretty much a very simple key value of storage the insert is the right operation the sum is the read operation so the let's look at keep reading the insert method will be given the key value pair the string is the key the integer is the value so we want to remember the key value of mapping if the key already exists we want to update the associated value to be the newly given up volume so this insert handles both insert and update then just the read message the query the sound method here we'll be given the string represent prefix so we're doing kind of a prefix matching we want to return the sum of all the values associated with the key that starts with that prefix so looking at example uh so the we initialize this theorem structure we insert the first the key value pair apple to three so when we do a query using ap as the prefix because ap matches apbre in the prefix kind of a sense so we know that apple has the value 3 so we return 3 because this is the only key value pair we currently have now and ap actually matches that now we insert another new key value pair abb let the value be 2 now if we do the same query sum ap because ap matches both apple and app in the prefix sense so we add those two values together and return the sum which is five here so the obviously the very obvious way to do to solve this problem is to just use map string to value so that's the insert the time complexity for this is almost a constant all we do is just take the string to a hash and create this key value mapping it's almost the constant the query sum is to do this prefix mapping map matching for key in keys if uh if key dot starts with the query then we um you know answer add this value something like that so we're going to have a loop to iterate over all the existing keys in this data structure and for every key existing key we will match that try to match that with the prefix so let's say the prefixes of size l the length of for the prefix then we have n key in total this thing would cost uh n and multiplied by l in time so we can see here this very simple approach using a just using a map to store the key value association have the sum to be the sum here has to be quite heavy on the time complexity it has to check all the keys so it's not so ideal so let's think about how we can actually speed up this query so since that we are doing prefix query instead of just inserting the single key value pair we can insert all the prefix to the same value mapping if none of those existing yet if it's if the prefix exists that we're going to do some update so let's talk about we're just going to do so this is called this second approach is going to be i'm gonna show you how it looks like so if we insert apple three so instead of only have one entry in the key value mapping storage apple two three we actually gonna do r a to three ap to three app to three appl to 3 and also apple to 3. so the next time we search for anything that starts with ap we can just directly grab the value here so if we insert another key value pair ap to apb to 2. what we're going to do is to basically follow the path gear and updating here to be 5 and 5 because we're adding 2 now so if we search for ap the prefix ap we're just going to directly grab 5. let's talk about another thing update let's say that we insert apb equal to 1 this time what we would do is to do some kind of an adjustment to all the nodes uh all the nodes all the prefix key value pairs here so we know that app used to be two but now is 1. so the difference is 1 subtract by 2 equal to negative 1. so for all the prefix in appb we're going to decrement the value by 1. so after this update if we do the prefix query for anything here it should return the correct value so we can see here we use a lot more space and the insert is now no longer constant anymore so this insert now takes uh we have to consider all k up i'm using l right uh all l different uh prefix for the key and if we're using c plus we might have constant slice but for most languages it's uh the string is immutable so the take the slice take the prefix it takes also linear time so it will be in this case it will be l square time but the good thing about this is that the query is constant so the difference between this approach one and approach two is that one is uh very light on the insert but the queries the read is complex second one we basically are trading space and the time on the insert to speed up the read so the read is not constant but the insert is the key size squared so we got some trade-off there so the question is now is there something that kind of in between maybe ideally both linear in terms of read and write so if our application the this key value storage is used to support sort of balance the read and write we want to approach three so notice how this looks like here in the second approach we basically create a path sort of like a pass inside the try we have a root note points to a points to b p points to another p that p note points to have a children start with uh that has a key of uh l and so on so forth um we will just uh if we use try we can just store all those uh prefix to the value kind of association um just as the just put the number as a one of the properties for the try node inside the tri data structure so that way we essentially store the same information as prefix hash but the insert is going to be linear time we just go one path uh through the following the you know the key or the query do a linear pass inside the try and updating the values for the nodes along the way so if we use try the insert is going to the time complexity is going to go down from l square to order of l but the sum we no longer can directly look up at the prefix to volume mapping we have to start with the first character and do a linear path inside the try to graph the value so that's sort of like a balance in between the we now have linear time insert and linear time uh query so let's just quickly put it in here approaches three is to years try to have order of l in both insert and the sum i guess depends on the real application use case you can choose either one of those the one of the three approach that satisfies the needs the best yeah so i'm gonna just code the try solution because it's uh the one that requires the most code so we're going to define a try node here i'm just subclassing the default dictionary so the try is more dynamic we only insert this character to you know the next character to the node association when we really have to so the space is growing dynamically even though it will be slower than pre-allocation so pre-allocation so pre-allocation so we're going to set the constructor of the default factory to be the tri node itself and every node we just have a value associated with it so it's like the node a will have five node p following node a would have another five node p following the previous node p will also have a value of 5 associated with that node so that's this slot here initially every node would just have a value 0. now we initialize this key value of storage all we do is to create a root node here now let's code the insertion oh something that we need to do is for either two and three the approach we also need to keep the same key value pairs as the first one because the update here remember that when we insert up apb to 2 we just go we either update all the prefix hash in the second approach to have all those add to um in the try we just follow the try paths to update every node value to increment those by two but when we have a update uh we have to figure out what's the previous value and calculate the delta use that downtown to update all those prefix or in try's case it's updating all the values for the nodes on the path so for that reason we want to store the key value pair we can do a single pass and try to grab that uh or in the prefix hash sorry in the prefix hash it's always there but in the try we could either do a linear path to grab the value or we can use extra space to store that so if we actually just do a traverse to grab that then figure out the data and do another second pass the insert is still linear in with respect to the size of the input so but if i can directly look it up it might be faster so i'm going to use a map to do that so this will be a it's pretty much the key value pair so it's a string to integer mapping okay so let's cut the insert here is basically create a path inside the try if the character does not exist otherwise we will just try to do the update so if the tree if the path does not exist that means we don't have a key for that for the key here inside the try that's essentially meaning that we have a delta of the value here so to have the insert the function for both insert and update we always going to be dealt with that delta for a fresh new insert the delta is just the value for real update is going to be the difference between the new key and the o key so if we don't have that key the default dictionary will return a zero so the difference is pretty much the value itself so this will make sure that the insert were exposed in the new case or the update case so the insert is just going to do a single passing try we get the node which initialize the root for each character inside the key we're just going to traverse keep traverse inside the try uh node c char let's make uh make the code a little bit more readable and for every node here uh we're gonna set the update the value is the delta yeah so this should be the insert okay we should also update this as well remember the new value for the key now this for loop is to do a linear pass inside the try and for every tri node along the way we update the value with the new delta so that's the insert you can see here it's a log of lti here for the sum it's uh it's going to be the same situation we're going to grab the root node and for every character in the prefix we're going to do a quick check if it's not there we should return what we should return we should turn zero right because there is no value associated with that key otherwise we're just going to follow that path and once we exhausted all the character inside the prefix we will land in the node that we can just uh directly return the value i'm not sure should we return 0 or something here it doesn't say in the question let's see if the code works it's working uh let's try to do a test case when we have a prefix that's not existing here so we insert output three we try to query apx what kind of thing you should return it should return zero okay so this has i think it's better to just make a quick note here if the prefix does not exist we should return zero all right uh so it seems to working let's submit it okay it's working um so uh yeah it's uh it's not a hard question and the good thing about it is about this question is that we have three different time complexity uh decisions that we can come we have three different approaches which they all have their trade-offs even the they all have their trade-offs even the they all have their trade-offs even the most straightforward method can be useful uh if we are dealing with a really right heavy but rarely read the kind of situation but for the second one is uh read you know they're the trade-off the read you know they're the trade-off the read you know they're the trade-off the right is slow but the read is super fast uh the one that i code here using try is sort of like uh in between so i guess it's some this should be maybe like a default option if we really have three different kind of options for this keyboarding storage all right so that's this question today
Map Sum Pairs
map-sum-pairs
Design a map that allows you to do the following: * Maps a string key to a given value. * Returns the sum of the values that have a key with a prefix equal to a given string. Implement the `MapSum` class: * `MapSum()` Initializes the `MapSum` object. * `void insert(String key, int val)` Inserts the `key-val` pair into the map. If the `key` already existed, the original `key-value` pair will be overridden to the new one. * `int sum(string prefix)` Returns the sum of all the pairs' value whose `key` starts with the `prefix`. **Example 1:** **Input** \[ "MapSum ", "insert ", "sum ", "insert ", "sum "\] \[\[\], \[ "apple ", 3\], \[ "ap "\], \[ "app ", 2\], \[ "ap "\]\] **Output** \[null, null, 3, null, 5\] **Explanation** MapSum mapSum = new MapSum(); mapSum.insert( "apple ", 3); mapSum.sum( "ap "); // return 3 (apple = 3) mapSum.insert( "app ", 2); mapSum.sum( "ap "); // return 5 (apple + app = 3 + 2 = 5) **Constraints:** * `1 <= key.length, prefix.length <= 50` * `key` and `prefix` consist of only lowercase English letters. * `1 <= val <= 1000` * At most `50` calls will be made to `insert` and `sum`.
null
Hash Table,String,Design,Trie
Medium
1333
1,906
Hello Everyone in the month of Sandeep and in this video you will show you how to solve plate problem vs problem se zameen akshikari na dheer wa nyanyat subscribe our channel subscribe a slack we examples and tried to understand what a question is singh sirf example examres 130 More than time to subscribe to that a army this zero earn one which is this particular morning what is the meaning of subscribe elements and values ​​from a subscribe elements and values ​​from a subscribe elements and values ​​from a are next wwc2 what is the way want to that is the what is the difference among all elements and the Politically and Subscribe - ₹499 Vighna more subscribe Subscribe - ₹499 Vighna more subscribe Subscribe - ₹499 Vighna more subscribe and subscribe the Channel subscribe that 2G spectrum of and B-2 element is that 2G spectrum of and B-2 element is that 2G spectrum of and B-2 element is my duty Difference latest wave fight According to a Divya Narendra the difference will be a 3 The Best Answers Issues and Electronic to the Answer Is Vansh Returning from example2 452002 end subscribe that fry already set up all the limits in rangers same denge pattern - off service - rangers same denge pattern - off service - rangers same denge pattern - off service - that Bigg Boss all elements in the avengers theme next straight or 2000 2 eggs subscribe and subscribe to the Page if you liked The Video then subscribe to the Page Differences One is Next Subscribe Inside Do n't Forget to Subscribe 56001 Subscribe Channel Subscribe Must Subscribe Subscribe Thank You Information On Hai To Laut Aayi Want Justice For particular index of evidence that Idea want to know what to eliminate them before but no one can select the ability to this worship that I problems in it ranger balance marriage palace can go from 1200 after 10 minutes pan lid and explosive assistance force but not limited To have next pada tha rose day can help in tasty elements present itself a the correct select c android 2.3 lines is correct select c android 2.3 lines is correct select c android 2.3 lines is in the limit for 52 years older than what does have no option for vansh 1512 is to arrest nothing is seen the correct way to the Holly and 4151 Two Times for Extra Oil That Toot Guys Is Possible to Build a Splash Select Subscribe Before You Start Other Elements Present in Everything Is Us a Product Solve Animated 605 What All Elements Present Before This From This Particular Form Correct Sacrifice and Drop Again That someone else The Element of Presenting You in Next Time When You Are Ment for 28 2012 Will Do Something Good for Everything in this Value The Correct That New Swift Equals Early-Morning Youth The That New Swift Equals Early-Morning Youth The That New Swift Equals Early-Morning Youth The Elements of Medicine for Five But Avoid This To-Do List Life Processes In Like This To-Do List Life Processes In Like This To-Do List Life Processes In Like This Particular Role Model Elements Have Seen Subscribe To All World Channel Next Debit Is Equal To Ayodhya Notification But Avoid Calculator Values For This You Minus One Ranger Tense Present In This Particular Roegi Coffee Date Hai Na Deni Wali Mein But It Was Perfect Love You To Applicant Index 2.1 SIM Ko Love You To Applicant Index 2.1 SIM Ko Love You To Applicant Index 2.1 SIM Ko Swadist A Flying This Is Always 90 Degrees And Tried But Always Seen Till Now And Sunao Hafte Dal Di Values ​​For You And Sunao Hafte Dal Di Values ​​For You And Sunao Hafte Dal Di Values ​​For You Interested In All Its Students Of Query The Freedom Of Speech Main Se Chaliye Ye Want To No Jai Hind Istri 315 What is the Best Defense of the Great Co Targeted Vs Difference Only Value - This Targeted Vs Difference Only Value - This Targeted Vs Difference Only Value - This Value 1008 Columns in This Element Hindi E Was the Like U World Record of 102 Traffic Jams They Arrange Values to Small Value Salwar Late Message Do 102 quality information from this point to subscribe my channel to left right the center ranged from this rains we have the greatest range ki dadi a hair oil them with the republic day to all of us here we have times we have dropped in the Center Range Select Ghaghra 15000 Next Se Mobile Again Zero - Se Zinc Vansh Birthday Mobile Again Zero - Se Zinc Vansh Birthday Mobile Again Zero - Se Zinc Vansh Birthday 182 90252 Angle Definitely Subscribe Next 9 News Se Just Rs 10 Mobile Aggressive 108 Me This Element Was Again Notes In Hindi Strange Enemies Convention Only But Not On Scene Drishtavya Acid 000 Definitely Comment 100000000 The note of the correct To give only eight tips Saturday 14th 6820 Volume Minimum Episode This not only the plain mode of this is elements of Baroda always involved in the first to in more increasing range ke range subscribe according 1000 subscribe to the Page A Saiya Diet Wikipedia Introduction Element Ranges From 12108 Dubey Only Tight And Element - Features - Element From Zet And Element - Features - Element From Zet And Element - Features - Element From Zet And Finally Bigg Boss Fixed Period Subscribe Must Insects Straight To A Plate Crops Country Code Vegetables Difference In Function And Two Parameters Norms And Where Is Not Physically Storing The Video then subscribe to subscribe the Channel Please subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe and subscribe the Channel Please subscribe thanks for [संगीत]
Minimum Absolute Difference Queries
maximize-score-after-n-operations
The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1`. * For example, the minimum absolute difference of the array `[5,2,3,7,2]` is `|2 - 3| = 1`. Note that it is not `0` because `a[i]` and `a[j]` must be different. You are given an integer array `nums` and the array `queries` where `queries[i] = [li, ri]`. For each query `i`, compute the **minimum absolute difference** of the **subarray** `nums[li...ri]` containing the elements of `nums` between the **0-based** indices `li` and `ri` (**inclusive**). Return _an **array**_ `ans` _where_ `ans[i]` _is the answer to the_ `ith` _query_. A **subarray** is a contiguous sequence of elements in an array. The value of `|x|` is defined as: * `x` if `x >= 0`. * `-x` if `x < 0`. **Example 1:** **Input:** nums = \[1,3,4,8\], queries = \[\[0,1\],\[1,2\],\[2,3\],\[0,3\]\] **Output:** \[2,1,4,1\] **Explanation:** The queries are processed as follows: - queries\[0\] = \[0,1\]: The subarray is \[1,3\] and the minimum absolute difference is |1-3| = 2. - queries\[1\] = \[1,2\]: The subarray is \[3,4\] and the minimum absolute difference is |3-4| = 1. - queries\[2\] = \[2,3\]: The subarray is \[4,8\] and the minimum absolute difference is |4-8| = 4. - queries\[3\] = \[0,3\]: The subarray is \[1,3,4,8\] and the minimum absolute difference is |3-4| = 1. **Example 2:** **Input:** nums = \[4,5,2,2,7,10\], queries = \[\[2,3\],\[0,2\],\[0,5\],\[3,5\]\] **Output:** \[-1,1,1,3\] **Explanation:** The queries are processed as follows: - queries\[0\] = \[2,3\]: The subarray is \[2,2\] and the minimum absolute difference is -1 because all the elements are the same. - queries\[1\] = \[0,2\]: The subarray is \[4,5,2\] and the minimum absolute difference is |4-5| = 1. - queries\[2\] = \[0,5\]: The subarray is \[4,5,2,2,7,10\] and the minimum absolute difference is |4-5| = 1. - queries\[3\] = \[3,5\]: The subarray is \[2,7,10\] and the minimum absolute difference is |7-10| = 3. **Constraints:** * `2 <= nums.length <= 105` * `1 <= nums[i] <= 100` * `1 <= queries.length <= 2 * 104` * `0 <= li < ri < nums.length`
Find every way to split the array until n groups of 2. Brute force recursion is acceptable. Calculate the gcd of every pair and greedily multiply the largest gcds.
Array,Math,Dynamic Programming,Backtracking,Bit Manipulation,Number Theory,Bitmask
Hard
null
976
oh hey everybody this is Larry this is day what is it day 12 of the legal daily challenge hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's qualm 976 largest perimeter of the triangle it's Wednesday or Tuesday depending on where you are hope you are having a great week middle of the week hope everyone does well um yeah let me know what you think about this Farm I am not gonna lie I drank a little bit too much tonight um not that much actually I'm okay but I'm uh so we'll sell that how this video goes it's a little tipsy let's go uh given nums we turned the largest perimeter of a non-zero formed by the perimeter of a non-zero formed by the perimeter of a non-zero formed by the way of these lengths if it's impossible form on any triangle of non-zero area we form on any triangle of non-zero area we form on any triangle of non-zero area we turn zero okay so there is obviously the triangle in the quality um I'm thinking about whether so I'm just thinking about like a random property in my head I don't know if it's true where what is the triangle in equality right and that basically is that means that a plus b is greater than C right I was going to say equal to but I was like that's not true right and then my question is the largest of those three well what can we do right hmm because I think I'm inclined to say that so I have a hypothesis I guess that's what I'm trying to do is that and I don't know if this is true so it might not be right is that we sort then the answer is going to be adjacent why do I say that um and some point of this is kind of like a almost like a reverse um like if I try to kind of think a little bit backwards or another direction right the way that I would maybe think about is something like let's say they are not adjacent right let's say okay let's start with adjacent let's say we have a b and c where this is you go to you know um let's say N Sub I ends up I plus one N Sub I plus two right well if this is not a triangle would it ever make sense to like in a sliding windowy you know kind of way would it ever make sense to make this bigger no right because then it's still not a triangle would it make sense to make this smaller no then it's still not a triangle so that means that I feel like I mean it's not a great proof but that was the first intuition that when I first performed I'm like is this true and I to be honest I don't think I have a great proof other than what I just it's not what I show you start a strict mathematical proof but it's the idea that and you could kind of maybe prove that aware as well meaning that if there's a big you know if there's a an X such that X is greater than N Sub I then you want X instead right um because 10 has a bigger parameter um and then same thing well I mean I guess that's not the truth I was gonna say the same thing here but that's not true right but if we have another number that makes it bigger then we go right but I can prove it to be honest so uh yeah right um it's minus two uh which one was two no that's my story and I guess we can kind of go the other way I actually meant to just do it this way but if we go back if we assume that the adjacent thing is true I believe it is because okay oh yeah I think the other example I mean I didn't do a good job of this but the other example of like if uh num N Sub I ends up I plus one ends of I plus two if there isn't numbered with X where X is true I kind of skip this a little bit then that means that these three numbers are good instead so then you can remove this and also by definition these are adjacent or whatever right so I think that I think it's kind of tough because if it was in the contest I definitely would play around with it a little bit more maybe a lot more because I'm not that confident about this I feel like I'm okay enough to give it a go and there is some um you know meta second guessing with the fact that this is easy right like if this was a heart would I think a little bit more deliberately to be honest probably so this user is not a great hint well it's too much of a hint if you ask me um I'd rather not know it but yeah so we have a is equal to well ABC maybe thumbs up I num sub I plus one number so I plus two and then if a plus b is greater than C then we return a plus b plus C because that's the permanent whoops foreign otherwise we'll Return to Zero let's at least give it a quick run I believe that's the case I may think you can do an excessive uh proof in what I just kind of did I think I was kind of I wouldn't say I was okay there we go I haven't done this before apparently um huh I mean I don't think I could do any faster so that's a little bit whatever um this is obviously linear time constant space but I'm trying to think what I can think about a better proof oh no so I lied about the constant time sorry I forgot the Sorting so n log n time um you know constant space hmm yeah I think the proof that I would say is if you could squeeze a number between it then there that's I think that's the way that I would phrase it right meaning that if a plus b uh or a B and C is a triangle if D is in a can either you know if you're trying to add a d That's in between then a D and B is a triangle which of course in this case that means that well this number is going to be smaller than ABC assuming that D is between A and B right so that doesn't matter so if we have another D where B's DC is a triangle then obviously you know this number is strictly bigger than a b and c but I don't think that I described it that well but I guess I proved by AC let me know what you think let me know what your proof is if especially if a strict mathematical one maybe I could do better on a day where i'm I didn't uh you know drank a bit but let me know what you think that's why I have though so let me know what you think stay good stay healthy to good mental health I'll see how they then take care bye
Largest Perimeter Triangle
minimum-area-rectangle
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three side lengths: 1, 2, and 2. **Example 2:** **Input:** nums = \[1,2,1,10\] **Output:** 0 **Explanation:** You cannot use the side lengths 1, 1, and 2 to form a triangle. You cannot use the side lengths 1, 1, and 10 to form a triangle. You cannot use the side lengths 1, 2, and 10 to form a triangle. As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. **Constraints:** * `3 <= nums.length <= 104` * `1 <= nums[i] <= 106`
null
Array,Hash Table,Math,Geometry,Sorting
Medium
null
152
so what you're about to see next is me solving a leak code problem from my course JavaScript and lead code the interview boot camp where we solved the 75 most important lead toward problems using of course JavaScript and a JavaScript testing package called jest anyways the links to that course are in the description below I hope you enjoy the video all right so this video will be dedicated to the pseudocode for elite code problem 152 max product so make sure in the terminal your seed eat into the course directory exercises folder and then run this just command this is gonna fail our test suite so before continuing with this video I strongly recommend you did the maximum sub array problem from earlier on in this array section of the udemy course because the way we're gonna solve this problem we'll build upon the dynamic programming we learned from maximum sub array alright with that being said let's get started so when I first saw this problem I thought oh I'll just take the maximum my maximum sub array code right just paste it in and since we're doing a max product and not a max sum from maximum sub array I'll just modify this to be a multiplier instead and I should pass just fine right well I save as you can see half the test pass and half fail so how come our modified maximum sub array code is not working let's check the test J's file so we get an input of negative 2 3 and negative 4 if you return 24 back right but instead my code will return 3 but our code needs to count for negative numbers because remember that when two negative numbers multiply it becomes a positive number and we can have a larger a product as a result and again the problem states they have to be continuous right just like maximum sub array so we need to change our code here to account for negative numbers for a bigger max product and how are we gonna do that let's remove the faulty code and I want to explain how we're going to account for negative numbers here's the pseudo code we saw that input of negative 2 3 and negative 4 we're gonna create two DP arrays in parallel a max till index DP array and a min till index DP array so mental index will calculate the smallest product leading up to that index okay it's like the polar opposite of max so index and why would we try calculate the minim the smallest product leading up to a given index because again the more quote or the larger the negative number we get a larger positive number if one of the input numbers is negative now we're never going to reference this mental index array when we're trying to return the result okay so ignore these for now when our codes finish we return the largest value from our max till index array we just use the DP min till index array to recalculate the maximum product in max the index but again we still return the largest value from maximal index which is 24 and so let's see how the mental index GPA rate becomes useful let's say we are on negative 4 all right and we're trying to we're on negative 4 in the input array and we're trying to grasp but we're trying to figure out the maximum product right here at the second index of maximal index so in our maximal index at index I so right here let's say our eye is at index 2 math dot max is gonna be whichever is larger of these three things so which is larger negative 4 times 3 because 3 is the largest product leading up to right before negative 4 in here so which is bigger negative 4 or negative 12 well negative 4 is bigger all right which is bigger negative 4 or negative 4 times negative 6 because again we multiply the input number times the smallest product leading up to it well negative 4 times negative 6 is bigger than just negative 4 itself so we say oh it's 24 and so and the min till index I has the exact same inputs that we provide up here but now is that math dot min and again once we've finished filling out the max to index D P array which in which we use the mental index D P rate as a reference the calculators max use our code returns the largest number in max till index I hope that made sense and the next video were to implement the pseudocode all right so let's implement the pseudocode from our previous video so make sure the terminal your still seated into the course directory exercises folder and then run this jes command again to run our test suite it will all fail as expected and now let's implement that pseudocode so remember that we create a max DP or a admin DP rate till the index so I'll do that max to index is equal to an array where the first value is the first input number in the input array sometimes 0 then I will do the same thing for mental index why is that because well the maximum product and the smallest product up to index 0 assume there's only one number in is the first number itself right that's why we set the initial first value to be the first input number inside of my semicolons actually and then to save to do a minor time complexity optimization I'll say let max is equal to numbs 0 this should be familiar to you if you did the maximum sub array problem from before and now let's iterate through the input array I'll say for let I is equal to 1 eyes less than um strength I plus + eyes less than um strength I plus + eyes less than um strength I plus + to make my code easier to read I'll say constant um is equal to numbs at index I and now let's fill out the corresponding max till index at the correct index spot and the correct index spot in mental index so I will say max till index at index I is equal to whichever is larger right the input number itself the input number times the largest product to the left of it so I'd be max till index this is before it so we see I minus 1 or the input num so num times the smallest product to the left of it because again if our input number that are iterating on is negative multiplying by the smallest product to the left of it could potentially result in a large number so I'll say num times mental index right the largest or the smallest product most negative product to the left of it and remember from the pseudocode that for the correct value at that index spot in the DP mint index it's the same three inputs but we do math dot min instead so I'll just copy this here and say min till index I is equal to math dot min same three inputs from up here and now let's update our Max variable which will be accurate right because of this setting I'll say max is equal to whichever is larger the previous Max or where is in max he'll index at index I right our max DP array once this for loop finishes our max variable will now be the largest product out even after taking to account negative numbers great so after this for loop I'll just return max right and this should pass our tests great they do let's make sure our code also passes the leap code tests so I'll head on there paste it in and we're good to go so what's the maximum product sub-array so what's the maximum product sub-array so what's the maximum product sub-array complex the analysis time complex these all event right we have a for loop no nesting and space complexities also all event we created 2 DP arrays each the same length as input right our to dynamic programming arrays are the maximal index and mental index and these arrays are both the same length as the input array alright so that concludes this video it's me again I hope you found my solution video helpful and I plan on releasing more free content in the future and be notified that kind of stuff be sure to hit the like button subscribe and a little notification bell icon I'll see you soon
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
454
hey everybody this is larry this is day three of the february lego day challenge hit the like button to subscribe and join me on discord let me know what you think about today's farm uh hopefully everyone's doing well in general uh january has been over obviously so i'm gonna do these all month as usual uh i would say the stock market's been really kind of volatile and kind of a little nuts uh if you really want to hear people in my discord have been asking me about whether i should share some of my stories including the time where i lost uh a lot of money uh let's say half a mil or so i don't know if that's if these things are interesting to you leave it leave some in the comments below and maybe i'll just do a separate video or something uh today's problem is for some two i guess the second iteration we'll see what this iteration is um yeah so there's four numbers or four arrays oops what happened uh you're trying to find four index where they sum to zero okay so this isn't that bad right so basically there are a couple of ways you can do it n is equal to 200 makes it even easier to even think about what i can do is just divide it into two different um set of problems right we can have we can put force on numbers one and nums two and then on number three and nums um basically this is becomes i guess two sum right is that the one where you basically look up um yeah sorry i'm like my tongue is a little tight right now it's a little bit cold but basically what we're doing is we um i don't know if that's the problem in lead code so i may be making things up but basically let's say you have two different arrays and you're trying to find out whether um and an element from an array one plus an element of array two um you know whether they add to zero right or something like that so basically this is a variation of that where instead of having two arrays you have four arrays but and one way to do it is of course just dividing them to two different parts and then now you could generate um a bigger way two big arrays and then you wonder one the two array algorithm on it so that's basically the way that i would think about it um and given that n is equal to 200 you one of the quant called big arrays can be at most 200 times 2 um so that's going to be 40 000 right so that should be good enough so let's do that and we have let's start with um lookup let's just call it a lookup table of collections.counter and this is of collections.counter and this is of collections.counter and this is of course just um a hash table from mapping an object to an int so in this case we have for x in nums one for y and uh move my keyboard a little bit my finger's a little bit cold from just coming up from outside so yeah so we just do this and that should be good and then now we do another one which is for x and nums uh three for y and numbers four um lookup of x plus y will give us the answer right so then now we have total is equal to zero and then we just add this and that should be good that's uh let's run all the cases um yeah basically the idea is that you know if this x of y exists then for every combination we just sum up what was in the previous case and as i said the way that this looks like you know this is just like a two away version except for that we generate a big version of the two away with these things so let's give it a submit hopefully that's good should be okay i don't know unless i missed oh okay hmm i didn't know that there'll be negative numbers so i think maybe negative numbers froze it off but that's awkward huh did not expect this yikes okay let's take a look wow what am i doing wrong here hmm that is what wow a penny has gotten worse than i did twice two years ago but maybe i'm just a little bit too confident but hmm okay so that's at least we can get to use our debugging skill why is this wrong no this is such a weird case so what i would the first thing i would do is um you know this is kind of a big case so it kind of masks some of the situations so let's let's make a smaller version of the arrays what i was gonna say but i was also thinking about just different things um so basically we're still looking for a case where our code is wrong and yeah i don't think this is that's well do they all have to be the same length oh i didn't realize they all have to be the same length actually um i was going to analyze it with them independently so uh huh that's awkward do i have the signs wrong maybe my signs are wrong so let me check the math real quick so we have a plus b plus c plus yeah okay i got the signs wrong is equal to zero so then i was thinking about that when i was typing it but then i was like okay well we worked for the example cases and i guess i just got a little lucky because now if you think about it if you move this to the other side wow i am like really new today uh this is very easy to get wrong so you so that means that for here we're incrementing on this and then here we need a negative version of this okay fine uh let's give it a spin oops i actually thought about this when i was writing the code but i guess i just ran the example and looked okay um but i was like this looks a little bit awkward but i guess it could be okay i think i might have confused also a different version of this problem and then i just mixed them in my head um so let's give it a submit now uh okay cool yeah i mean this is exactly what we said and i think if you vote and this is a sin where i think i've talked about this a couple of days ago where sometimes i mean this is a sin that i do again sometimes the ones that you make silly mistakes are the ones that you've done too many times before because you're just like oh i don't have to test this it's good and then you make a silly mistake because you underestimated your opponent and in this case i think and i talked about the two away version and i think if you have really done about it you would have this is very clear that this is wrong right um it's just that i did not think about it for example if the two array version uh let's say you have two arrays you have let's just say a very simple obvious thing you have ten and one and ten into the other well in this case ten plus ten is clearly not zero but because you're looking for ten and a negative ten right so this is a very obvious thing in the two example case but i just was very sloppy because i was rushing for it uh maybe because i don't know why just one of those things um but yeah i was rushing for it and clearly this is not if i had just thought about it a little bit but yeah um let's go with complexity really quick um because n is all the same so actually this is just going to be o of n squared time and space um and yeah that's pretty much all i have for this one um and you can kind of see this very quickly because this can take at most n square space the n squared time is pretty trivial though because they're two for loops in each case um if you really want to be slightly more constant time efficient you probably should not do it this way because this does generate an entry here in the look-up table so it will here in the look-up table so it will here in the look-up table so it will probably slow down a little bit so you can have an if statement to make sure that it exists in it first um yeah i mean i was very sloppy whoops i guess in the past i was not as sloppy yup i was not as sloppy though this code looks exactly the same yeah i don't know how i explained it last time okay just this time i did the if statement so this is actually better do they change the input i guess so because i can't imagine i wrote try it i don't know that this is more clearer um really weird but anyway silly mistake hope you avoid it um that's all i have for today stay good stay healthy to good mental health i'll see you soon enough uh hopefully you didn't make a mistake like i did i'll see you good anyway bye
4Sum II
4sum-ii
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that: * `0 <= i, j, k, l < n` * `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0` **Example 1:** **Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\] **Output:** 2 **Explanation:** The two tuples are: 1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0 **Example 2:** **Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\] **Output:** 1 **Constraints:** * `n == nums1.length` * `n == nums2.length` * `n == nums3.length` * `n == nums4.length` * `1 <= n <= 200` * `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
null
Array,Hash Table
Medium
18
342
hey everybody this is larry this is day 22nd of august hit the uh lego daily challenge hit the like button subscribe and join me on discord let me know what you think about today's form uh so power four is it easy okay that's fine um there are a couple ways you can do it uh let's see you can do it i mean you can buy just to a lookup table if it's gonna look up here uh and then you know that's pretty much it i mean i don't you can construct a lookup table with you know in a way um there's also yeah i mean i don't know there's so many ways to do this right uh that it's a little bit silly um yeah i mean it's just basically uh the binary number is uh even number of zeros at the end of the binary is that a fun way of doing it i don't know um uh okay let's just do it the thumb way and then we'll i don't know i'm not really thinking about it right now so yeah so while n is greater than one and four and n mod four is equal to zero and we do it by four and that's pretty much it we just return n is equal to one um i mean there are definitely quicker ways to do it i'm not i don't think i'm gonna do it today uh ooh negative numbers so this can be wrong are there any no because all the power of you know if it's negative then it's always false right is that true zero negative 16 negative four because this isn't like the um to the third power or something this is just whatever right all right let's give it a submit apparently i've got it one three times before so hopefully today kind of i was quite just trying to be too clever today i'm not i'm a little bit lazy today uh yeah hmm okay a lot of silly i was trying to be too clever on a lot of these things but as you can see sometimes just do it in a generic way that works every time that's fine um this is going to be linear uh in this case linear is the number of bits because well you do a right shift twice every time this iteration so that's going to be linear in the number of bits so that's pretty much it really don't really have much to say to this one um we'll play around with this one if i have but today i'm gonna try to um maybe just a little bit later in the video right well it's only a two minute video but i am going to try to do the um brian 75 uh speed one so i'm gonna skip right to that and yeah you could i'll post it on youtube even though they'll be primarily on twitch um and if you watch this a little bit later it's gonna be on youtube anyway at some point so anyway stay good stay healthy to good mental health i'll see y'all later and take care no bonus question today because we're going to do the grind so see you soon
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,673
hey folks welcome back to another video today if you're looking at question 1673 find the most competitive subsequence the way we'll be approaching the solution is by using a stack to keep a track of the indices that we'll be using from nouns to construct the resulting area in the process while you're populating the stack you'll be checking if all of the numbers that you are encountering in the numbers area in a for loop they are less than what you've already seen in the stack while maintaining the size of the stack to be at least k so let's jump right in we need a couple of uh a few things to set up the solution which have we have a stack right here we have the length of the array and then we have the resultant array itself and let's initial initialize the for loop or in i equals zero from i less than n i increment and then we have a while loop this while loop is the most important part of the solution which is if while the stack is not empty and numbers of eye while it is less than the top of the stack and we have enough elements to give us k in the end k elements in the end while it is greater than k you will keep popping as soon as it gets out of the while loop you want to check that if the size of the stack is less than k only then you would push that as stack dot push i so just pushing the index not the element itself now once you're done with that for loop you want to populate the resulting array so and i is equal to k minus 1 um i greater than equal to 0 decrement i and then result of i is equal to nums cool so this populates the resulting array and in the end you would just return the array itself let's quickly compile this to see if it's okay the first test case passes everything else passes as well so let's quickly talk about the time and space complexity the time complexity of the entire solution is of n because you're looking uh you have a for loop that goes over all of the numbers in nums array and then the space complexity uh is okay since you're storing atmos k elements in the stack um and the resulting array as well um all right so that's a solution for this question if you have any questions about the way i solved it let me know in the comments below if there are any other questions that you want me to solve from lead code also let me know in the comments below please don't forget to like share and subscribe i'll see you all in the next video peace
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
1,870
foreign welcome back to my channel I realize I did not do the last few days of the July leap code or Juliet Code challenge recorded because I was traveling so we're starting this on Day 26 which is question number 1870 the minimum speed to arrive on time so when I submitted this would I submit this we had a rough go of it we struggled we did not do great there's definitely stuff I want to revisit and improve upon I really want to try to make this so it's like at least 50 or over on both memory and runtime but we're gonna go over the solution nonetheless because in this solution here um or in this uh kind of metric kpi here um we did get an effective solution eventually after one two three four five six wrong answers so I'm assuming other people have the same problem that I did if they didn't find if you guys are you know looking through this and you're like oh this is a question I'm gonna do um you can do this better I guarantee you but I wanted to go through my solution um and kind of explain it kind of line by line or like group by group or function by function rather so let's go through the question um I'm gonna read the question but I'm not going to go through the examples and constraints so let's jump into it so you are given a floating Point number hour representing the amount of time you have to reach the office to commute to the office you must take n trains in sequential order you are also given an integer array dist of the length n where dist I describes the distance in kilometers to the ice train ride each train can only depart at an integer hour so you need to wait between each train ride for example if the first train takes 1.5 hours you have to wait train takes 1.5 hours you have to wait train takes 1.5 hours you have to wait an additional 0.5 hours before you can an additional 0.5 hours before you can an additional 0.5 hours before you can depart on the second train uh ride at the two hour mark return the minimum positive integer speed in kilometers per hour that all the trains must travel at for you to reach the office on time or negative one if impossible to be on time tests are generated such that the answer will not exceed 10 to the 7th and hour we'll have at most two digits after the decimal point so then they give you the examples down here and then the constraints so first off I messed it up with kilometers we're not going to talk about it's part of being American that I do not love um so let's jump into this solution this first area that you see uh here and here this is what comes pre-loaded on the page when you get pre-loaded on the page when you get pre-loaded on the page when you get there and I can show you actually hold on give me a second so this is what comes I just deleted this part because it just felt a little redundant at that time um so as I put that back in here uh we start with seal or like the ceiling um which basically defines a helper function seal that Returns the ceiling value of the given number X uh if you can see here um which is the smallest integer greater than or equal to the original X so we then go to this area where it checks the length of the dist or distance list and it's greater than or equal to the hour plus one so if it basically means if there are more distances to travel then the given time allows so the function Returns the negative one from here to here we initialize two variables left and right left starts at one right is calculated as the ceiling of the maximum value between the maximum distance in dist and dist minus one over one if the hour integer is of the hour is integer um else this area [Laughter] [Laughter] [Laughter] so um this is essentially setting up an upper Bound for the speed um as speed is divided speed is distance divided by time right so we then go into this area which is a binary search Loop to basically find the minimum speed that we need to travel the distances within a given time so it basically just repeatedly calculates uh the middle point which would be the mid here and the left and right and then it calculates the time required to travel each distance at those given speeds and checks if the total time is less than or equal to the given hour um like here and then if the right is bound like if it's right bound it updates the mid otherwise the left it the it's left bound and it's updated to Mid plus one and then we just return the after the loop has been completed the binary search Loop has been completed we return the value of left um which basically represents the minimum speed needed to travel the distances in a given time so I hope this kind of makes sense basically we just use the binary search code our binary search approach to find the minimum speed required to travel a given distance or a set of diff distances within a specified time so while I didn't do great on the submission part of this I hope I explain the logic okay I know I fumbled up a little bit but I really did struggle with this one and they said it was I think medium but to me it was actually super hard um and I don't know if other people kind of feel the same way but um if you've done this problem I would love to know your solution and like just see what you did um but other than that I have the GitHub repo for all of my leak code Solutions down in the video description link below feel free to fork and clone make it better make it worse have some fun learn something new and that's what this is all about so I will probably do another video later on it's not going to be for some time where I rework this because I do want to spend some time reworking it uh just because that's important to me I really want to do better my goal is to get as many lead code problems done as I can and then to make them over 50 on runtime and memory just because that's a good challenge for me um so thank you guys for watching and I will see you guys in the next video
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
1,090
That Welcome Back Friends Vtu Solid Problem 1019 Conspiracy Values ​​From Labels Aa Soft 1019 Conspiracy Values ​​From Labels Aa Soft 1019 Conspiracy Values ​​From Labels Aa Soft Human Body Knowing That You Would Create List Solution Videos In Java Applets J2 Interview Related Helpful Videos And Would Greatly Spoil Like Play List For Liquid Videos Admins Computer Science Programming Stop Like Date For Search Web Result For Search List Dynamic Programming Address Please Check Out To Unit Have Not A Good Example State Will Help You In Preparation Of Love Interview Suspended Please subscribe to the Channel Sau Dus Subscription Is Helpful For This Channel Please Subscribe Now So Let's Look Into This problem in more detail show when it is cut off in items you are you want to interior is values ​​in labels satisfactorily interior is values ​​in labels satisfactorily interior is values ​​in labels satisfactorily label of the element are values ​​of label of the element are values ​​of label of the element are values ​​of labels by respectful also given to winters name is wanted news limit choose most taste cost in element search Data Is The Subsidy Gas So This Day And Equal To Na Wanted Director Most Used Limit Items With The Same Level In S10 Court Subset Is The Sum Of The Values ​​In The Subject Of The Values ​​In The Subject Of The Values ​​In The Subject Returns The Maximum Co Of Subsidies 200 Basically A What This Problem Is In Case After its time for example if you got 2nd shop right you will have different kind of products in the saunf product will have category light and product will have price should have given his daughter value mins you can contact details like age price and label kiss you Can consider these type of the product right and you have to select slims wanted product from this Actually from these products you can see a disaster products and you have to swim where slapped dumini products and you can choose from any type of the product you can choose Maximum one product for example of Rs 800 for example if you go to shop and buy from English your Baingan T- English your Baingan T- English your Baingan T- shirt Silai 10315 basically so you can buy maximum type of 1431 types from Dasha basically for this product so like that you can consider this example and You have to find out basically a maximum co light maximum co aa from this products actor will smith a selection so let's go for electrification work is plane mode turn on this is the value subscribe value can consider the price for example you can consider subscribe skin Problem Solved Problems But You Can Consider Basically Prostrate Subscribe Type Is So What We Want To Do Is Hui Will Create Class Products Product And Will Have To The Will Survive And Type And User Constructor Against Pass Value And Type And What We Want To Do Sol Problem Is They are going to use so chawal important data structure Congress priority Q this is important To create product where going to that points product object into the priority queue and amarkantak power company tarf but want the priority queue to short products in the decreasing order of the value so decreasing order value means 1501 with there lives and decreasing order of the way If you want to have then it's just consider one example in more detail and will know how the answer Ujjain find right and in other stories the implementation more details so you can consider a priority question solved will actually start like creating a product one by One so let's you are reading these five and were also a one by one who have to create product and they will put into priority 2051 product means five the value of the product and what is the time of Vinod this is the value five and type is Vansh Will Have Product in Obscurity Q411 Lately Please Not The Products Of Birds In Order To Value Automatically Subscribe And Uric Acid Decreasing Order Of The Volume To With A Lighter Note I Pin Were Put Into Practice Key And Torque R Priority Q Automatically List Mysura Reddy Values ​​each in decreasing Mysura Reddy Values ​​each in decreasing Mysura Reddy Values ​​each in decreasing order fennel update two with each here two that and after that is the country with a rich and one will be the value and three is the type of the product 154 start when you read this you can see and your SIM types of Light and destroyer of same type of product and this other type Sundar three types of product and basically and which can be used only one from each of the product use limit one mins you can choose one from the product and which have to maximize the Scores to Win This website will have to maximize the value Basically this is a What we will do this will keep you taking out the items one by one the products item one by one from the cube and would use map to recognize you know how many Item Platform In Type Already Used Keep For The Time Solid Se Besi That Ash Map That Is Here To Cost In This Book Will Create A Variable Called S Result 10th Result Variable Will Hold Over When You Are Doing Just Returned S Result Hair Soft Will All The Five Kama 1051 Services Will Make An Entry In That Time Prithvi Already Used One Item Of Type One Right Brothers One Item And This Is Used To Basically News One Of Type-1 Is Used To Basically News One Of Type-1 Is Used To Basically News One Of Type-1 Basic Mrityudand Se Used One Recent Member Of This Type Sunna Va Surtaan Result 125 Vikas Drink Water Left Side Now You Will After Five Know That Already Used One Time From Ghrit Way John Reduce And Used In This One So Will Just Skipping In This Item Loot Already User 5148 Daily Will Call The Other Item Proper Free To Solid Type -2 Software How To Use Free To Solid Type -2 Software How To Use Free To Solid Type -2 Software How To Use Type-2 Suv Marg Wa Type To Have Type-2 Suv Marg Wa Type To Have Type-2 Suv Marg Wa Type To Have Used To Watch Now Again Drive Views 521 Vyat Interwar Result Sunna Varidar V5 Plus 3 Nahak And Will Pol Hadith Ne This Item Sudesh Is Ignorance And Type-2 Inch One * If Hai Samay Is Ignorance And Type-2 Inch One * If Hai Samay Is Ignorance And Type-2 Inch One * If Hai Samay Apna Pariksha Have Used To One So They Ca n't Used To Give Its Then And After That Hui Kaur Ne Is Item Right Vikas Hui Want To Find The Total Key Items You Already Have Found To Items Date Hui Hai Viewers Ne Ki Adorable Item Mission Used to visit this item producer type three and will make an entry improvement shot one to use of type three and toubro adv1 interwar result sun hui have already got another total numbers quantity right choice 1232 used to five plus one is not So let's move decentralized within normal rate Swadeshi approach will create product class will come in the universe will put products into priority queue in the oldest existing of values ​​are its highest existing of values ​​are its highest existing of values ​​are its highest value in first and now used as map 2025 track of how many items you have used To update the specified cons, the use limit should not go more than that use limit for the specific type 510 water solution will also give the solution, so you can see here the result from this study, just product class and laddu per this is The profit is yes value and type 8 and in a given priority queue products and it is like decreasing order of values ​​will decide which means the basis is like decreasing order of values ​​will decide which means the basis is like decreasing order of values ​​will decide which means the basis of maths basically maximum value will keep on top Android operating near by values ​​and veer Android operating near by values ​​and veer Android operating near by values ​​and veer and creating the Product Clear Write Values ​​and Labels Adventures of the Rings Values ​​and Labels Adventures of the Rings Values ​​and Labels Adventures of the Rings Product * Priority Q Offer Means It Product * Priority Q Offer Means It Product * Priority Q Offer Means It Well and the Product Into R Priority Q and Fear After Death Will Create Hes Map and Waste To Organize 1205 Wild Condition Hear Where Is Food Village and Norms Wanted Maximum Items Which Can Find His Nerves And Misery Items For Example Research And Prosperity Fortune Should Be Tamed Basically They Will Katra To Find The Products In Priority Q Software Will Keep All In The Priority Product Which Gives Team The Highest Value Product Here And You Will Check In the map has not had any entry for the product which has been used in will just edit the result and will adv1 entry into river map life easier to have used one product a for the time basically and will increase it is because now you have used Actually the evening cement high heels life you already have time entry into them appraised you want to make and that is class 10th use limit is given to us swim suit be let inside use limit raised and only hui and half inch sir like you all And to our recent and will again put back into map with vansh yaavan more items to use for the time basically 100 villages have one in the map * 100 villages have one in the map * 100 villages have one in the map * data previously used items ki raat saunf example1 through use 5451 interview for type vanshu next time when you using And They Never Seen Before Day You Have To Share With You Like You Can Increase The Tourist And Type Above Time Basically Its Objectives 2 And They Will Keep In Preventing Aay Whenever They Are Using The Product Right And Will Return Our Result Which Is The Maximum Scored a gift from this ride 100% a gift from this ride 100% a gift from this ride 100% approach to a priority queue and map is time basically some solid state called examples were given hair oil pimples and taken so let's run this is do me sun which aware getting character results year the soul will Submit this code 200 Work code Skating accept with the active per cent and seventh 2% and memory or 90% of the time which is pretty good for this is the way you can solve cent and seventh 2% and memory or 90% of the time which is pretty good for this is the way you can solve Rajesh values ​​from labels problem with the Rajesh values ​​from labels problem with the Rajesh values ​​from labels problem with the help of priority one has map showing no Justice Important To You Know Conflict Classification Product Between 2018 Have Two Powder Objects For The Product * Powder Objects For The Product * Powder Objects For The Product * Priority Q Opinion 100 And Thank You Can Order Productive One And Wherever You Have A Balanced And You Are Not Used Limit Items You Can Keep Adding In Trading Items Into your results for the score basically 133 approach fennel minister at least solutions in java j2ee technology hand dial 100 concrete you know job interview related material video song torch light pen follow and java j2ee developer and you want to you know preparing for interview channel benefits please to subscribe this channel subscription really helps thanks for watching the video
Largest Values From Labels
armstrong-number
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
Math
Easy
null
1,833
Hello friends, our today's question is maximum ice cream bars. This is a medium level question of ateleed code. In this question, we will be given a variable named Eric Course, inside which we will have values, what will be the cost of ice cream and the second variable will be given to us. Coin We have so many coins, coinc has to buy maximum ice cream and tell them in the return how many maximum ice cream we can buy, then first we will buy the smallest ice cream, so this is our given example, first 13241, we will sort inside it. We will give our cost and we will continue to mine the cost from it one by one. When our coins run out, our course will be more. In case it is more, we will return it to its previous value. And here is our code, inside this, first of all, we have made it short. Our course which we did by checking the coin, if it is small, then in case we called ice cream, which is ours, we will return the count of the cream, we will adrevise, we will increase the count, someone will mine it, this was our code of its time complexity. If you are talking then our time complexity will be: Hey sorting time complexity will be: Hey sorting time complexity will be: Hey sorting time is O and people and here the time complexity because it will be N O N and if we talk about total time complexity then it will be O and people.
Maximum Ice Cream Bars
find-the-highest-altitude
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. **Note:** The boy can buy the ice cream bars in any order. Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ You must solve the problem by counting sort. **Example 1:** **Input:** costs = \[1,3,2,4,1\], coins = 7 **Output:** 4 **Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. **Example 2:** **Input:** costs = \[10,6,8,7,7,8\], coins = 5 **Output:** 0 **Explanation:** The boy cannot afford any of the ice cream bars. **Example 3:** **Input:** costs = \[1,6,3,1,2,5\], coins = 20 **Output:** 6 **Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. **Constraints:** * `costs.length == n` * `1 <= n <= 105` * `1 <= costs[i] <= 105` * `1 <= coins <= 108`
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
Array,Prefix Sum
Easy
null
1,660
hey everybody this is Larry this is me doing week four of the uh ni by weekly premium challenge what am I talking about but you know this problem hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem 1660 correct a binary tree a problem that I have not done before so I'm excited to kind of give it a spin I'm still in Hong Kong right now just living life I suppose uh yeah follow me on IG though maybe not today maybe tomorrow uh you have a binary tree with a small def like there is exactly one in red node where it's right child incorrectly points in it okay so there's one note that is wrong is it a binary search tree or just regular binary tree we moove this and R node and every Noe below it how do we know oh how do we not I mean uh oh the same depth okay I was going to say like why like what would be the rule for um not using the one instead or like in this case also the one I suppose um okay this is a medium problem though I struggled a lot with the last medium on the contest so uh I mean it's not so bad I think it's just m I mean it's going to be breaker search I mean I'm thinking I was thinking about using some death for search thing but Breer search makes the most sense because pref search then because they on the same depth and this is very specific for this problem um if they're in the same depth then you visit all the notes on the same or not you visit but you put it on the um on a queue to be visited at the same time right so yeah okay yeah I think that should be good so let's get started just uh do they have unique whatever uh the values are unique so we could hash on the values we can also hash on the Node itself directly but it really doesn't matter I suppose so yeah so scene is a set right and then we can maybe just do seam. add of Q iser than zero uh node is equal to Q right um and then basically just C okay for next node in no left no. right if next node is not none then yeah q. aen uh this isn't quite right yet hang on I know I'm just typing out the what you may say a template code yeah and uh okay yeah if this not no then if not is in scene then that means that uh um that means that this is the bad node right the node is the bad node because that and it is pointing at something that we've already put it into the que um so yeah so that means that um no mean I think this is fine none no that right is none I think that's it right and then we can return uh otherwise do we do any do we have to oh I guess we have to return it uh and I guess we return the rout right like what is from node and to no oh that's just indicating the bad nodes I guess um how does the pointer stuff work maybe I misunderstand um not quite sure let's just do uh at least a print statement right node. Rue P node right something like that too lzy to format it okay so it does know that the two is a prad node so I have to remove this node and every node and no so not just every node below okay um I mean there a couple ways you can do it you just look up the parent which is kind of annoying to set up but not impossible right so uh so yeah so here uh I oh I guess it cannot be root because there's no other node on the same level so then that we node uh parent right then now here parent. left and then here we want and that should be good I mean now that we actually read the problem correctly I've been trying to go too fast lately but uh yeah uh okay oh okay yeah that's F that's true I was trying to remove every child of the parents like I a little bit lazy so I'm wrong about that one but um so yeah um if parent that left you goes to no okay now it should be good I said that like four times so I have I Inspire no confidence but uh but still the idea is right I mean I think that's the um that's one takeway as well uh is that if you structure your code and your ideas in a good general direction you can the modifications are kind of easy which is why maybe I don't pay attention that much but sometimes it bites me in the butt so I don't know what to tell you about that particular part but for this particular problem it yeah uh I think BFS is the way to go for the reason that we mentioned is just that um because the thing about pointing at a note at the same depth is the big one uh yeah um that's all I have for this one I don't really have much to say um much more to say uh this is that first oh sorry bre first search so this is going to be uh all of n or and beinging the number of notes those are all and V plus you could say per se but the number of edges is always going to be two times the number of notes at most um for left and right but this is a tree so actually there's only end noes right n minus one or sorry n minus one edges but there's an extra Edge so there's n edges so this other cases it's going to be all of n or linear time and linear space for the Q and the scene I suppose so yeah uh and in case you're wondering the scene um it hashes based on the you could say it's a reference pointer but technically in Pyon is like an ID um thing but uh but as long as you're giving the same uh reference it'll give you the same uh hash so yeah uh that's all I have for this one let me know what you think stay good stay healthy to mental health I'll see youall later and take care bye-bye
Correct a Binary Tree
thousand-separator
You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this invalid node **and every node underneath it** (minus the node it incorrectly points to)._ **Custom testing:** The test input is read as 3 lines: * `TreeNode root` * `int fromNode` (**not available to** `correctBinaryTree`) * `int toNode` (**not available to** `correctBinaryTree`) After the binary tree rooted at `root` is parsed, the `TreeNode` with value of `fromNode` will have its right child pointer pointing to the `TreeNode` with a value of `toNode`. Then, `root` is passed to `correctBinaryTree`. **Example 1:** **Input:** root = \[1,2,3\], fromNode = 2, toNode = 3 **Output:** \[1,null,3\] **Explanation:** The node with value 2 is invalid, so remove it. **Example 2:** **Input:** root = \[8,3,1,7,null,9,4,2,null,null,null,5,6\], fromNode = 7, toNode = 4 **Output:** \[8,3,1,null,null,9,4,null,null,5,6\] **Explanation:** The node with value 7 is invalid, so remove it and the node underneath it, node 2. **Constraints:** * The number of nodes in the tree is in the range `[3, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `fromNode != toNode` * `fromNode` and `toNode` will exist in the tree and will be on the same depth. * `toNode` is to the **right** of `fromNode`. * `fromNode.right` is `null` in the initial tree from the test data.
Scan from the back of the integer and use dots to connect blocks with length 3 except the last block.
String
Easy
null
147
in this video we will see how to do insertion sort on the elements in a singly linked list so insertion sort is a very natural way of doing a sorting so you have let's say a number of cards let's say you have two four three one so first one is already sorted so you can think of them as a cards having numbers and you have to arrange them in your hand so you will see that four is more than two so it's in correct position then you come here you see that 3 is less than 4 and more than 2 so you put 3 here between 2 and 4 now it becomes 2 3 4 1 then you look at one you see that four is more three is more two is more so one should come here so you put one here now it becomes one two three four so you start from first element in fact second element first is already sorted and if this is current element then before this everything is sorted and you want to put this current at correct position and so after each step we are making progress by one step one more element is sorted so we will do it n times and searching can take o of k times if we are at the kth step so 1 plus 2 plus 3 plus all the way up to n or n minus 1 it doesn't matter so time is of the order of n square and space o of 1 we will just keep track of a few node pointers to keep track of the current node previous node and also uh beginning of the list so how we can do it in the list again it's very simple let's take an example let's say we have 3 2 1 4 and make them a linked list so next of three is 2 1 4 and null and we are given the head pointer so this is already sorted next so we initialize current to this one and previous here previous is null so you can create a dummy node and make its next point to head so that way previous will also be valid always and this will also denote that we have to search after previous so current is sorted so what we do we look at next of current if next of current is more than current so if next is more than current then do nothing we don't have to do anything this is till this point it sorted next of current is also more so till this point it sorted so nothing to be done here just current equal to current next else that is next is less it should be less and not equal to i think the elements are unique so if next is less than current then it means it's not sorted because next should be more so we will find the correct position for next so let me draw in yellow so we have to insert this next at correct position before current because next is less than current so current is more than next so there are a few elements here current is here next is here and next is our current is more than next so we start from here we check if it's more than next we insert before it if it's less than next we look for next one so till these are less than next we keep searching once we find an element which is more than next we insert next before that and what we will need to insert that so there is this element its next is this one so we cast this element and we change this next pointer to point to this n and its next point to this one so if the moment we change this next pointer we lose track of this one that's why we cast it into some temp node and we will see all of this in the code then we can change this to next also some node will be next of next so this now is gone here so this should point here the next of current so current next should be equal to current next and then the next of this one should point to this one so these three pointer exchanges are required and we will call it start because that is the place where search will start so this is the dummy node start and its next is head and we initialize previous to start and current to head and we start searching after previous and once we find it previous is here so till previous uh previous next is less than current next is nothing but the node to be inserted previous equal to previous next so we keep incrementing previous so when previous is here previous next is this one and we are inserting between previous and previous next and once we have inserted we reset previous to beginning so that next time also we search from beginning and not from here so list node start equal to new list node and it's next equal to head also current is initialized to head and previous is initialized to start while current is there if current next so if current next is less than current then only we need to insert so this is the main insertion step in the insertion sort else we don't need to do anything it's already in the correct order so just increment current now let's fill this insertion step this is the main part so we need to find the correct position for this current next so remember that previous is here so we will be comparing always next of previous to this current next and if it's less we keep incrementing and once next of previous is more we know that we need to insert this current next after previous so this thing between previous and previous next we have to insert this current next and now when this loop terminates we have found the correct place for current next which is between previous and previous next so let's do the pointer exchanges so we save this node previous next into a temporary variable because this next we will be updating to current next now we can change this pointer so this previous next is current next and current next should be current next this thing so this now is gone so this current next should be current next that is this comes here and previous next is now next previous next is now the node that we inserted and its next should be the temp whatever was the next of previous and we are done now we will reset the previous to start so that for the next element again it starts from beginning and not that point onwards finally we need to return this new head which is next of start and let's see if we have done everything correctly so this case seems fine and the solution is accepted and if we look at the time taken it's here 16 millisecond that is we are roughly better than 99 percent of all the submissions so we are in great shape now let's do the same thing in java and python java solution is also accepted finally we will do it in python 3. and the python solution is also accepted
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
297
the hacker heap in this video we will look into this problem serialize and deserialize binary tree from lead code the problem is if given a tree we need to serialize the tree into this string and if given a string we need to create a tree and return it back so before we start please like and subscribe to the channel because YouTube won't show it to other people if you didn't like the video so let's look into how actually this works this is actually pretty simple even though it's defined as an hard problem it's pretty straightforward let me explain how to do it so what are the properties of a binary tree in node can have two children left and right or a node can have one child either left or right or it can have no children at all no children that is it's a leaf node so in it can have two children or a node can have left or right or it can be a non load so these are three checks we need to do when we are trying to serialize it so let's look into this example so let's consider this tree which have a couple of children five so if given this read the output should be one two three and coming to four and since there is no right child for two we will pass and null and when it comes to 3 there is no less child for three so we will pass a null and then five the string should be this the output should be this so when you look closely into that did you find anything similar so basically what we are doing is a breadth-first search first we are is a breadth-first search first we are is a breadth-first search first we are going through the root and then its children so basically if a node doesn't have either left or right we are just keeping it as null if you want to look into the pseudocode it would be like up we will take a queue here is this tip whenever you are doing a breadth-first search you are doing a breadth-first search you are doing a breadth-first search always think of a queue because that's how you do a breadth-first search you how you do a breadth-first search you how you do a breadth-first search you keep the nodes and then the tail nodes and then there chilling out so you will get the list in order so we will take queue and we will push the root into Q so we will loop that queue while the queue is not empty what we will do we will pop the node pop we will name it as like current node and we will see if it has any children so if it has a left child and it doesn't have a right child we will push the left child value and for the right shell we will push now so that's how we do it and we want to continue this loop or until the queue is empty so we will have an inner loop where we will check the queue size so for each level we will have that node so when it comes here when it initially comes here it is at a level-one so it will have one node and level-one so it will have one node and level-one so it will have one node and we will look through all the nodes in that level and then push the nodes later on so when it comes to level 2 we will have two nodes and when it comes to level 3 we will have two nodes so that we know they are at what level and we know how many elements should be there in that level in the first level there is only one element in the second level there are two elements and in third level we need to have four elements but since there are only two we know that we need to add null value so let's go back and fill up this serialize function so now I'm here back at a late code so the serialize function as we discussed we will have AQ define which will take as a three node list as I said we will offer the root into this while queue is empty what we need to do is we'll get the size of the cube int size physical to Q dot size so we got the size now we will we have to append all the nodes in the particular level in order so I will look through all the nodes in that particular level Halas and the size plus every time I will pop a node which is a current node Q dot poll that will give me the current node so now what we need to do if the current node is equal to null as we discussed so we also need to have like a string builder which we will append to that P dot append off now my comma else what we need to do we need to push the left and right node to the queue first we need to append the value append off dot Val plus the same thing come up and we need to push it to the queue the current node dot left and right that's it so once we are out of this so we just need to return that string as V dot to string but look at this we are adding a comma at the end so the last element would have a comma so we need to remove that so we would set the size dot set lint off as V dot length minus 1 dot 2 string that is it so now we will see how to deserialize a given string so for this utilization you'll be given a string like this 1 2 3 4 null comma 5 and we need to generate a tree like this 1 4 &amp; 5 generate a tree like this 1 4 &amp; 5 generate a tree like this 1 4 &amp; 5 basically these two will be null the right child for 2 and left jail for 3 are basically null so how do we do that so given a string the first step the step 1 is to split the string so we do it by a start split of comma so that will give you an array like this one two three four null and five so now we got this array how to do it so we know the first element in the array is the root so what we do we will create the node and set it as a root so tree node root is equal to new tree node and past the value one basically s of zero so now we got the new similar to the last problem we will define a queue and put this root node first and we will do the same thing but this time we will be inserting at different levels how do we do that let me explain the algorithm a little better so now we have this array we just talked this is the root node that's another Q will have the root node one right now similar to the last time while Q not empty so we already got the root node one so we got the tree node now we need to insert the rest of the nodes so now what you do is I will loop through from the first element since we already had the root element so index I is equal to 1 I less than length I plus what I would do is pop the current element let's say it as a parent and we will pop it out from the QQ dot pop so now this is gone what we will do is s of I not equal to null we need to add that element first to the parent element as a left child so what we do like we will create a tree node new node tree node with a safai and parent dot left is equal to this new node and we would do increment the I now we got the left child we just need to check the right child if s off I not equal to null we will add it to the tree node and also we need to add to the queue dot add off this node we will create node and where n dot at fair and dot right basically will be this new node and again we will push back to the queue so at this time what we will have is two and three similarly we will come back and pick up two and we will add four as a left child and we will do plus I this time it's null we won't be adding it and then we will pop three since it is null we won't be adding it with the left child and when we do plus I it will go to this last index now it's fie we will add as a fourth child that's it so this two will be gone and we will pop for witch and basically the length of the array is done we won't be doing anything and we will return this root element that's it let's go ahead and cut it out so as I said the first step is to split at comma good now we need to create a tree node root is equal to new remember this is a string so we need to pass it your arse end of s of zero if data is equal to empty string we need to check we need to return null because there won't be a tree at all now we got is here we will create this Q of three node going to list my bad first we'll add this root right he got it here so wall is empty not empty now we need to loop here for I is equal to 1 I less then I start length I click this go now I will pop the parent node if s of I not equal to null what I do is renewed just copy this we left s of hi and I need to add parent daughter left it's equal to left let me let chain so there won't be any confusion that's child u dot add of change already once we are out of here we will increment the I is I'm not equal to null what we will do is we know right child is equal to me they can copy it sorry my bad child that's why I'm giving dot right child that is it and Q dot a hat off watch a so once we are out of this loop let's return the root that's it let's go ahead and run it Ward cannot BT difference okay maybe that's the problem what's this string cannot be converted to bully and did I is equal to this Oh double oh sorry my bad it's a Q dot pole or remove you can use either of it not pop let's move this and try to do this if oh I think since we are adding a space here I think that's the problem I am adding an extra space I believe no comma let me see if it works there you go it worked let's go ahead and submit it and see if it works yeah it worked so what really happened was I give an extra space here when I am yeah extra space here when I try to append this to the stringbuilder that's caused the issue other than that it's good so pretty much this is it thanks for watching I hope I explained it clearly please like and subscribe to this channel hacker keeper I will be posting more code problems jolly little stuff thank you
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
947
Ki Sachin Questions Likh Phanda Medium Bat And Its Most Stones Remove vid0 And Column Soen Vivah Birds Play In The World With A Bunch Of Faults And Mid Point Meghvansh Newly Married Stones Problem And Here Removing The Room With Date Sheet 2018 200 Om Vipal Type Laut This The Amazing 10 Sharing Simro So They Can Move One To The Place And Width Remove One Liners That Som Vihar To Return Largest Possible Number Of But Can Help Only Request Player That If Studio Mind Pants Off White Polling Staff Is Not Advised To 9 4 Picture Something On A live webcast begins you can't stop 1000 white happens that roman's fight little eyes after word well center flight share next oil 2019 option problem is a patriot jhal the lord will find wutz jhal ki lakshmi she has been Prominent academic waterloo ki a jhal jahan case ho ki vipin tha ok so you can plot but president something better without you give ki shiromani ka bhagwan loot management ko forced ho half 2014 bhi likh do ki recording in the apps point like button Apne feet ko jhal hua Next Paneer Welcome to Go Loot Muslim's Mathur at game on ab se ka dansh object's mobile Jhal hua blast mein to ki importance ki show Vihar Vriksha Stones with first and best source Simru and Idhar film column we raw ki And bold since loop a lot of mission simro gas on that if this account statement is a secular country interactions were recent ok just fun their forced sonukumar two steps taken that soham important vacancy lekar 0001 president m rosso nuvvu and idli liquid also digit for two Babban is forced to either oppose Vihar-1 movies and there to either oppose Vihar-1 movies and there to either oppose Vihar-1 movies and there is no vacancy but 251 Shukar Maan Tu Sareen SIM Calling Facility Nuvvu Updated On Ek Shaap Main Anil Kumar Jasvir Cutting Ka Number Four In English Vighna Different Reasons Which Can Delete And How Can Way Achieve Possible Number Maximum Volume Maximum Number Of British Rule 10 Different Countries Like Subscribe And Take Good Yes So 19 Minutes Ago That Vax X Pet Or Related To Update Your Links On Or Cut Stress And Country Why Lax You Did S Wallpaper Or Pakistan Loot from this you zoom out to buy a judgment Navodaya Intermediate Verification ki sandesh ko energy mite just a question is that was not reduced from zemtv110 that we developed in delete scientific traditional a hua tha every problem share no not subscribe to ki badripur chirwa mirch and The Side of the White Tiger The Amazing spider-man is subject to that obscene dancing list or that Sudhir Vihar To Make Largest Possible Number And Smooth Secretary Can Be Reduced In The Middle That Effect Tried To Remove 10 Followers 1000 Results Max Plank Whose Noida And Exam Slap From Noida Organizations To Find The Note Which Will Give You That Understanding Ladakh Lake Issue Cricketer Graph To Begusarai When Connected To It ZuluTrade Test Cases Can Predict What Will Happen In The Logic Is A Veteran Actor Who Loot Thanks So How To Select Which One To remove a request from animals do not want to see the land of blood and subscribe to my YouTube channel that this hormone balance qualification on Samsung is based on the condition in porn tasv 15909 friends exposed and of the you say not based on The condition that anything they number 2017 problem you can you are off world 500 index festival of ireland one and a half inch of the island which is neetu's one of the best president camp remove suicide give vote to carry mode on this ireland limit to give way Can Say Thanks For This Point 12th Maths 10th Who Is The Current National Exactly Bluetooth Plot Know How Do You Do Secretary Who Is CB Editing List Abhi Can Have Wave Network Don't Want To Hand Over Love Life To Na Yourself Youtube Live One Mistake Brot Shame To remove with hidden cam intermediate state weather report subscribe now to remove the phone on do loot should make that possible flight fare no you all subscribe and subscribe the Channel subscribe our Lord is provider type were engaged at the metro station 200 test very side contact number of sa actress and tours slum free city it is to ghagra hua hai how to death by students from the first pahal inventive vision election sure that suck oh god this question invest to so they can remove the right pictures president stay In these activities in education providers and on that Vinod Deshwal guava account after size verma a that Navratri rituals to friends if any people till fast 100 other turn on do problem this you sweet children Mohit reduce account temperature is below zero hai avni computer If victim despite 1021 problem video delete is to shampoo member absorbing one drops two more white its side earth the option return to text that this birthday fee no day not cast and scheduled for submitting this form you were past two days after writing on chittor Se Vihar Terminal Dushwaar Hai Loot Pathak Kam Hair Spa Central Tum Kaise Ho Ki Kinnar Remove Chehra Chandramukh Hai Loot Jhali Ki Pyaaz Tomato Motorcycle Hua Hai Om Shivpuri Gwalior Mein Hai Bluetooth And Akash Kushwaha I Want To Make A Gajendra Posted In The Form Of 225 One Line The Effigy Start From The Left And Started Running One By One Will Be Left With The Last Time Like This Hai Re Ke Bachai De Vriksha Something In Between Vaikunth Second And Third Looters Ne Or Se In 20 Minutes Of Work Google 202 Buddha Corner One Cement Chakli Absolutely Laptop Price Churna Picture One By One In An All In One Day Is Either Thank You So You Already Know That In This Particular Ireland One Know Dealer Address All The Best Torch Light Decoration Number Of Ireland Russell Pulation Hai That YouTube Beach Dutt Information Yadav Subscribe 108 Ne Kiya Plate Surat In Computers A Why Not That Under What Will Just For The Top And How To Find The Number Mode On In Remote Definition Of State Water Family Discussion Subscribe Note Remote And Liquid Crystal Subscribe Number 9999 A Person From Water Portal This Is What We Apply For Adult Flu Ward Amazon App A File In The Lap Of Way Not Subscribe To Describe The Order Of The Giver That 501 y1 More Different Directions And Gives Pen Number To Insert How Basically Happened Bhojpuri video editing is becoming the last one from the files, it's node, aap ki kya koi faad aur hui hai liye 589 madhya Jai ​​Hind solution tabs, one more approach, Jai ​​Hind solution tabs, one more approach, Jai ​​Hind solution tabs, one more approach, students union phase, cat, this side, liquid cooling clip, want toe control inflation, tomato Twenty20 till This version of the question on you is all the time is of this What do you can locate the Indian Idol of Lord Make a decision compare to start your browser either has in tamil love you know that you are living in a production Dushman Portal of Duplicate * Is Channel Portal of Duplicate * Is Channel Portal of Duplicate * Is Channel 133 Proof of Birth Can They Convert Into Indirect Version Just But Problem Is I Want Divorce In Between You How To Write Is Din Sadhak Can Be A Powerhouse Loot And Life Never Appeared On ALook Torch Light Bill Hum And Dhan Pane Indicating A New Sanaya 555 Loot Jaan Loot [ Sanaya 555 Loot Jaan Loot [ Sanaya 555 Loot Jaan Loot [ Praise] Has taken Find the Length of the Island of Tasting Labs' Play List A Loot This person has completed in Haryana in the world Soon I have definitely given Sorry on a single line See you find that tennis star somdev intuitive volume off steps and notes in between were hua tha ki but how will create dalenge ayapar ki x y ko doubts aa ki a twitter sonia song tak twitter achcha source it nikla idhar aa aap This link police arrests of single bank fixed ofton in and ok adapter connection old collection of noble definitely rate items from her all this from the best film and best modified and did not have any soul jhalar bhi type of skin kabir team arijit singh latest song And give them in any direction angry birds and came back from head to hearing these apps and liquid list a that last week underrated tasted won ki pm mix hai main abhi khana fab flash lights ko birthday wish tuesday a normal busy aryan set no Better understand what is the problem into a single place of the like subscribe and in the final loot ultimate disgusting thing with friend element thought in between tits set2 represents all kind of his cosmic soul witch usually vikram chauhan and liquid these two ajay ko office loot hai So debt questions and if try slim up last moment 158 ​​so ruk authority can better splendor 158 ​​so ruk authority can better splendor 158 ​​so ruk authority can better splendor fool you should know are next many breeds existed loot hua tha jhal pregnant chaugne waali hai aap sensible ho me ka sex mein loop giver for you
Most Stones Removed with Same Row or Column
online-election
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Array,Hash Table,Binary Search,Design
Medium
1483
95
Hello friends, we are going to talk in today's video, if there is any problem, unique vansh only RTO, then one of my recommendations would be to do female tuning - part-10, female tuning - part-10, female tuning - part-10, you will get very good training, why should you take this problem, you will come to solve this problem. It is very good that we have become with the country. Okay, now let's talk about the problem. What entries do I give you and give you the return of the whole structure and unique vestiges. It is okay that through notes of unique values ​​from one to two. It is notes of unique values ​​from one to two. It is notes of unique values ​​from one to two. It is okay and there are bacterial properties. Any particular note has a property in it, its left rally will be less than the value of the first root note and the life will increase, it will feel the current and all this thing will be subscribed, till then I have given it here. If you want, then you like it very much, if you have a problem with it, then set a reminder for the interview that this five different play list will make your white different way 28 your porn union. Okay, so don't forget to subscribe. If you have a problem, if Otherwise, if you have to tell the numbers, then it should be simple. If you want to give you the numbers only like this, then the numbers are possible, then whatever number you are getting from the formula, then the entry is your debit * and then the entry is your debit * and then the entry is your debit * and relaxation witch one to three, if it is circular difficulty then it will become white for you, see. Where did it come from here? This 12345 is fine, so if you wanted to tell the number, then for updates, you can tell the number of Mangalsutra, but here the number is here, you have to tell the number. Is it okay to give fruits also in possible years, then it is 20. % How it was done One tell the number. Is it okay to give fruits also in possible years, then it is 20. % How it was done One tell the number. Is it okay to give fruits also in possible years, then it is 20. % How it was done One thing is sure that you have to explore the significance, I have to give every note a chance to become a hang out, only then you will be able to block it as a frequent one, this is why first of all I should have done one court, okay one if I If given a chance to build a road, is there any leave given for it? If you move in the other direction, then you can look at the validity of 12345 ticket, travel train and such things. This is the cream, this is what it is in one night, but there can be many meanings here. Gas inside this if you give a chance to become one then her future husband 452 323 ok now in this you need to click here ok subscribe Raghavi chanting penance there is no chance and disgusting so from here and from here you are free You can find it in See this here are the four and five after that this film is a this thing edit this profile thing here I have taken cup of sugar but on one side of this the person from West Indies its quantity will be the reel and here its The file will be fine in life and for that we will have four. Okay, so see when you make it, whenever you make it, there will be two ways of joining it. Episode 345 You have made such a regiment that means when all that is dear to you will become two. It's going to start from, isn't it, you thing, such a bank, this two is okay, so that you, her, I, her body, for the return, then this is done, three, four, for 5 to 10 minutes and these two MP3s, okay, this is five entry, then security that. There is any note on its right which was published in the fort itself but this is next to you, now we will fix it from now on, now it will be in the school but here you will get two structures on irrigated, why one Bar you will keep the to-do why one Bar you will keep the to-do why one Bar you will keep the to-do in the center and but what will you keep slaughter is okay and in this 350 is the same arrangement which we have initially fatal free and 51 this is done then it can be your one share like share 123 in to is piled and 1,000 Kiran Written Two Reigns Wave Raw To and 1,000 Kiran Written Two Reigns Wave Raw To and 1,000 Kiran Written Two Reigns Wave Raw To Family And Request To Subscribe This Is For Your Decisions Next Destination What To Do Apart From Okay Let's Turn Off The Alarm That Brother Now Finally Meet So This Thumb Note Is Being Spread One Two Okay, it is going to be played in right, it was full face, so there is valentine point in the right, now it is one two, it is okay if you change it, then you will do the antioxidant one, here if you keep it one, then the right method will be done, okay and if If you keep two or if you remember, then it is fine if you arrange it in front of the other and if you arrange four similarly then you can arrange it like this and it is the right method, your file is fine and if you keep five first. If you have kept your four in this fort, this is your lamp on the left, then means you are here on what occasion, how many more Indian festivals are there, what are the writing and editing restrictions, how many structures are you going to get from this and your marks, how many units are you getting from here. It is fine in the structure, out of the four, on the left, use all the switches of Pride for all customers. What am I trying to say in this, like if yours, it is free, wash it and you had kept it as one and this is now one* and on the right. What can you keep in the right is now one* and on the right. What can you keep in the right is now one* and on the right. What can you keep in the right issue four and five Misri, the omen is already good, now left, there were two things in the left, first kept 12345, now what will you keep for any thing, you will keep Rafale in this way, file 4th Meghvar's left. For every rally of Right Clear, you will multiply this repeat a little, like for Elephant, the thing is repeated twice, in such a place, you will not write it as economic and here, if you write 2nd, then even after dropping it, you will repeat the thing twice. How did this happen four times, this happened once and this on 3821, if you buy one and a half or two like this, then by paying ₹ 5000, you can see paying ₹ 5000, you can see paying ₹ 5000, you can see how this charger is made. 1234 That is why the comments that miss left or right are repeated every time. So what will we do, we will do it in the entire property sector, we will give every person a chance to become this route and as many possible guests will be able to become in personal shirt that figure like this combination, uncle can get such a combination, Amritsar is this affair, is anyone from there? Okay, so you can do this for ₹ 5, this was this thing here, can do this for ₹ 5, this was this thing here, can do this for ₹ 5, this was this thing here, how about it in the office for ₹ 5, then we will how about it in the office for ₹ 5, then we will how about it in the office for ₹ 5, then we will add, okay, that's why when it was free, one such thing became a fashion in his two years and 15 more It will be like this, that's why it's okay friend, repeat a little like the means, first of all you have to work for the root, seal is seen here, first we are worthy of working for the root, you are the one, then you first check what all he has got in the light, then left it. There is value and for you, family and even and right, now in the last problem I used to do verification on vegetable option, Malik used to wash one thing puts you in the test, first heaven for your form or you become the root in everything. You call for them. Okay, while doing Jaishree, whatever number of codes, whatever orientations are possible in the medical select, this loop thing and with the right maturity, we will meditate on both sides of the animals. Where do you come from? Please use your code. We will take it through the court to know how this thing will be cut in the friend circle, so if you still face a problem at this time, then definitely tell me, I will definitely come and will try to tell you in a better way, if it is okay through the account, then we will leave it. Diabetes did not add much to you but most importantly what should you do? We have not issued article to the prince on April Kaushalya Orange Section 120BC. My tablet has been decided that what is the name of the government. Editor-in-Chief. Understanding half of the ads. If you are according to Editor-in-Chief. Understanding half of the ads. If you are according to Editor-in-Chief. Understanding half of the ads. If you are according to e.g. That your more than one is fine, come and e.g. That your more than one is fine, come and e.g. That your more than one is fine, come and you fold it and divide it, subscribe Alinagar, subscribe for the right, Nazul cream is coming home, operators pomegranate gets activated, then it will not work in Edison left, which is your Rangers subscribe. And if it is about your brightness, then how will it work? Brother, come on stuff, you are the first one to come and go to fiber, that is why I thought that if you want to go to fiber and not to go through water, then you must have become an editor for mixer too. There our channel will come C means like when you like this is our brisbane take so be at the end of all of these so that you become the season here but what happened at the end of yours is at the end there is a null value here from Criminal Rally Okay this is If the phone is for the rights of the child, then what is the last tap? Okay, if it is right for child development, then this tap will move the condition for the contest. So here, what will we do now? We will not keep the channel point here, do the video channel. And the number of tomatoes, possible roots, number of fruits, whatever they are, now we will see, if you are busy like this, if you have only one note for free, then you can do it with your hands, if you I told you that you have baking soda, asked what reminder? Done, this sound is less, just edit it back, okay, do it, Hi Dad, how I saw it inside, give everyone a chance to become a guava, like this, 105 What to do, give everyone a chance to become Tiger Woods, oil Africa that we I came like this, I kept hearing it, okay see how if it is consumed in fruit juice then you will worship through two, for that what will happen to you? I - the for that what will happen to you? I - the for that what will happen to you? I - the thing will go up to 151 and the rider vibrations and till the vibrations in these three till hanging, the right's range is regular. From seven to till is fine like if it is broken then what will happen in the left 1782 what will come is fine for 582 now this many surfers will be made in the last, as many surfers will be made in the right then what will Shahrukh Khan do with them first, what will be our route and how many in the last Click here to see if you knew how this is happening, delete it today, when you have it, when you have unbroken police station, when you have route two, then read these two things in your left leg tractor, once, delete one, there is one and there is one. It is okay to erase it once, it is pure and once, what is this is your left, okay, and at this time, whoever pleases you, erase it once, and erase it once, fiber time, Udayraj Fateh, already in this. What did we see? Envelopes of 5.02 for the first one. 0.2 or cancer Envelopes of 5.02 for the first one. 0.2 or cancer Envelopes of 5.02 for the first one. 0.2 or cancer means you have got four answers. Ways for the one. What was the first answer? Okay, there was arrangement for guava and you did the conference and the second only meeting is your life insurance. You did it like this, when the next time if you want to play your money again, then I pray to you Stuart Broad, then I want you to try again on your money, I have to make a tour here and back on my face and here. Significance for access is dependent on you and it is clear according to all the albums in each left that if you want to do every last date, then I will do it by picking your routes thoroughly, what is there according to the prompt on the routes, like here if you pay attention. Were involved in this loot and keep this palace R right I will give you popular okay so what will you do with this then all the problems here are gone and now what will we do we will keep the route and return back yes I will return the premium okay now like I Talking about the reaction, it is said that see, we got mercy on the solution on the basis, so all of you are getting connected as we were seeing here, tissue was 345 in two of its plates, now we have passed like this, so it is okay, I will break it. How fist abs sacrifice will come and break the record the next day, then all its cosmetics are different, this is the richest year of disturbance, I would definitely like to comment once, you have this thing, you will make some things a topic and yours, you can see for all. You are going to follow this chord, so if you see something, if you write it down logically for a copy, then you are going to have this tension forever, I am adopting this knowledge, normal, you will remember it for a long time. It will remain and you will get a lot of benefits from the Internet. Video: You have to write this directly. Video: You have to write this directly. Video: You have to write this directly. Similarly, the Internet has to explain to you first in your interview. After that you have to write. So, if you are interested in this and stunning this point then I will tell you a lot. It is going to be more beneficial, friends, I hope you will give me the explanation and vote. If you understand, still you have any kind of problem, then you must tell me in the comment section. I will try to tell it on simple WhatsApp. If you want, please comment on my If you like this video then please like this video and subscribe to the channel. If you have friends then share the YouTube channel with them. Many friends will like to watch this video and see you soon in the next video. Take care by thank you. You
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
1,857
hey everyone today we are going to solve the radical question largest color value in your directed graph which involves finding the largest number of nodes in your path with the same color in your directed graph so in this problem each node in the graph is associated with a color represented by a lowercase letter so like a b a c a and uh so looks like a represents red color and the B represents purple and the C represents um blue so the goal is to find the largest value of color such that there is a path in the graph that contains all nodes of that color so this means that we want to find the highest frequency of a color in any pass in the graph that visits all nodes of that corrupt for example if the graph contains nodes with colors like a b and c and there is a path like a zero two three four so in this pass we can find the three a right so index 0 index 2 and the index four right and then one blue I think X3 so in this case um a is a like a highest frequency of the colors so that's why in this case output is 3. before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example so to solve a discussion now so we will use like a breast first search to Traverse the graph and to keep the data we use like a 2d array so this is a 2d dynamic programming so why do we use a 2d array so actually we have to keep track of two datas so one is a current position and uh the other is a number of colors so that means so if we uh index 2 so value two so how many num how many each color we have so far like a four red or purple or blue so that's why we have to keep track of two datas so that's why we use like a 2d array and uh so for 2D array um so this question um in this question uh so each English letter represents uh like some colors so potentially we have like a 26 colors from A to Z right so that's why um this length of row should be 26 because of a space program on the screen let me write down until C so usually 2z so basically we iterate through all vertex like one by one and we start from zero because any in this question uh any vertex don't go to the robotics so that's why it's good to start from zero and so let's begin first of all um so now we are zero here the robotics so current color is a right so which is red in this case update 0 to 1. and then take the neighbor node so let's go to one so let's take this bus when we need at vertex one so first of all compare each color with corresponding previous vertex color so that means zero one passes 0 1 plus 0 1 and 1 2 passes zero two so first of all we'll check the one zero versus zero so zero is one so one zero is zero so one is a bigger than zero in that case update this one to one zero like this so one and then take one but they are same so we don't do anything and check the one two buses still two so they are same we don't do anything and the check until Z so in the end we get the one zero until Z and then um next we try to move buttocks from one buttocks one to somewhere so but before that um don't forget the current color so current color is a purple so popular is a one so B so in this case up to date one and then um try to move somewhere but there's no but it's from uh index in about X1 so we finished robusting for this bus so okay so far so what does this numbers means that means so if we uh index one we have um one color for it and then one color for purple so let's check for this bus one left color one purple color so that's why our so when we see the these 2D metrics so it's easy to understand like uh when we after one so red is one proper is one so okay oh oops let's move this bus so we already added the last one so move two so we do the same thing again compare each color at two with a corresponding color so in this case one bus is zero so one is a great thousand they're also up to date two zero two one and compare two and plus as still one but they are saying we don't do anything so 2 and 0 2 they are saying we don't do anything until Z so in the end we so at the Row 2 at 2 so we get like a one zero one two Z and then again uh check enabling so we have so three so that's why uh there are paths to go then so let's move from two to three but before that don't forget uh the current color so current color is red so 2 0 outputate two zero to two so okay uh before we move to three so let's check so if we are about X2 so there is a path only from zero so this pass has two little colors so that's why two zero is a two and the other color should be zero right so looks good so let's move three again uh compare each color with a like a previous vertex two in this case two so um compare three zero versus two zero so two is a greater than zero so update three zero with these two so two and the other colors should be zero so we don't update anything until Z and then again take a neighboring we have Vertex 4 from C so let's move but uh so again before move to from three to four don't forget other current color so color is uh blue so update 3 to with one so when we are at vertex 3 so we have two that color and one blue color so let me change the color so let's so this bus we have a red two red color and one blue color yeah it looks good so let's move to four again we do the same thing compare each color with like a previous um and 2 is a greater than zero so update two and uh so four one passer three one zero we don't do anything and then four two passes three two so the previous color is blue so that's why uh we have a one blue so one is a greater than zero so update this zero to one and the other color should be zero right so and then um next try to move from four to somewhere but before that don't forget the current error red so for zero update four zero two three right so when we are in the butt X4 so yeah this bus we have three car uh three let and one blue three Nets and one blue and then I'll try to move somewhere but there is no pass then also we finish traversing and uh after that um take the max number so this one so that's why um we should return three in this case yeah so that is our main idea to solve this question I think uh this program is quite wrong so I try to explain a little by little and as simple as possible so yeah with that being said let's get into the code okay so let's write a code first of all um create a direct graph with other Json list so graph equal default addict and at least and create a in degree equal um initialized with zero multiply length of um colors so in degree e in the degree of vertex is the number of xg's going to the vertex yeah so we call it in degree itself for H in edges so if at the 0 equal H one so this is a outer degree and this is a in degree so out degree and in degree are equal in that case it's a circle so in that in the case just return minus one if not the case add a graph so key should be in outer degree so zero and uh values should be in degree so h and one so that means from this vertex uh going to this vertex and then count uh in number of in degree so in the query and the key should be H and the one plus equal one after that so we talk about the graph with a breast for such so we use a DQ so Q equal KQ and the greater list I for I in length and the length of Kara and if in degree current position equals zero so why we check zero here so because if in degree of vertex is zero that means uh we don't have like a we don't need a any prerequisite vertex that needs to be visited first so this means this vertex can be like a fast vertex to drop us a graph so by starting place for such from these nodes with zero in degree we ensure that we are starting from the root of the graph and visit all nodes in valid order so that's why we check here and then after that create a DP list equal so as I explained earlier zero multiply 26 because uh there are 26 alphabet in the world so that's why for underscore in Orange and ranks of arrows so yeah I bought other piece here and then um initializer like a Max color equals zero this is a return value and then starts traversing while Q and the first of all um part six equal Q dot pop left so take the first vertex from Q and then get the current color so color equal so to get the current color I use a ASCII value so Ord in the Karas and the current politics minus ORD and the a so what I'm doing here is that so I'm not sure exact ASCII code but if ASCII value of a is 100 so B should be 101 and the C should be 102 and the D should be 103 something like that so if I subtract a value of a from current color so every time we get direct correct number so that's why uh I subtract a from current a color and then so as I explained earlier before we move to um azerobatics don't forget so don't forget uh to update the uh 2D Matrix so vertex and uh Cara plus equal one and then take the max color equal Max color should be current Max color versus DB and the bar ticks and the color so after that check the neighbor buttocks so for neighbor in graph in the current vertex so every time we take the neighbor robotics now first of all add minus one to uh in degree so neighbor minus equal one after that as I explained earlier uh check the each color already presented by uh like an English lower character in lens and the 26 and the DP and then never in the character equal Max and I want the same thing this one passes um the other is DB vertex and C so this is like a previous vertex and this is a like a current vertex and uh if a previous vertex has a bigger number update current position with a previous number and then oops after that if in degree and the neighbor equals zero in the case that can be this current vertex can be like a start startling point to two of us like a father so that's why add current neighbor then finish your best for such after that check any and E in degree in that case we should be down -1 in that case we should be down -1 in that case we should be down -1 so this line of code is checking whether there are any remaining vertex with non-zero in degree after traversing the non-zero in degree after traversing the non-zero in degree after traversing the graph if there are any it means that there must be at least one Circle in the graph because of those but vertices have like incoming edges that cannot be resolved so that's why we should return -1 so that's why we should return -1 so that's why we should return -1 so indicate that there is no path that contains all nodes of a single color and then um if not the case just return Max color yeah so that's it let me submit it sorry uh this program should be inside of this for Loop so like this then so let me submit it yeah looks good in the time complexity of this solution should be order of B plus e so V is the number of vertex and the E is the number of edges in the graph so this is because we troubles the graph using a press first search visiting each vertex and each edges only once so space complexity should be order of V multiply K plus e so B is a number of vertex in the graph so K is the number of possible colors 26 in this case and the E is the number of edges in the graph so this is because we create a 2d metrics for dynamic programming so that is a v multiplier okay so to store the count of each color at each node and then we create a Json list to represent the edges of the graph which take up order of E space and also we use a DQ implementables for such algorithm which can take up to order of B space in the worst case if graph is a like a straight line 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
Largest Color Value in a Directed Graph
largest-color-value-in-a-directed-graph
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`. A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path. Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_. **Example 1:** **Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\] **Output:** 3 **Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`. **Example 2:** **Input:** colors = "a ", edges = \[\[0,0\]\] **Output:** -1 **Explanation:** There is a cycle from 0 to 0. **Constraints:** * `n == colors.length` * `m == edges.length` * `1 <= n <= 105` * `0 <= m <= 105` * `colors` consists of lowercase English letters. * `0 <= aj, bj < n`
null
null
Hard
null
86
welcome ladies and gentlemen boys and girls today i want to solve another problem which is partition list so basically this is the best problem it gets like from my side okay let's see what the question is saying like we given the head of a league list and a value x partition it's just that all nodes less than x comes before the node greater than or equal to x okay so what is saying like we are given something x so s can be any value is over here 3 so what we have to do we have to put less than 3 less than three over here and greater than three over here okay so i hope this thing makes some sense to you guys like what the question is saying okay so let's just look at over here like uh how we're gonna do this so i will just take uh okay instead of taking to the whiteboard should i take you to the right way i will take you to the whiteboard okay so let me it is everything from over here and here we go let me gentlemen so what i will do i will just first of all create two uh two dummy node okay dummy list so i will call it beforehand and after head okay so beforehand means like the value less than x will attach on this dummy list okay and initially it's value zero so i will say this value zero and after has a means the value greater than or equal to x will come over here on this list okay and then we will join them together okay all right so let me just take you sorry let me just take that following example we have something like one four three two five two we have one four three two five two so i will do it over here we have one four three two five two okay so like this so they're pointing my mistake i just drew it very bad so okay let me just erase it and i will do it good for you only for you guys so make sure to hit and like this video i'm just doing only for you here we go ladies and gentlemen so okay i just draw it so we have something like this okay and we have to put it over here and our x is three so it will like to uh the value before the three will come on the beforehand so this before and a value after the three will come over here after the three or equals to three will come over here on the after so i will use two pointer uh before and after okay so i will just probably before and after so the people pointer will check so it will check if my head value is less than x then what i will do i will point it over here i will point to my over here so in this one is less than three so it will come over here it will come over now on this one i will check is less than three it will say no is greater than three so what will happen i will use my after pointer and it will come over here on my after head okay similarly on this one i will check is it uh greater than three or equal to three it will say it is equal to three so similarly i will attach over here now on this one it will check it is greater than three or equals two people say neither is greater than neither equal equals it is less than three so what will happen i will add to my before head over here are you using my before pointer okay on in this one i will check is it less than three it will say no it is greater than three so what will happen i will add it over here on my after hand now on this one i will check is it greater than or equal to three it will say no it is neither greater than three or nine it neither equals to three it is less than three so what will happen i will attach over here okay so we just uh just completely traverse our original linked list so what will happen it look my head my original hand will point to the null once my original head points to that and so what i will do i will say okay so it means we just done it then i will make i will say my after dot next is my after pointer my after dot next points to null okay now we have to join them together now we have to join beforehand and after that together okay then what i will do let me just let me zoom it out to get some more extra space okay so now guys what i will do i'll just simply say do one thing attached to my before uh dot next over here so my before note next will come like something like one two and it will attach this one aft after the head after hair after head dot next why because initially we have zero so i don't want zero i want from the four so it will come something like four three five and finally none so that's our oh that's our all the uh list like uh like partition is that what we the what the question wants from us so ladies and gentlemen i hope you like this idea may this give you some i like how we're going to show this because this is a very easy question believe me it's very easy code very easy to do so let me just move it over there okay so you will definitely go to understand believe me you'll definitely understand so list no i will say what i will say beforehand so i'm creating my dummy list over here so is the new list node initially value i will give it 0 because i love to give zero okay and list note before will be our uh beforehand okay because it's a pointer before the pointer okay and it's pointing to the beforehand okay it's like initially at over there now we get list note after head is the new list no initial value zero and my after is after i will get an after pointer and after point is initially at after head after is at my after head okay so i hope this thing makes some sense to you guys okay so now what i will do in general i will turn up while loop my while loop will run till my head node equals to node so my head does not reach or not once it will then i will simply stop traversing it okay in this one what i will do i will check if my head dot well is less than x if that's so then what i will do i will say before don't next before dot next because you know i have to point before the using before pointer so initially i might before head is at zero so i have to point after it so obviously before dot next because to my head i will put my head value over there and i have to update my before pointer so my now my before pointer will come on my headphone okay before x 2 before so next so i just upgrade over here similarly over here as for the condition if my x is greater than equals to my hair value so i will attach to my after head so i will say else whatever you have to do after go next uh equals to head and update your after as per the above which i told you similarly what will happen initially i might dummy one i will come over on my like it's pointing to the my next one it pointed to my head now i have to update my after pointer so my after is initially at one time so it will come on my head now okay on the new node okay it will come on the new node not head over no after door next okay so i also this thing is very clear okay so finally what last thing we have to do i have to upgrade my head as well because you know every time we have to update you can either update in the using if loop but you know make try to make the shoot as short as possible so it's very helpful to see it's a very good thing okay and finally after coming out of this loop what we have to do i have to simply uh is okay i have to simply say after dot next my after value is null so it will be like once i'm on the end thing i will say my just point my after rule my null okay here we go now what we have to do i have to say my before don't next will be my after head don't next what i'm doing i'm just joining them together so after the month before what next so you know i'm on the before one so attached to the next video online after that my before pointer i test my after hand don't necessarily you know like after i had like what we have over here i will take you to this test case so it means like we are on the uh we are on the over here so i have to attach over here so i use before but next what i have to attach after head value after this value because we don't want zero we want from over here okay that's what i'm doing over here right so i also like this thing with some sense like i cannot best to explain each line of code what we are doing over here and why we are doing it like this that's my main motive is so please like this video please guys okay thank you very much okay so now finally what i have to do i have to return my before hand next before head to next similarly let me stick to the my white board if you look at over here i have to return after this one note this one is we just go to save the list okay this thing will just go to save the list okay so ladies and gentlemen just all the code let me just run this code to see any compilation error do we face so we will get to that okay and here we go we just get something over here okay my spelling mistake b e f o r e b for head darkness so spelling mistakes happen so it's not a big deal engine engineers do a mistake because that's why we are engineers we do mistake we solve the mistakes so cheers to engineers okay so let me just submit score and i will tell you the space complexity and the time complexity and let's see it's accepting all the tests and here we go ladies and gentlemen so it's going very well okay so in this one the time complexity is our big o of n to go n okay because we are just traversing on the original no not original linked list uh iteratively okay we are traversing on our uh iteratively on our original linked list oh because we are changing number of nodes and n number of nodes okay and the space complexity is our bigger one why because we are not using again any extra memory no extra spaces that's why i love linked list people we are dealing with most of the time we are dealing with space complexity because one so thank you ladies and gentlemen for watching this video i hope this thing makes some sense if you still have any doubt just do let me know in the comment section if you still don't understand anything i will suggest you to watch this video again because you will definitely understand and thank you ladies and gentlemen for watching this video i will see you in the next one till then take care bye and i love you guys believe me i love you take care bye
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
718
Hi gas welcome and welcome back tu my channel so today our problem is maximum length of repeated so in this problem statement what have we given here name van and namas tu de rakha hai ok what do we have to do na find the maximum length There is a submerre which is present in both, okay, so let us understand through the example that the problem is exactly ours, after that we will see how we can solve it. Okay, so what have you given us here? Give us two eras. The numbers are kept, you are fine, what do we have to do, we have to see from here and that is of maximum length, so that length has to be given to us after turning. Okay, so here you can have one length also, it can also be of left, three length. It can also be of four length. Okay, so we have to calculate the naximum and give its length. Look, your van is matching, you are matching 3, it means that yours is 3232. You are also a van, you are also a van, it is also of two length, now you will see here, then it is also of three length 3 2 1 3 2 will see here, then it is also of three length 3 2 1 This is of three line, is it of four line, but if not, then what is your maximum? If it is of three length, then you will give that three, what will you do by turning it here? Now how will we solve this problem? Look, our solution here will be based on sliding window, it is okay because this is the one which will give you the most optimized solution. Here you will get the time complexity of M*N, I will complexity of M*N, I will complexity of M*N, I will tell you how it happened and here you will see the space complexity for the first time, you are three, you are one, okay, this is what we have given, what will we do, we will keep 7 here and we will keep all these four here. Van tu three, we will do this in the first step. We have done it. Is he matching here? Is he matching me? We still have zero. Then what will we do in the second step: Van tu three tu what will we do in the second step: Van tu three tu van seven. We will place four here and van one. We will keep you here. We will keep 3 here. We have the right to match. I am doing the match. We did not match anything in the second step too. Then we will go to the third step. 1 2 3 2 1 7 There will be four here, there will be van here, there will be you here. If it is here, it will be one, you have matched the length, right, so far, you have got the length, okay, then we will go to the fourth step, if you are three, you will be 7, here it will be four, here it will be one. Here you will be there, here there will be three, okay is it matching, if not even one is matching, then nothing has matched, now we will go to the step again, okay 1 2 3 21, here there will be 7, here there will be four, here What will be your van here, you will be here, there will be three, is one matching or not, then we will go to step six, van, you are three, you are ok, what will be yours, here, what will be 7, here will be four, here will be van Hoga yahan pe hoga yahan pe haan pe tu yahan pe three yahan pe Tu here van is ok, so 7 here will be four here van, here you are doing 3 line here, is this match happening, are all three matching in this, so what is now in place of van, our maximum is 3. It is done, it is okay, we will move further, we will see till here, it is okay because starting from here, we have seen the light, we will make all the elements overlap till here, we are done till here, now these two are left 1 2 3 2 1 What will we do here? We will keep the three here. We will keep 2 here. Is 147 matching? Is it not matching? Okay, so far our three is the maximum, then we will go to the ninth step. 1 2 3 2 1 Here You will put three here, you here, van here, okay now let's leave it because we started from here, started from its beginning, from here back to its starting, we reached here, starting from the overlapping garden. Now we have come till the initial stage, we have come till its beginning, so it is done, now we will not look further beyond this, whatever we have got now will be our maximum answer, then how will we solve this problem, see, I mean, I told you that in this way. Now you can see how our code will be, what will we do here, we will have to take care of the index in both the tables, okay, so here when there is zero, we are taking four here, we are getting our match done, then here Here we are seeing that our a is 01 when a is taking two elements here so what is our a is three and four is a okay then here you are seeing 0 1 2 when a is So what is this of yours, you are getting three, a is 4, then what are you seeing here, zero van, when you are taking three, here you have become 01234 of four length, then what will happen to you here. It will start from here, okay zero, sorry, zero, van, three, four, what will happen from here, zero, van, three, this is its here from van to 4, its from 1, zero to three, then what is its case 012 34, its 2. If 3 is 4 then what is its 0 1 2 is it ok 3 4 This is zero van tu hai which will be the overlap part ok we will get it matched so this zero van tu three four is its three four Its zero van is zero van ok What will happen here, so now we come, I will show you the code part, after that again I will explain to you how we have done it can happen for you that what you see here, we have Ijj Ka Ise I Kae Ise Ji Ka. Always keep in mind that it is okay to start from where, it may be different in your approach, yours may be different, our approach may be different, it means look, when you have a question about pattern printing, then everyone has a different question. We solve it in different ways, we solve it by applying different conditions, you can do it in this also, it is not necessary that you match our solution, if you match our solution, then I will tell you how we did it. Okay, so look, we have done it here. But how to do those two IGs, how did we create them, what did we do here - starting from N + 1 what did we do here - starting from N + 1 what did we do here - starting from N + 1 and we will take it up to M. Okay, and what will we do with it from zero to less, we will take it up to N and Okay, so what will we do in this, see what looping we have done, let me show you what we will do, see what is its length, I is yours, its is five, okay, both of them are 5, MB is ours, 5 and the end is also our five. Okay, what will we do? We will start from -4. Okay, we will what will we do? We will start from -4. Okay, we will what will we do? We will start from -4. Okay, we will go till our fourth because this is your mines end plus van till the end there will be only four, so it will be four. Okay, mines five plus van will start from mines four, so what about yours? We have taken this from zero till the end i.e. from We have taken this from zero till the end i.e. from We have taken this from zero till the end i.e. from zero till your four. Okay, so your Jab I - 4, what will be yours, zero will be Jab I - 4, what will be yours, zero will be Jab I - 4, what will be yours, zero will be one, you will be three, four will be okay, this will happen, isn't it, all these So what will we do? First check both of them when we add them. We will see whether there are mines or not. Are there mines? There will be mines in this case also. So what will we do in the case of mines? We will not see. Because the index should not be in the minus but when you add these two then it will be four and you will get zero. Okay, in the first case we need only 0 and 4. How to get zero? If we do I + How to get zero? If we do I + How to get zero? If we do I + J then we will get zero. And if we do this then we will get 4, these are the two we wanted, then in the second condition, what did we want, zero one, three four, we wanted right, so we came here again, what will happen to us -3 and this will be ours, what will us -3 and this will be ours, what will us -3 and this will be ours, what will zero van tu Three four will be this then look here I + J, in this case there will be minus, in this look here I + J, in this case there will be minus, in this look here I + J, in this case there will be minus, in this case also there will be minus, then what will happen in this case zero, then what will this be yours, three will be in this case, okay then I. + J What will be yours in this case will be okay then I. + J What will be yours in this case will be okay then I. + J What will be yours in this case will be van So what will be your four in this case will be three four got it and zero van got this is what you wanted na let us see in a second here zero van three four this is what you wanted na this is what you got Okay, so this is the condition we have done here, look, we will start from -1, less till M, we will do start from -1, less till M, we will do start from -1, less till M, we will do I + + count, we will take one and K, we will I + + count, we will take one and K, we will I + + count, we will take one and K, we will start from zero, less than the end, we will take S plus, we will see I + If this take S plus, we will see I + If this take S plus, we will see I + If this is your less, give it zero, then continue. When I + J, give your less greater, When I + J, give your less greater, When I + J, give your less greater, equals, you will be M, then it will be time break. We do not need to look further, that is, we will go till A, so we do not need to look. Na, till here M will go till A, so we will not see, okay, what will happen after that, here you will see again whether I + J is I + J is I + J is matching both in I + K, what if it is matching both in I + K, what if it is matching both in I + K, what if it is matching i.e. the overlapping part. Is i.e. the overlapping part. Is i.e. the overlapping part. Is he matching? Was he matching? Do corn plus and no in maximum account. What do you do? Update the account. Ok then you will be updated here. If your adervise is not matching then the account should start from zero again. If it goes okay, then finally what will you do? Maximum you will return it here. Okay, I hope you have understood the problem. If you liked the video, then please like, share and subscribe. Many people say that if you do not run and show it, then I am also showing by running that it is yours to submit, it is ok actually time, this is why I don't do it.
Maximum Length of Repeated Subarray
maximum-length-of-repeated-subarray
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_. **Example 1:** **Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\] **Output:** 3 **Explanation:** The repeated subarray with maximum length is \[3,2,1\]. **Example 2:** **Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\] **Output:** 5 **Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\]. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 100`
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
Medium
209,2051
303
Hello guys welcome to my video problem in half an hour school principal rickshaw blurred multiple quality basically office let them between the left and right in this slide as an example to one's and supporters 1234 this youth to-do list related to give till very youth to-do list related to give till very youth to-do list related to give till very 153 Subha Dare Things You Have An Inductive Which Is The Activist Arundhati Maurya Three Elements Which Will Be Two Three Inch Plus Form No Answers For Multiple Subscribe Must Subscribe You Will Find The First And Last Over All This When You Will Get Answers To All Of Ooh A Sudden Start B This To Here Chappal Electricity Office And Takshashila Mountain In Recent Years Even Vikram So Let's Observed Across Mister Talented To Beawar Road Turn Off Switch Parts Of The No. 1 Class And Liberation Army Village That's Our Norms Victor Is Dust The Amazing Inside A Word Can Be Used For This Is Used To Make The Summary Of The Chapter To Do The Use Of Which Is The Play List You Can Return Number Dot Big Be Dot Big Guide Plus Loot Question A First Question This point is too difficult for the way you want to know what you want to love you want to take and what you want to do you want to write what you want to include or exclude Element Industries Limited Subscribe Finally Bigg Boss You Answer This Simple And Give You A Ki This letter is given to the students by DC SP DS working ki Surajkund spine and SMS code and see its working on this occasion Sudhir WhatsApp problem all this prostate problem with his approach s every time but if any problem from time complexity while admitting then I will Have to I am fighting over all this element will have to hydrate over all elements ok so let's pray inquiry super career maximum your writing for all elements video prem* and time complexity of video prem* and time complexity of video prem* and time complexity of making and qualities you maximum guided over all the elements from i don't want Difficult Just doing turn off name every time makes it very positive Guddu It's interests of them into one time when you can improve time complexity Improve time for kids basically events to develop It's already sold in the villages located Sudhir Vats I let me clear Radhe- Radhe Restore The I let me clear Radhe- Radhe Restore The I let me clear Radhe- Radhe Restore The Duke 390 Mode Switch To Paani Next Time Aisi 151 Plus To Equal Than To 363 Shyam Time Aisi 16 Plus Ko Difficult And Spontaneous Word And Doing Paper Quilling Assam Artist Ok What Is This Are Meaningless Ko K Swarnim Doing This App Will 10060 Sr. Someone Tell The First In Next End Singer Support Okay By Bigg Boss-1 Plus Singer Support Okay By Bigg Boss-1 Plus Singer Support Okay By Bigg Boss-1 Plus Two Give Me Three Now Taylor Index Of Two Time Singh Including Six Wickets Three Plus Two Plus One Gives Milk That Deep Waters And Such Now In Third In Next Year Singer Sex Tobacco Someone Plus Two Plus Polytechnic He 12012 Help Reduce Knowledge Se Foreskin Mexico Or Not I Want The Time Between The Gaines 12345 Vibrator All This Element And Assam Back Water Into A Busy Schedule Look Pear 100MB Look At The Third And Extended To Forest Index Of Two or Three Listen What is Mean Disruptive Photo Volume My Time Stand Up Till the Up to the Second Value My Support OK But That Want I Want the Center Someone Like You Will Find That This Particular Volume and This Particular Value Print Android Subscribe Distic and Destroy When Man A Lips Middle Verify Happiness-Prosperity Dasham Between Man A Lips Middle Verify Happiness-Prosperity Dasham Between Man A Lips Middle Verify Happiness-Prosperity Dasham Between A Sworn In Gold Loot-Loot A Sworn In Gold Loot-Loot A Sworn In Gold Loot-Loot Third Intake Dasham Appeal 3D Extend OK Next Summary Text Me I Want The Song From The First To The Third And You Will Look At The Summit For The First Liquid 1001 And Orders From Someone To Keep Them In This World Channel Subscribe 10 2010 - 999 Safar Answer World Channel Subscribe 10 2010 - 999 Safar Answer World Channel Subscribe 10 2010 - 999 Safar Answer You Can See But Two Plus Form Is Equal To 9 During Cigarette Co Police Youth Ki Bigg Boss Now This Third In Next What Is A Vast Umpire All list before problems and element stand what you want some of orders for animals what you want you can only marine elements of view after to remove samadhi di now 200 chennai express delink rating system up to third next hair removing them with all the best And You Get You An Answer Receiver Answer OK What Do You Speak Scheduled Casts And Modified Food Little But Another Factor Se Paun Inch 9V Channel Ko Subscribe to subscribe and subscribe the Video then subscribe To My That Tractor Rituals for Advanced Scientific To How To Calculate Appreciates And Sorrow And Simple Person Succulent Samet Yusuf 12356 Question Recirculating At That Time Digits Stand For Others What They Want That To Point Is Equal To Zero Oil The Number Road Price Subscribe School Meeting Ka Tilak Particular Time To What We Will Do Then subscribe and element 66 is oh enemy love sad him cod salary to what will and wish them will play these figures listen for oneplus element training jaswant privacy in secondary 12th part plus two three layer riding on current element with fabric Volume Waste Placement Yourself Improve Traffic Jam Lettuce Element ₹500 And The Current Element ₹500 And The Current Element ₹500 And The Current Element Is Point To You Will Get Five The Value Of The President 300 Five Plus Pimple 285 Rates Will Be Focal Point Its Western And Southern Student Nurses Scientific Noida - One Will Not Exist in this is Scientific Noida - One Will Not Exist in this is Scientific Noida - One Will Not Exist in this is equal to zero is later just give light condition oh that is equal to 100 waste connection shift fennel IEA is just speak volumes of eye - 110 edit ok speak volumes of eye - 110 edit ok speak volumes of eye - 110 edit ok now crotch traffic absolutely low 210 itna bismil va prameya fix are not change This Code For Jab School Commented Last Will Not Take Into What Should We Do To Return More Answer Story Click Subscribe Button On Right Side - - - Click Subscribe Button On Right Side - - - Click Subscribe Button On Right Side - - - 100 Giver If Not Subscribe 200 Grams Post Which Should Work Late Only Front Lagot And See That Sudhir And Now Compiler Expected And Specification A Woman And See What Is The Earth 101 Thing Africa Animation Hua Tha Hai Pimple Aur Laddu Conference Sewerage Working That Checked Shirt United Thank You Will Be Saint And Slim
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
35
hi everyone today we're gonna talk about one more question on binary search so name of the question as you can see is search insert position this question is a standard question and this question is from lead code let's read the question given a sorted array of distinct integers and a Target value return the index if the target is formed if not return the index where it would be if it was in inserted in the order what this means is like for example you have an let's take this example right example number two where you have a sorted array one three five six and the target value is 2. S2 is not present in the array what they want us to do is we want they want us to give us the index where this target could be inserted in the array such that after inserting the target value in the array still needs to be in a sorted order so for example in one three five six if you put the target value 2 should be the second element right because 1 2 3 5 6 will be then assorted array so the index at which this target value needs to be inserted in the array is going to be index number one which will be your output if you look at the another example which is one three five six and the target value is 5 as 5 the target value is already present in the array we have to just return the index at which we found this target value which is index number two zero one two this is the index so as you can see from the sample inputs and outputs there are two things which are clear one is the target value is there we just need to give the index and the index needs to be zero based index meaning that we have to start the indexing from 0 second is if the target value is not present in the array we need to give the index at which this target value can be inserted in the array such that the resultant array still should remain sorted right so these are two things we need we know again in the question they have mentioned that we have to do this using what uh given the time complexity which they are looking at they want a Time complexity of O of login as you know of login is a logarithmic time complexity and the most famous algorithm which takes logarithmic time complexity is binary search so this is a hint for us to you know solve this question using by research so let's see how we can you know manipulate a standard binary search algorithm to solve this question actually employs you know one of the famous observation of binary search which we are going to see through a example let's take an example of an array which is sorted one three four seven nine and let's say we want to uh you know find the target value 8. as you can see 8 is not present in the array let's try to apply a standard binary search on this array and see what we get the index are going to be 0 1 2 3 and 4. as we know low at is the first index is going to be 0 high is going to be 4 middle value can be 0 plus 4 by 2 which is nothing but two so a of mid as compared to your target value right a of mid as you can see a of 2 is nothing but 4 so 4 and 8 so 4 is less than the target value if a of mid is less than the target value we are going to go and search in the this half of your array right so what changes yours your low becomes equal to Mid plus 1 right pyramid is nothing but 2 plus 1 is 3. so now we have low equal to so this is one iteration right low equal to 3 and high is going to be 4. yes now let's move on let's try to find out the middle value here metal is going to be 3 plus 4 Pi 2 which is nothing but 7 by 2 which is equal to 3 okay so two threes are 6 so this is 3. so what is 3 what is a of mid which is your 3 at third index we have number seven so let's compare seven and a Target value which is eight seven and eight if you see what is the uh relation 7 is less than the target value if that's the case what we need to do again your low is equal to Mid Plus 1. right so if low is mid plus 1 initially low value was 3 numbered is equal to 3 so met plus one is nothing but 3 plus 1 which is equal to 4 high is also equal to 4 correct if I have to find out middle of this obviously it's going to be equal to 4 itself y because 4 plus 4 by 2 which is nothing but 8 by 2 which is nothing but 4 correct so what is a of four is nine what is the relation between the middle value and the target value 9 is greater than 8. in this case what we do in a standard binary search high is equal to Mid minus one the value of your high is currently four mid minus 1 is 4 minus 1 which is equal to three so what we are looking at is low equal to 4 and high is pointing to 3. now this is going to this is where a binary search a standard binary search is going to stop why because the condition low less than or equal to high is not satisfied by these values correct and we are going to usually we halt a binary search and we return minus 1 outside the while loop I hope you remember if not you can check out my video about the standard binary search okay so what we're getting here is after you finish this is where you your binary search is going to stop now let's look at these values and let's revisit the array so the array we were started with this one three four seven nine so let's try here one three four seven nine let's write the you know um what to say about the indices which we can have is index 0 1 2 3 and 4. the target value which we were looking at was basically eight correct after the binary search is over right your low is pointing to index number four and you see this flow is pointing to index number four think about this if you have part 2 insert the target value in this sorted array how would your array you know change and it would become 1 3 4 7 after 7 we would have 8 and 9 why because we want to maintain the sorted uh sequence of the array indices would be 0 1 2 3 4 and 5 right 8 would be inserted at index number four correct and if you see somehow your low value after the binary source is over the low index rate the low variable is also having the value 4. can you see this yes so this is what actually happens in a standard binary search you know you do not have to do anything this is one of the observation of a binary search algorithm in the standard binary research algorithm the if you are if the target value is present in your array so obviously you are going to return from mid right wherever you are conditioned your the middle value is equal to the Target value you return the index right which is the index or in which mid value is stored right if the target value is not present and if you finish your binary research right the while loop is over where this condition is no more met what we do is after that whatever where the low index is pointing to is low index is actually pointing to that index where the target value should be inserted in the array such that the array resultant array is in a sorted format right so the answer to our lead code questions we were looking at here this one search insert position would be a standard binary search algorithm as you can see here the only difference is your instead of returning -1 which we your instead of returning -1 which we your instead of returning -1 which we usually do to say that we do not find we have not found the element we are going to return the value low as we saw on the Whiteboard that low is going to store the index where this target value needs to be inserted if this target value is already present in the array as usual whenever this condition is met a of net is equal to Target you can simply return now the standard binary search has a Time complexity of login I have used the iterative version so space complexity is also constant which is O of one so the entire solution has been possible in oauth login time complexity hope this helps let's look at one function you know which has been provided by Java that is called as arrays.binary search like called as arrays.binary search like called as arrays.binary search like similar to your arrays.sort Java similar to your arrays.sort Java similar to your arrays.sort Java provides us some standard functions uh you know which actually has the implementation of binary search and log of n time and that is binary search here you have to as you can see on the screen you basically need to provide your this function with an array of you know integers like me if you want to sort your integer I mean you want to find some Target you know in your integer array and the target value which you're looking at so this is going to you know give you an index which is again zero based right so whenever you have a need like in this question which we just saw where you just want to use a standard binary search and not write the entire code but simply you can use this function straight forward right one uh interesting thing about this function is that if a particular element which you're trying to search okay if it is not present in the array this function is going to return you an index which is negative but more importantly it returns in this particular format it returns in the form format of minus insertion point minus 1. now what is insertion point the insertion point is basically again which we spoke about is the point the index at which this target element would be present if I had to insert that Target value in my sorted array like for example if I have an array like this which is sorted one three four seven nine and I wanted to like we took the same example right on the Whiteboard and if I wanted to you know insert the number eight which is my target value in this uh sorted array 8 would be actually inserted at index number 4 which is after 7 there would be an 8 here right so this particular um if you use arrays.binary search and um if you use arrays.binary search and um if you use arrays.binary search and you know send the element you know your target value as 8 what it is going to do is it is going to send you an index of minus 4 is where actually the 8 should have been inserted in your um and sorted array and minus one so basically 4 becomes insertion point so minus insertion point minus 1 which is equal to minus five so this area is not buying research is going to then you know send you back minus 5. now as you know that whenever an element is not found you know this function Aries or binary search is going to return the negative value secondly there is a standard in which it's going to uh you know written like it's a formula you know which it follows using this formula you can definitely find out the insertion point right for example if I because it's minus insertion point minus 1 if I want to actually find out the index at which I should be inserting this element in my sorted array would be minus whatever index it's returned like for example minus of minus 5 plus basically minus of minus 5 plus 1 which is going to give you basically 4 right let's run this app actually I have already you know ran and got the output here you can see it can be inserted at index number four here you can see two uh you know lines saying the same thing and the reason is what I've done is you know I have also you know written the function search insert which is taking the standard binary search right which we just saw in Elite code uh solution so this is the code which I have written using standard binary search and return low right whatever function whatever value the search insert does is the same value which I can obtain using simple one like just two lines of code like calling you know standard arrays.binary search and then standard arrays.binary search and then standard arrays.binary search and then applying this uh you know addition of one that's all right so you can keep that in mind whenever you have standard binary search uh examples and you not need to write the entire code you can simply use Addis dot binary search similarly if you have a collection and you want to and it's sorted and you want to you know search in that collection again use similar like arrays.binary again use similar like arrays.binary again use similar like arrays.binary search you also have collections.binary search which also collections.binary search which also collections.binary search which also functions in the similar manner hope this helps uh keep practicing and subscribe to my channel bye
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
241
we're going to take a look at a legal problem called different ways to add parentheses so given a string expression of numbers and operators return all possible results from computing all the different possible ways to group numbers and operators together so you might return the answer in any order so you can see here we have an example right so you can see this function that we're going to write it takes a string expression and we want to return it list of integer as a result of how many numbers were right basically like how many uh possible ways to group numbers and operators together right so you can see here one way we can do is basically we group you know the first two numbers right so two one once we get the you know the total value of two minus one we can use that which is one minus one right so at the end we just get the total value of one minus one which is zero right the other way we can do is we can group those two ones together and this will give us zero so two minus zero right two minus the remaining value which is going to be two right so you can see we have two values so we basically try to keep track of all the sum right so we have a zero here we have a two here so at the end we're returning that in a list of integer now you can see we have another complicated example here so you can see we have two times three minus four times five so you can see here one way we can do it is we can first get the sum or the value of this which is 20 right once we get that we can get 3 minus 20 which is negative 17 and then negative 17 times 2 right which is going to be negative 34 right so that's one way we can do it the other way we can do is maybe like we can you know start to group by just this first right which is 20 right and then we can also group those two first so that's 6 minus 20 this will give us 6 minus 20 will be negative 14 right so that's one way we can do it the other way we can do is maybe we can group those two right once we group those two together you can see this minus this will give us negative one right so if we have two times negative one times five right so in this case what's gonna happen is we can group those two together so that will give us negative two times five right or in this case we can also group two times negative five right this will turn into negative five so in this case 2 times negative 5 will also give us negative 10. so that's why you can see we have 2 negative 10 here right it doesn't matter if you group those two together or those two together the end result will give us two negative fives here so and then the other thing we can also group is we can also group by this one right here so let's say we group two times three first which will give us six right so six minus four times five okay and then what else we can do is maybe we can group those two together so that will give us two times five so this will give us ten right and you might also be thinking like okay what if we just group you know like try to group four times five together maybe we have like six minus 20 right but you can see 6 minus 20 we already done it like right here right because you can see here uh in this case 6 2 times 3 is 6 4 times 5 is which is 20 so 6 minus 20 is negative 14. we already done it so we cannot have you know duplicate group together right so in this case it's pretty much we already group those two together and we also have to group those two together so we already done it so we don't have to do the same uh group together right basically we can have the same result value right but we cannot have the same grouping so in this case how come people to solve this problem so let's before let's talk about how we solve this problem let's look at the constraints right so the constraints you can see here the expression.length which is the here the expression.length which is the here the expression.length which is the size of the string is between 1 to 20. and for the string we only have addition subtraction and multiplication we do not have division at all so in this case uh so basically based on the constraints right like there could also be a situation where the expression or the input uh that we have could be for example maybe like just one number right like one right if it's just one then the output should also be one right so that's something that the question didn't really you know that we want to clarify uh before doing this question right if it's just one num if just one value right if there's only one value there's no addition no subtraction at all then we want to return the same value as it is right but in this case we want to return a list of lists of integers so in this case there's gonna be one and let's say input is you know let's say the input is equal to um in this case 2 minus 1 right so the output should just be like 1 right because there's no way that we can group the only way we can group is two minus one right so in this case you can see these are some other examples and now let's take a look at how we can be able to solve this problem so the brute force approach to solve this problem is basically we can travel with all the combinations that we have right we can try with each and every single substring um basically for example in this case let's say we're breaking the string into half right let's say if i group those two strands together right or in this case those elements together and those elements together right and then i basically say this is the group that we have right maybe we can try with this combination and basically add our total value onto like a result list or something right so in this case if we were to dfs down to this path uh what's going to happen is you can see here we have fn right in this case we're going to call this function we want to continue you know try with all the combination for the left substring and we want to try all the combination for the right substring so you can see here we're going down to two so f n2 is basically just two right and for fn uh in this case the function if we call the function for the right substring in this case with one minus one in this case we can continue breaking because you can see there is operator right if there's an operator we can continue to split into half continuously and tap until we only have like just one number or in this case one uh single integer value and now we can basically just like return that integer uh list of integer value for this sub for this string right back to the original or the root function and then in this case you can see one minus one is going to be zero and this is going to be two minus in this case the operator is a minus sign so two minus zero is going to be two right so in this case you can see if we go down to this branch the value will give us two okay if we go down to this branch okay so let's say if we were to go down this branch let's say if i group those two values together and this together right so based on this operator let's split the string into the left half and the right half so it's kind of similar to how we did it in our break problem uh you can see here we basically have two minus one right two minus one will give us one and then in this case for one it's just one right so in this case two minus one is one minus one is zero so in this case this uh this path will give us a zero or in this case because one minus one is zero right so you can see here we have two combinations so let's say we have another example right so let's say we have two times three minus four times five so in this case what we can do is that we can basically uh group the left substring right and the right substring um together and then basically try to come up with all the you know all the possible combinations we can come up with for each and every single operator like we're trying to uh go down to all the combinations that we can come up with right so you can see for each and every single operator that we have right maybe we can just do like what we say what we exactly did on or break problem which we break the string uh in half right so based on this index right here in this case we know this is the operator we can split the string the left substring and as well as the right substring and then what we can do is that we can basically try to calculate what are the total values of you know of each and every single parentheses that we add right or in this case every time we group a value together like what are some what are the total value right so in this case you can see where we have on the left we have two right so this will this function will return us two and then for our right we have three minus four times five uh in this case you can see for each and we do the same thing for each and every single operator we continue to split the string in half so we have three in this case you can see three this function will return us three and then we group four five together and three individually together right so in this case you can see four times five will give us 20. uh and in this case you can see this will be three minus right because this is a minus symbol uh 20 so 3 minus 20 will give us what will give us uh in this case will give us 17 right and then we can also try with another combination which is three and four together and then five individually so we have a negative one here and a five right so this will give us what so this will give us um negative five right because in this case it's a multiplication symbol so in this case you can see that for this function this will generate negative 17 and negative five right and here it will give us two so what we can do is that we can try with all the combination right so you can see here we one way we can do is we can group two together and then three four together and five or in this case you can see uh we can also group two together and then four five together and three together by itself right so you can see we have two combinations if we group those uh you know those elements together and this element together right so in this case you can see we're going to get 2 times negative 17 and 2 times negative 5 right so you can see we're trying with all the same all each and every single combinations that we can come up with right so in this case uh once we try all the combinations we're going to add it on to the result list that we're going to return right to back to the root level so once we're back to the root level what we're going to do is we're going to try with another combination right maybe this one and this one right here so 2 times 3 which is 6 4 times 5 which is 20. so in this case it's going to be a list right so list of this and that so 6 times 20 which is basically uh in this case is a minus symbol so 6 minus 20 will give us a negative 14 right so in this case what we're going to do is we're going to uh return you know a list of just only negative 14 in it and then we're going to return back to the root level and we're going to add that onto the um right basically added on to the result list so that's that and then we're gonna backtrack and then we're going to try with another combination maybe like for example uh let's say if i want to group those elements together and this element right here right so what's gonna happen then is we're just going to see you can see we continue to break the string down into smaller string right so you can see we have two so we can basically group two together and three four right or we can basically like two three together and four right and then you can see here we have two combinations uh in this or in this yeah in this case we have a list of size of two right because in this case you can see we have two times negative 1 which is going to be negative 2 and we can also have like 6 minus 4 which is going to be 2 positive 2. so we and here you can see it's just going to be 5 right so it's going to be negative 2 times 5 and 2 times 5 so this will give us a negative 10 and positive 10 right so we're just going to return that back to here and we're going to add it on to the result list right so basically you can see this is basically how we solve the problem using brute force and now let's take a look at the code so in this case you can see this is our brute force solution in code right so in this case we have different ways to compute so this is our main function i basically add all of those symbols right all those characters onto the hash set um and then what we do is we also have expression array in this case it's a character array and then we basically convert the expression into a character array right so a lot easier to work with and we're basically passing down like an index right so in this case we're starting like basically our string is between zero to in this case the last character index of the of our uh string right expression right so what we do is we do our perform our dfs function it takes the start and the end and then what we do is we have our result list that we want to return at the end and we iterate from the start to the end and what we can do is that if the current character is the operator right if it's operator then what we can do is that we can just did what we exactly talked about right maybe this is the operator then what we're going to do is we're going to split the l we're going to you know calcula we're going to dfs the left substring and then calculate the right substring just like how we did it in the merge sort uh video right we basically try to break the array down into smaller pieces and then we compute it and then we basically coming back up right so you can see this is sorry this is what we did right we basically have operator set we see that this character is an operator then what we do is we're going to get the left list and the right list right so it's going to be a list of integer and we try with all the combinations that we can do right in this case maybe like for example just like i mentioned before it could be like in this case there is a two and there's a negative two right so maybe like two times five and negative two times five right there's many combinations we want to try to get all the combinations in there right so and then what we do is that let's say if there's a situation where it's just a number for example if it's just a two that we passing in then it's just basically the result the list of this the size of this list is going to be zero right so what we can do is we can basically just convert um the current value right in this case it's just two if it's just two we can just like convert it into a uh you know actual integer value and add it on to the result and then we can just return result at the end right so that's basically what we can do uh let's say if there's a situation where we have a function right let's say let's just call dfs so let's say dfs and let's say this thing is 23 or something right in this case what we know we this is not going to go here right because you in this case uh the string that we're dealing with is 23 so let's say it's index 0 to 2 or something right or the last character let's say is index 1. so in this case we go here we know that in this case this is not an operator right so in this case 23 so this is not operator and this is not operator then there is nothing we added onto the result list so the result list is going to be empty so if it's empty we're just going to convert this string right here into an integer value and add it onto the result right so it's pretty simple and then here basically i call this calculate function basically uh calculates those two values right it will give us the total value of those uh it will give us a total a result value right so in this case based on the operator if it's a multiplication addition subtraction we do what we have to do right so if it's a multiplication we times addition we do plus subtraction we'll do minus in this case it will never go here because like the question states uh it will only have multiplication addition and subtraction right so this is the calculate function and then in this case this is how we basically solve this problem using the uh the brute force approach right so this is how we solve the problem and uh we know that the question says it's going to be between 1 and 20. but let's say in this case the length of expression.length is a lot bigger maybe expression.length is a lot bigger maybe expression.length is a lot bigger maybe like 100 or maybe like a lot more right that in this case how can we able to improve the time complexity we know that it's going to be exponential but how can people to improve further improve the time complexity um in this case let's say if the input scales right what we can do instead is maybe we can like try to cache this right you can see here uh we basically compute four times five multiple times right or in this case four times five multiple times we know it's going to return us list with only 20 in it but let's say if the input is a lot bigger maybe like for example dot right in this case we have to have a lot more branches that we're going to go down to so in this case what we can do is we can cache this um so you can see here we have three minus four it's already computed three minus four is already computed uh we also have let's see here we also have like five already computed right five already computed we also have like two times three also computed right so you can see we have a lot of things duplicate computation right if the input is very large let's say maybe like you know what we can do is that we maybe we can be able to cache this right so what we can do instead is we can basically create this function called get key and we have this cache which uh the key is basically a type string and then the value is a list of integers right because this is what the function is going to return right integer list of integer values right that's what we want to cache so in this case what we're going to do is that for our base case uh we first get our key right which is basically take this star and the end right this is our start to start end right we have put a comma in between uh and then what we do is we basically say that uh we check to see if cache contains this key right if it does we're gonna return that if it doesn't we're gonna compute it and then we're going to save it onto our cache and we're gonna return that computer value
Different Ways to Add Parentheses
different-ways-to-add-parentheses
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**. The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed `104`. **Example 1:** **Input:** expression = "2-1-1 " **Output:** \[0,2\] **Explanation:** ((2-1)-1) = 0 (2-(1-1)) = 2 **Example 2:** **Input:** expression = "2\*3-4\*5 " **Output:** \[-34,-14,-10,-10,10\] **Explanation:** (2\*(3-(4\*5))) = -34 ((2\*3)-(4\*5)) = -14 ((2\*(3-4))\*5) = -10 (2\*((3-4)\*5)) = -10 (((2\*3)-4)\*5) = 10 **Constraints:** * `1 <= expression.length <= 20` * `expression` consists of digits and the operator `'+'`, `'-'`, and `'*'`. * All the integer values in the input expression are in the range `[0, 99]`.
null
Math,String,Dynamic Programming,Recursion,Memoization
Medium
95,224,282,2147,2328
1,464
hey everyone today i'll be going over lead code 1464 maximum product of two elements in an array so given an array of nums uh you want to choose i and j of that array uh return the maximum value of nums at i minus 1 times nums of j minus 1. so very confusing way to word it i'll take a test case here it's very simple to maximize the product of a pair you just find the two biggest ones and multiply them for some weird reason it wants you to do minus one so this would be you can see the two biggest are five and four so five minus one times four minus one which is just you know four times three which is 12. and that's the answer um so really all this problem is find the two biggest uh subtract one from each of them and then return the product so i'm going to do that and let's look at the constraints so there's going to be at least two uh each num is going to be a one or over so let's go uh first for first biggest and let's go second for second biggest and then all we're going to do is we're going to iterate through numbs and basically what we want to do is we want to check if this is the first biggest number so if num is bigger than first uh let's just set both of these so we're gonna go uh first physique and then the first biggest number now becomes the second biggest number so second equals first or actually uh rather we can go first um we also want to check if it's greater than the second biggest uh if it is we can just go second equals number and then from here uh we just do exactly what it wants so first minus one times second one so just the first and second biggest uh multiplied make sure each is minus one uh run this and that'll be correct let's go ahead and submit this and yeah it looks like it's pretty good so yeah like i said it's a very basic problem but yeah i just wanted to simplify it so i hope that helped thank you for watching
Maximum Product of Two Elements in an Array
reduce-array-size-to-the-half
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12. **Example 2:** **Input:** nums = \[1,5,4,5\] **Output:** 16 **Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16. **Example 3:** **Input:** nums = \[3,7\] **Output:** 12 **Constraints:** * `2 <= nums.length <= 500` * `1 <= nums[i] <= 10^3`
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue)
Medium
null
6
Hello Everyone and Welcome Back to My Channel Algorithm Why Today I am Going to Write the Code and Also Explain to You the Algorithm to Solve This Zigzag Conversion Problem Which is There in Lead Quote It is a Medium Level Problem and Has Been Asked in A Number of Companies Which Makes It Important for Interviews So let's start it by taking the name of Shri Krishna, in this question we will be given a string 'S' and an integer ' string 'S' and an integer ' string 'S' and an integer ' Namroz', okay whatever 'S' will be there, we will Namroz', okay whatever 'S' will be there, we will Namroz', okay whatever 'S' will be there, we will divide it in 1000. To make a zigzag pattern, like the letter which is on the zeroth index is placed on the zeroth row, then the letter which is on the first index is placed on the first row, then the one on the second is placed on the second row, then to make a zigzag pattern, the letter which is on the second row is placed on the second row. After the row which is before the second, that is the first row, we will insert the next element in it, okay then for how long will we do this, we will keep going back one by one and how long will we do this until we get to the zeroth row, okay then like Zero eighth row comes, after that we will again start going down words. Okay, in row wise row, down words like from zero to one to two and when we make the opposite pattern of zigzag, that is, diagonal, then we will make it. Row wise we will go up, okay like two to one to zero, we will keep doing this, okay, this will be a very intuitive approach, one, we will take a variable with which we will add it to the string, and to create a row, we will take a string array, okay once dry. Let's run it and see how we will do it. Okay, so first of all we will create four days. Okay, four days. So let's assume that y is the string. Char is mt string. Let's assume for now. Okay, what will we do now? We will take an i variable from which We will do it's current on this string. Okay and what we will do in Nam Rose is first of all we will write a loop to go from top to bottom and then we will write a loop to go from bottom to top. So a simple one There will be a loop which will start from zero and will go till Namroz, let's assume R, it is ok, R is not included, ok because it is 0 1 2 3 and Namroz is four, ok so one from the bottom, sorry, one from top to bottom, one loop. We will write that which will be from row to r and then we will write one for going from bottom to top. Now for going from bottom to top we will write that from where will it start, r is right from -2 like in this case r is right from -2 like in this case r is right from -2 like in this case where is it starting from. It is starting from the second index. We will have to add this letter in the second index row. If it is ok then how is the second index coming? The number of rows is four. The index one before four will be our last index but we will have to add the last index. No, we have to take the one before the last. Okay, so for the one before the last, we will again do one minus. If we had to take the last index, we would have done Namroz's minus. We have to take the one before that, so Namroz is doing minus. Okay. And where will it go from R Might to Row in which zero is again not included because from zero a new pattern is starting from zero, so we will again enter values ​​in it through this loop, enter values ​​in it through this loop, enter values ​​in it through this loop, right? It will be an easy approach, let's try and run it once. First I was here, so I put P here, okay, then I moved ahead, then Y, I put A on the bottom one, okay, then I put W, then P again. So instead of writing this again and again, we can understand it from what is already written. Okay, this four is okay, then we started with number minus two and then went backward in the row, so we have written number two. What was there after A? Then A was put. Okay, this loop ends at L. Now again the loop from zero to Namroz will continue, so from A to A, that loop will end again at A. Okay, then if we make a zigzag one, we will put R and A. Okay, then only AG is played, so for NG, we will run it from zero to Namroz, but if I ends, then we will end that loop also. Okay, so by doing this, our The string that will be formed will be like this, P will be written in the first row, OK, so here P I A is written in the answer, then in the second row, A L S I G will be there, so here P is also written A L S I G, then W A H R. If it remains here also, AHR is written and then PE, then here also PE is written. Okay, so it will be completely like this. If we have to return this answer, then it is quite an intuitive approach, it can be thought of in our own. If you divide it into four rows and we have to add letters, then let's code it. It will be a simple code. Let's start by creating a string array. We will make a string, er, answer, new string, and how many letters will be there in it, okay? Then for int i is equal to g. Now all the elements in this answer are null. Okay, so let's treat it with MT string. Then int a i 0 i is the variable with which we are going to add. On string s, i will always be less than s dot length. Okay, now we write the loop int and int, take the index. Now i is already there, so the index should be less than number and the index will start from zero. Index plus. Ps and index should be less than Namroz and there is another condition that the aa should also be less than s dot length. Ok in this loop here the answer of index e is equal to addot cut aa and aa ko i pe jo character. After adding it, we have to increase aa. Next, we will take another loop int index e equal to nam ro -2 now index should be greater than 0 -2 now index should be greater than 0 -2 now index should be greater than 0 because new pattern will start from row which means repetition of the same pattern will start and Index will be minus in this then give again answer at index plus equal to a dat caret i p ok last what will we do in this answer we will make all the strings in answer as a common string and return int sorry string str in answer res plus equal to st r and then will return re. Let's run it once and see. I missed this i int. Sorry, here also a should be less than the dot length. I sample test cases are being run. Submit and see. Let's take it and submit it successfully but before leaving please don't forget to like the video and subscribe to my channel also tell me my improvement points in the comment section datchi
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
270
okay so lead code practice time easy question closes binary search tree value um if you have um seen the previous video two goals similar as previous videos two goals the first one is to find the solution for this specific problem and put some solid code there and the other one is to see how to solve the problem properly during interview so let's get started the first step is always to clarify the problem with your interview with the interviewer if it is not clear to you and try to fully understand the problem at the same time think about some ash cases which could be pretty special and then after that it is about finding the solution so finding solution parts you will need to find the solution yourself mostly by yourself and communicate with your interviewer run through some uh time space complexity analysis etc and also um and also after the communication with your interviewer um if you're both okay with that uh it is the next step which is doing some solid code so you turn your id into the solid code and um during this time we care about the speed the uh the speed the readability of the code and also the correctness of the code as well and last part is about testing you explain your code using some sample test case do some sanity check and set up some test cases to have enough test coverage so let's take a look at this example so exam questions so given a non-empty so exam questions so given a non-empty so exam questions so given a non-empty binary search tree it give me bst and the target value find the value in the bsd that is closest to the target so given target value is a floating point and you're guaranteed to have only one unique value in the bsd that's closest to the target which means so this one means that the bst is never going to be empty so at least one note okay so having said that the ash case i don't think there is too much of dash case to be fined to be found because um it is guaranteed the tree is not empty so that's only as case i could think about but it's not empty uh based on the notes and thus and then we try to find the solution of the problem so it says it's bst so usually it is binary search um so you start from the root if um the target is smaller than the root then you go to the left branch otherwise you go to the right branch and at the same time you keep track of the closest value using a variable so i would say the runtime is going to be linear to the height of the tree and let's do some solid code for this so for this one we don't need to check whether the root is empty whether it's a non-pointer because it whether it's a non-pointer because it whether it's a non-pointer because it says guaranteed to have a unique value so let's see for okay so um well uh okay so how to do that all right so how to start okay so well um root is not equal to none um the thing here is we are going to put the thing called the let's see closest uh glow this is equal to root dot value and so if um if so we will say i would say closest is equal to um closest so root dot value minus let's say mass. um this one if this one is smaller than mass dot abs closest minus target if the root value is closer then you assign the root value as the closest otherwise we will keep the closest as it is all right other so and then if the target is smaller than root dot value then we are going to the left branch is equal to root the left otherwise uh we are going into the right branch root is equal to the roof top right and finally we just return closest so we're pretty much go complete with this let's take a look um take a look at one example to see how the code is going to work so let's say we have the root we have the tree like this and we are trying to find target as 3.714 we are trying to find target as 3.714 we are trying to find target as 3.714 and the first of all closes is equal to four and they say and then we step into this um while loop so first of all we say so first of all we will see so because it is still the root so we can skip this checking actually uh we will see the target is smaller than the root so it is going to snap into this branch so it has a two uh which is the two the node is two and uh and then we do this uh comparison and we see four is closer than 2.7 four is closer than 2.7 four is closer than 2.7 uh okay so if this one is smaller then you have the roots so if current one is closer then the current closes then you're going to have okay so that's right and now we have 2 3.7 larger than 2 and now we have 2 3.7 larger than 2 and now we have 2 3.7 larger than 2 then we go to this node with number s3 and we see that 3 is still not closer than the current closes which is four um then it closes still four so we return four at this moment so let's do a submission okay so it is good and um and that's it for this coding question so regarding the task is set up uh i would say since the note says and it's definitely not the empty tree i would say some gender tree um it's general bst um so i would say one example like this um would be pretty much pretty enough it would be pretty enough regarding the tax coverage i think because it touches the if and else branch as well um so that's it for this coding question if you like this video please give me a thumb up and thanks for watching
Closest Binary Search Tree Value
closest-binary-search-tree-value
Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286 **Output:** 4 **Example 2:** **Input:** root = \[1\], target = 4.428571 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * `-109 <= target <= 109`
null
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
222,272,783
1,594
hey everybody this is larry this is me going over q3 of the recent weekly contest 207 uh hit the like button to subscribe and join me on discord and let me know what you think about this farm uh maximum non-negative product in the uh maximum non-negative product in the uh maximum non-negative product in the matrix uh so for this problem uh i would recommend so there are a couple of problems in last couple of contests where it's just you know you're given an array instead of a matrix uh and the key thing to notice is that you're going to move right or down so basically you're constructing different paths but different arrays so you so if you haven't if you're unable to solve this i recommend um going over the maximum non-negative product in an array and non-negative product in an array and non-negative product in an array and then understanding that solution and it will help you with the insight for this solution that's how i kind of figured it out um and the short answer for this problem is dynamic programming i actually didn't implement this in a good way i so and i will go over the code in a second so basically the idea is that in each state is well each state would be x y on the coordinates and also um and also whether you need a negative number or not right and once you phrase that it becomes a lot easier to understand and write the recurrence that's how i always try to think about it um but if you watch me stop this live during the contest i actually struggle because i asked the wrong question a little bit um or not i wasn't it wasn't clear in my head what the question was and that's why you know for these kind of problems if you're trying to find figure out the transition you have to ask the solutions very precisely otherwise you're going to get have to mingle with r51s and weird edge cases and weird bass cases and so forth so then so for this one uh and also if i look at it again i might have split into two functions but basically if negative uh this f or if i guess and also i should call this positive and sub-negative that may this positive and sub-negative that may this positive and sub-negative that may have been a little bit better but if the input is positive that means that we want the max positive answer uh from this help uh from this call right uh if negative or and it's actually technically not negative you want to call that because you want to get the max right if negative then we want men uh negative answer from this car i can't spell and min negative answer means the max absolute answer uh so that's kind of why i uh that way and i probably could have simplified swing a bit if i did it that way but um but yeah and then all it is after that it's just going from left to right i think one additional thing to note is that uh because the grid ij can only be up to four uh i mean they don't tell you this you know they asked you to mod uh and also on javascript it may be a little bit weird so this is not true for javascript so it's a little bit weird to be honest but for a lot of other languages notice that it is up to four in my maximum value and that those columns you go to 15 meaning the longest path it's all only going to be about 29 or 30 even and 4 to the 30 is equal to 2 to the 60 and 2 to the 60 of course fits in a 64-bit int 64-bit int 64-bit int right so those are the constraints that i would think about and that's why you can mod it at the very end instead of like modding it progressively which leads to other type of issues as well which in this problem you don't have to think about it luckily but yeah uh so basically once you have these questions uh the transition becomes easier uh for base cases right if you go out of bounds if you want a negative answer you want basically the opposite as a base case so that you never return this answer basically this is a standard value that should never happen so you should return the infinite the positive infinity number which i have this but i should have really rewritten it uh and i have the negative infinity answer instead right so let's actually maybe do a little bit in refactor um so let's return infinite uh and this is this feels a little bit backward because you basically don't want this to ever be to answer your return unless there's no other choice so that's why if you want a negative answer you return to you know the opposite of what you want uh and then the base case the other base case and this is for if you go a bounce right and the other base case is let's say you get to the corner uh if you want them and again this is where we can go back to the question right if we want the negative and the number that the number at the corner is negative then we could just return the number right or zero i suppose actually but uh and i actually double checked during the contest and if you want a positive answer and the grid number is positive then you just return that value uh otherwise again this is the same as this though it's went differently because i'm awkward um but yeah and where i confused a little bit was that i actually initially if you look at me during the contest i solved it like this but now that you have this recurrence this becomes a little bit easier to reason um which is that you know basically if the good answer if the current grid value is negative then we want to swap the what we want right because uh and we actually we should have this doesn't even i don't know i guess i should have uh combined these two things so let's actually do that in retrospect no it's okay but yeah but basically if you want the negative answer as we said then we want the minimum negative answer so we take the min of the current value times uh this function which um which yeah if this is negative then you'll you know basically you want the minimum negative answer from this call right and if it is positive you do the same except for max so that's why the max and the min are different and that's why the confusion here would not be great because this is not what you that's not your input right so you're returning a wrong input so yeah so that's pretty much the transition uh and this transition of going uh bottom and to the right there are a lot of legal problems uh that deals with uh that kind of transition so i definitely recommend you go for it but basically the question you know uh recursion is and dynamic programming and record uh memorization is just rephrasing the question in a way that you can ask a different question by itself which means that okay if i go down and i want a negative value you know how do i go right or like what's the smallest negative value if i go down and what's the smallest negative value when i go to the right and so forth so that's kind of the way that um yeah so that's the kind of the answers that um this would give us so yeah because if uh the new because if this is negative we want our input to be the opposite of whatever so that we kind of keep on uh alternating um yeah uh so then and then at the very end if this is greater than uh well it's close to the infinity my previous infinity value then we return negative one uh for not possible um and then otherwise we just return the answer mod the mod value uh and we kick off in the corner with asking for non-pi or sorry not negative asking for non-pi or sorry not negative asking for non-pi or sorry not negative so positive value um so what is the complexity here right well if you look at this function uh everything we just do a constant amount of time so this is going to be o of one and then now we look at the so work per core is equal to o of one so how many possible inputs are there well there's rows times columns and negative it's two right so uh number of possible cause is equal to uh rows times columns times two for positive and negative so which is equal to over r times c uh or you know or 15 squared in this case so yeah so that means that total work is equal to of r times c and of course um yeah you can actually reduce the space a little bit more by noticing this only goes left uh yeah this only goes right and down uh so you could rewrite it bottoms up with dynamic programming to even reduce the space complexity more uh and the space of course in this case it's just the number of possible cause because we store one cell for each one so yeah so this is time complexity and space complexity it is you go to all of one per core and given that we have all of r times c core uh this is equal to of our c uh space complexity and again you can upsell by converting this these two bottoms up uh and with that you can observe more by uh using the space of optimization technique uh so yeah so i'll link below on that dynamic programming progression uh tutorial that i have um but in terms of explaining this problem that's all i have uh let me know what you think of the like button hit the subscribe button and you can watch me solve the problem live during the contest next after i press the button thank you i'm really behind i'm really slow today oh this is sounds like it's annoying already oh sorry i keep my mind so let's do that okay and now the status only one non-negative so zero is okay so this fits in long by the way maybe you this oh this is annoying so i want this positive answer let's see oh what this is an awkward one uh a lot of potential issues here yes so that doesn't look very bad well this is fine but so i've gotten signs well so that's not that way give me a hundred that's not a hundred my base case no this doesn't make sense okay that's good but that's not so good just so oh makes sense why is that so we're looking for this should be huh oh yeah still no this should be false yeah okay that's just still long though oh and this code should be more right this is it should be just 325. this is true it goes here this is true we're looking for a true negative but this other thing here this is still true don't mess up the signs again so up no this should be that's why oh i think i'm mixing it up okay it was negative one okay and this is fine because i need this to be bigger that's unfortunate so hey uh yeah so that was the end of me solving this from during the contest uh thanks for watching hit the like button hit the subscribe button join me on discord ask me questions let me know how you did how you feel uh and i will see you during the next problem bye-bye
Maximum Non Negative Product in a Matrix
maximum-non-negative-product-in-a-matrix
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
null
Medium
null
338
hey everyone welcome back and let's write some more neat code today so today we're going to be solving a binary question counting bits and this is one of the binary questions from the blind 75 list that we've been tracking in the spreadsheet so we will finally be adding a video solution to this binary problem i'm pretty sure it used to be a medium problem which is why it's highlighted yellow but i think it got changed to an easy problem so the statement is pretty simple we're given an integer n and we want to return an answer array of length n plus one basically a value for every integer in the range from zero all the way up until n so if n happened to be zero then we would just return a single integer if zero happened to be two then we would return three integers for zero one and two and basically for every value in this range zero to n so if n was two we would have three values in that range zero one two for each of these values we want to know what is the number of ones in the binary representation of this particular integer now what's the binary representation of zero it's of course just zero right you could add multiple zeros but it's still going to be zero what's the binary representation of one it's going to be just one right you could have some leading zeros we could have as many as we want but at the end it's just going to end with a single one so there's only one occurrence of the integer one in the binary representation of 0. so far our output is going to look something like 0 1 and then now we just need the number of ones in the binary representation of 2 is going to look like this 1 0. you could have some leading zeros but this is the main part that we're looking at so it just has a single one so then the output is going to be one for that so the array that we would return is going to look something like this zero one now the brute force way to solve this problem is going to be n log n and that solution is going to look something like this let's say we had an arbitrary value such as 2 or maybe even 3 right we know the binary representation of 3 is going to look like 1 right so how are we going to count the number of ones in the binary representation of three well we first let's get the ones place right is this gonna be a one or a zero how can we get that well we can take three mod it by two which is gonna give us one so we have at least one here right so we already looked at this position so what we do is basically cross it out and then we just want to look at the remaining portions now how can we actually do this uh like what kind of operation can we do basically if you take three and divide it by 2 integer division here and most programming languages will do this basically by integer division what that's going to do to this integer is it's basically going to take that ones place and remove it take the remaining bits and then shift it to the right so it basically does exactly what you would want to do and of course what do we get when we take 3 and divide it by 2 integer division is going to give us a 1 so we're basically going to get this and when you look at that yes this is the binary representation of 1 right so now we're gonna take this and mod it by two as well we're taking one modding it by two that's also gonna be a one so far we've counted two different ones for this integer and again we're gonna take this uh this one's place now and chop it off and now we're left with a single zero so if you take one divided by two yes you get zero once we get to zero that's how you know when we're stopping right there's obviously in zero there's no more ones in zero so basically we counted two different ones so that's how we would do it for every particular integer the example i showed right now is three and to get this the time complexity is log n because for any integer n how many times can you divide it by two well of course that's just log base two n now we don't really worry too much about the base usually but yes it's gonna be log n log base two n that's how many times we could divide any particular integer n by two and of course we know we're doing this for a bunch of integers in the range all the way from 0 to n so we're doing this n times doing a log n operation n times is going to be time complexity and log n now there's some repeated work that we can eliminate that you can easily recognize when you actually draw out the bit mappings the binary representations of a bunch of integers and with that repeated work we can actually get a working o of n solution let me show you that right now i just drew out the binary representations from zero all the way up to eight so we know that of course zero has zero ones in the binary representation when you get to one we have one occurrence of one in its binary representation for two we have one for three by looking at this we can see we have two different ones and now when you get to four you really start to notice how we are doing this repeated work notice how for four all the way to seven we have a one in this place right in the most significant place we have a one and notice how the remaining portion of this and then this and this these four are just repeats of the previous four that we calculated right because we're you know we're counting zero adding a one right to four when you add a one you just change it to this from four when we add a two we get this which is basically the binary representation of two itself right and then you get a one zero and then you get a one which is matching over here so now looking at it this is the binary representation of four right there's just a single one in this position so if we wanted to take zero and add four to it we would just to take this position and add a one here right that will take us four positions ahead and if you had a one and you changed this bit to a one we're adding four to it so you can take a one and change it to a five by taking that bit so similarly when we get to four we know that yes we're gonna have one extra one in this position right because we just got this one represents a four this is the most significant bit so far but for the remaining ones all we have to do is take this offset it by four and get here and count how many ones were over here so when we're calculating how many ones for four we're just saying it's one plus the number of bits at position zero how many bits how many ones were in position zero that's our dp so you can see this is a dynamic programming problem because we're using the previous results that we calculated to compute the new results in other words this is going to be 1 plus dp of n minus 4 and actually when you look at this 5 we're also offsetting it by 4 to get these two right because that's what's going to match up with this which is going to tell us how many ones are going to go here right so and clearly we see that's a 1. so here we're going to compute 1 plus again dp of n minus 4. and similarly for here we would say one which is coming from here plus the number of ones in this binary representation which we know we already computed up over here and the answer to that was one so in this position really there's going to be two ones in this binary representation now over here once again we know that there's at least one from here plus how many were in this binary representation we computed that at position three which again is offset by four so this is going to be one plus two which is going to be 3. now you get over here so now we have an even more significant bit last time the most significant bit was in this position and we know that represents the integer 4. now we got an even more significant bit which represents the integer a so we know that this is going to have at least one occurrence of one and then we want to know how many ones are in this binary representation now how are we going to get that in this case you can tell the offset is no longer four because if we do an offset of four we get to the integer four that's not what we're trying to do this binary representation represents the integer zero so in reality we want to take eight offset it by 8 which is going to get us all the way over here and once you do that's when you actually notice the pattern since this is going to be 1 plus dp of n minus 8 you can tell that for each value this is going to be the equation 1 plus dp of n minus a particular integer and that integer is going to be called the offset and the offset is going to be the most significant bit that we have reached so far and what are the most significant bits well the first one is going to be a one the next one is going to be a two the next is going to be a 4 8 16. so basically they're doubling in size every time because we know a bit is just a power of two right that's what binary represents so let's clean this up just a tiny bit so we know that this is kind of our base case zero is going to have zero ones in it now in the next position what's the most significant bit we've reached so far it's in the ones place right so therefore it's going to be a 1. so when we're computing this we're going to compute 1 plus dp of n is always going to be the value we're computing right now so that's going to be a 1 minus 1 because 1 is the most significant bit we've reached so far down here we reached a new significant bit of 2 right because we've gotten to the value 2 so far so for here we're going to say 1 plus dp of n minus two now in this next position again the most significant bit is two right we know that two is a significant bit the next significant bit is going to be four because that's another power of two so three is not a it's still going to use the previous value so from here we're going to compute 1 plus again dp of n minus 2. now once you get here we see that we've reached a new power of 2. so then we're gonna be modifying this to one plus dp of n minus four and then of course when we got to eight we know we reached a new power of two so we were gonna do one plus dp of n minus eight how do you know if you reach a new power of two well you can take the previous power of two for example it was two right let's say the current power of two is two let's say we multiply it by two does that equal the current uh value where if we got to three n equals three we would check does two times two equal three no it does not so we did not reach a new power of two if we got to four two times four that does equal four so now we reached a new power of two and then from four we would do the same thing so four multiplied by two does that equal to seven right let's say we got to seven and we were trying to see is this a power of two no this does not equal seven but once we get to eight then four times two yes that equals eight right so we did reach a new power of 2 and we'd do the exact same thing so the next time we would reach a new power of 2 is would be 8 times 2 equals 16. so next time we reach a 16 that's going to be a new power of 2 and 16 times 2 is 32 etc so that's how it's going to work and once you know this idea it's not super intuitive until you actually kind of draw it out but once you do the code is actually pretty easy to write let me show you how so our dp array is going to be initialized to all zeros and it's going to be length n plus 1 because that's how many we're trying to compute and we're also going to have an answer array which is initially just going to have a single zero in it because we know n is going to be at least zero and then we're going to go through for i in range all the way from one up until n so n plus one this is non-inclusive in so n plus one this is non-inclusive in so n plus one this is non-inclusive in python so we're actually going to be stopping when we go from one all the way up until n and we're going to be keeping track of one more variable the offset aka the highest power of two so far so initially that's gonna be one so before we actually compute the dp or the number of bits in this integer i's binary representation first we're going to check how can we double our offset we're going to check if offset multiplied by two is equal to i the current end that we have just reached if it is then we can set offset equal to i otherwise offset is going to stay the same and then we can actually compute the dp so we're trying to compute dp of i which is basically the number of bits the number of ones in i's binary representation we know that's going to be at least 1 plus dp of i minus the offset and actually one thing i just realized is the dp and the answer array are actually the exact same i don't know why i even created an answer array we can get rid of that so this dp is basically our answer array it's going to give us the number of bits the number of one bits in each integer's binary representation so once we're done with that we can go ahead and just return this dp array so as you can see this is a pretty efficient solution this is the linear time big o of n time and space solution i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191