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 |
---|---|---|---|---|---|---|---|---|
443 | Hello friends, welcome to your day 40 and at the beginning of the challenge, let's go straight to the screen and start today's question. Okay, so the number of today's question is 443. Okay, the name of the question is String Compression String. Okay, so basically what do we have to do in the question, let us understand what the question is saying, first of all, basically what is said in this, I have given you an array in an input, what is given. A B C and C, all this is given in the string, basically so what we have to do is first of all we have to compress it in some form like a is twice like a2, after that b2 and c3 and convert it in this form. We have to put this and this again in the same array like a2 beat and c in the same array and the rest of the terms of this array are not important to us, again put these forms in the same array. And we have to return this part of ours, how big was it, like tooth 4 5 6, we have to return this six, what is the length of our string that was compressed and the written six and the first six characters. Off the input array should be a2 beat and it's okay, like if I look at the next example, it looks something like this, ours, okay, if I look at it, what was here that this is ours and the times are coming now. If one is coming once then we don't have to do anything with it and return it like y but here let's see what is A then T 3 F 5 6 7 8 Na 10 11 12 B if it is B then B up to 12 times is ok I hope so you will imagine that it is ok so now what you have to do is if there was one before A then we can skip one because there was only one time so we don't have to do that, after that B will come. After 12, in which form we have to convert this, in this array further its four terms, tooth 4, where to put them, a bv end to end, whatever terms will be there next, we do not care about them, we just have to tell how much of our array is useful, how much length. So, how will we do it, let them understand, okay, for this, let's go through the white code once and understand it a little more, for this, I will make it. First of all, what is written A B C, okay then? If I compress it, what will be its string? To then C and then Th is fine and the rest of the things do not matter to us and return its length. What is its length? Tooth 4 F. So its length F. Whatever comes, I will return it, then my answer will become. Now I will say this. How will I do this work, it is quite easy, meaning there is no difficulty, if it is very difficult, then we do not have to do anything in this. This question is very easy, it is okay, but the question has been made complicated, but no, it is okay, first of all, I am Weble. I will keep the value of which is okay and I will start here okay means this will be my current right now J and I will go back and check that if the character behind me is not equal I will start from Y and I will check the character behind if not equal means that Character of my is not equal Whose character of a is not equal So what will I do Basically I will make the count a string Answer key which will already have A Okay I will make the answer key which will already be If these two are not equal So I will push the count into the string only if the count is greater than one. Otherwise, before going ahead, I will push the count to one and then B. If this character is the same then what will I do. Look, I wrote E count in this. This is greater than and ok count is greater than and ok if count is greater than one then what will we do we will append count meaning I will add meaning like I make SR then SR plus count now I have this plus equal to count I added plus to SR. Now why add this plus to the count? If greater than and because there will be a currency greater than one, only then we need to tell. For one, we do not need to tell because that means anyway. It seems that if If we don't write anything then do one and after that what will we do which is the character which is current AT plus equal to character of aa and also append it to b and after this it becomes ours when character nut is equal if else character is equal. What to do if the character is equal like the current character will go ahead that means our pointer aa if it is same then just what we have to do is to make the count plus in the whole what is the only thing that is missing here After this, we also have to make the count one, count plus, after doing count plus, count becomes two, after count two, nothing happens here, what is right here, now our i countr or now you see what is the current character. Both are not matching, count is greater than one, yes then what did he say, ATR plus equal to two, put count two, after that make the character plus two, put the character C and what is the value of count, make one so that the next count increases. We went again to c, after going to s, again count plus count value to two, after that came one more time big, now both are equal, back and forth, then those behind made three, now as soon as three are done, same loop. It will end. What do we have to check after the loop ends, meaning we have to keep one condition even after the loop. We have to keep this condition after the loop that even if the loop is left in the last loop, we have to add three here. After adding three, if this string is formed then we will definitely make the answer. Let's do it easily. Now no, I am not going to use string in this, I will use string builder. Look, it is very important to use string builder. Why because when we concatenate a string again and again, in Java, the string in Java is iMusica, it will automatically get deleted, AB CD will become another string, then if I add plus to AB CD, then how will AB be created? First a new CD will be created, then E will be added to it, so to avoid this thing, we use string builder, what happens in it, there is an A B CD, E is added to it, okay, so I hope you understood. Okay, so let's go straight to writing the code, first of all I created a variable count e 0 and to create one of my answers I created a string builder a b equal to new stringing builder and kept it as mt for now After placing it, I added the first character s b dot up case of zero, I added the zero character, now what will I do, I want to keep a count as one, not zero, it is okay, I just told you in d for e int. Now I have to start from one because I have already done the first character, let me do the lesson, after this give me the condition, I's Kiss of My is not equal to whose Cats of I, so I have to do something else. Else, I just have to do the count plus, first write, now see, there are two things, first of all, I have to add the count, but the condition to do the count is if the count is greater than one, then we will add it, only then if the count is greater than one. We will add that, so what I will do if so, I will append the bt append count but what is the count, first is the number, so to convert it into integer form, I will add a mt string along with it. Okay, this is because If there is a number, then I will give it MT string to append with it. After giving MT string, what will I have to do, I will append the A B dot append character which was in caps and then I will count. Because the counting is about to start, now I see what should I do, as I had shown in the case of C, what was happening in the last one and if the last one fell, then what will I do for that too, I will check somewhere, okay, our last. I do n't have a counter, should I do it? Now it's like I have become a stool, but I have a string, where should I put it, there is nothing for it, I will make a small loop, then I am a lesson, a bead string will last till the builder's lathe. Aa pps now I extract the character c e s b e d r aa I have extracted the character after extracting the character where will I place it I will convert the character into a string in our cusp of a e plus this and return s b dot leth ok After returning the add layer and running it, we will see that String can't be converted to character. I would probably say that it's okay, it worked like that because it was a string but only character had to be inserted, it worked anyway. Try submitting. If it gets submitted then we will dry it. It's okay. Let's dry it. Okay, so let's take this part. It's a very easy question. Lately, we had A. Even if we don't make a double first, it will work. A B C. D&D, this is something I took, okay, B C. D&D, this is something I took, okay, B C. D&D, this is something I took, okay, first of all, I created a SB string in SB and added the SB character off as soon as I came inside it. Okay, I did this thing, now our loop starts from here. Don't come here now, are the characters of aa equal? What is the characters of aa equal? What is the characters of aa equal? What is the meaning of characters of aa? If these two are equal, then as soon as we come, the count will become plus. Just the value of count was initially one, now two was initially one, now it has become two, right from here? The count is done, what happened, run the loop again, come up from here, what happened after getting up from here, come up, not equal, if these two are not equal, then the count is greater than one, yes, then a b dot is appended after that. Append the characters of A to Ab, append the characters of A and B, make the count one again, said, make the count one, I came here, I made the count one, okay, looped again, now I came, are both equal, meaning come here. From here, both a and both are equal, so the value of the count is two, again come big, further again, if it is unequal, then count plus again becomes plus, cow becomes cow, then again the value of count has come, now look, the count is unequal. Is the value of 'Is' greater than one? Yes, then add a value of 'Is' greater than one? Yes, then add a value of 'Is' greater than one? Yes, then add a dot to this also. After appending the 'K', append ' dot to this also. After appending the 'K', append ' dot to this also. After appending the 'K', append ' Aa'. After that, change the value of 'Cow' to 'one'. Then again change the Aa'. After that, change the value of 'Cow' to 'one'. Then again change the value of 'Kat' to 'What have I done? It value of 'Kat' to 'What have I done? It value of 'Kat' to 'What have I done? It is okay to do 'one'. Now let's see again, now aa is not is okay to do 'one'. Now let's see again, now aa is not is okay to do 'one'. Now let's see again, now aa is not equal and aa is not equal, that means if these two characters are not equal then the count is also one, then this part will be wrong, append caps off aa, append two and make the count one. Only one count has gone again. Now our aa got up from here and went here means come here, now he has come here. OK, both are checked, both are equal, so change the value of the count to 2. As soon as 2 is done, our loop ends. It is done, after the end of the loop, I came here, the value of count is also one, no, if it is greater than one, then s is the upt bar. Look, this string of ours was completed perfectly, like a was there twice, so a2 should have come, b was thrice. If there was then B, C should have come only once, then C should have come in this type. Now, what do you see, I took out the character A from here and put it in CA, A, something like this, it looked like this, A B C A D something. It looked like this, did I change it? I changed it, I said, I removed A, so I put it, after that what do I have to put here, I have to put 2, so I put 2 here, okay, I kept removing one character at a time and inserted it. Gya put 3 here put C here put D here and put two here and returned its length to T 3 4 5 6 7 8 Whatever our answer is T 3 4 5 6 7 Please return it to Sen. Okay, so I hope you have understood the way I answered this question. The question was quite easy. Okay, so let's meet you guys tomorrow where we will answer the next question. Will be solving till then thank you. If you like the video then like the video and subscribe the channel. See you guys tomorrow. | String Compression | string-compression | Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.
After you are done **modifying the input array,** return _the new length of the array_.
You must write an algorithm that uses only constant extra space.
**Example 1:**
**Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\]
**Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\]
**Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ".
**Example 2:**
**Input:** chars = \[ "a "\]
**Output:** Return 1, and the first character of the input array should be: \[ "a "\]
**Explanation:** The only group is "a ", which remains uncompressed since it's a single character.
**Example 3:**
**Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\]
**Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\].
**Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ".
**Constraints:**
* `1 <= chars.length <= 2000`
* `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol. | How do you know if you are at the end of a consecutive group of characters? | Two Pointers,String | Medium | 38,271,604,1241 |
235 | um hello so today we are going to do this problem lowest common ancestor of binary century which is part of the code daily challenge so we have a bst and we want to find the lowest common ancestor um of two nodes that we get in the input and the lca is just the lowest possible parent of both um and bst is a binary tree where the left side is smaller than the root and the right side is bigger so if you take a look at this example we have two and eight um so the lowest parent they have together is six if we take a look at the second example two and four here two here the lowest parent is 2 right and so you can it can be one of the node itself so that's one thing we can talk from here so how can we solve it um should be pretty easy to think of the first solution which is well we know that if the p value is smaller than the root value or the par node that we are looking at and q value is smaller so both are smaller that means we need to search on the left side right because both are smaller so the parent is either that root or something on the left the parent is definitely on the left side right because it's more both are smaller and by the same um idea if both are bigger that means since this is a bst this is the property of a bsd uh if both are bigger we need to look at the right otherwise that means we found our lca so if it's in between if the node value is in between both um and they are not both smaller and not both bigger that means it's actually in the middle and the first one we found in the middle um that means that's what we are looking for so else we can just return uh root right so that's the main idea go left or right using the bst property um and then if you find the first one where both the value where the root is in between both nodes that means that the lca we are looking for so that's the idea that we are going to implement here so while root we can just check if both are smaller than the value then we need to go left which means we need to assign uh ruda left otherwise if both are bigger so let's just change the sign here and then we need to go right so this is else now otherwise that means we found the first one where the root is right in between both that means it's the lca we are looking for so we need to return it otherwise when we exit and we didn't find it we will have none so we can either return none here or return the root um we didn't find any uh and that's pretty much it you can also do this recursively you just need to handle the base case of fruit equal to none and then you can do the exact same condition except here instead of assigning you can recursively call it on that left or recursively call it or that right um otherwise you can also return in your recursive function um yeah so let's run this make sure it passes test cases okay so it does best test cases now in terms of time complexity this is we are doing only one side right either left go left or go right so that means it's the height of the tree so it's uh off height of the tree in terms of space we are not doing any extra space so it's over one um yeah so that's pretty much it for this problem please like and subscribe and see you on the next one bye | Lowest Common Ancestor of a Binary Search Tree | lowest-common-ancestor-of-a-binary-search-tree | Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.
**Example 2:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[2,1\], p = 2, q = 1
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the BST. | null | Tree,Depth-First Search,Binary Search Tree,Binary Tree | Easy | 236,1190,1780,1790,1816 |
143 | hello everyone it's really good to see you here so today we are going to solve a lead code problem which is reorder list so what we have given a linked list and we have in the form let's suppose l0 l1 till ll then what we have to do is the first element should be l0 then the second element should be ln and then the third element should be l one then the fourth element should be l n minus one so in this way we have to reorder the given list okay so now let's see the approach to solve this so here we have given a list l so what we do we just split this uh list in two different lists so what i mean from this is that this list this is a one list and this is another list so what we do this list remains the same but this list we have to actually reverse it and when we got this l1 and l2 then we have to simply merge it so the first element of l1 then the second element is from l2 then the third element is from l1 then again fourth element is from l2 so if any of the list remains then we just connect it throughout so let's see how we can uh do this so firstly the very first thing which we have to keep in mind is that how can we find this second list or how can we just separate two of this list so what we do we take two pointers slow and fast so the slow pointer uh moves slow and the fast pointer moves fast so if slow moves one step fast moves two steps so in second iteration slow is here and fast is here and after that when slow reach hears fast is pointing to some null value so what we consider that now our slow pointer is here so from this point we have to reverse our linked list so reversing the linked list is a sub problem here so you have to know how to reverse a linked list so if you want to check that also then you can check the link given in the description and now so after reversing this list we got l2s543 and l1 as one two so now what we have what is the task so the task is to merge these two list so first element is this then the second element is this third is this fourth is this and so on so let's try to understand it using the iteration so what we do here let's suppose we are here so now we are going to use four pointers here so h1 is the head of the first linked list this first l1 linked list h2 is the pointer for the second linked list so it is pointing to head of the second linked list then we are taking t1 so t1 is basically head next had h1 next and t2 is basically h2 next so these four pointers we have to use so what we are doing initially is h1 is this one so now h1 next would be h2 and after that what we do h2 should be equal to t1 and after this iteration what we do we just shift t1 here h1 also here h2 here and t2 also here and after that we can see that now our list look like something like this so 1 is pointing to 5 is pointing to 2 and then 2 is pointing to 4 and 4 is pointing to 5 so this is the second iteration so how we are doing is now our h1 is at this place h2 is at this place t1 and t2 so now our h1 next is equal to h2 so 2 is pointing to 4 and after that we can see that now our t1 is pointing to null value so what we do we just come out of the loop and rest of the list is pointing as same so we don't have to do anything and from here we got our reorder list so now let's try to see how we are doing this part of the code so here this one is list reverse so we are taking three pointers previous current and next and then we are just reversing the list so this reverse function actually just reverse a linked list from the given point of node now after that we are taking two pointers slow which is equal to head and fast which is also equal to head and then we are iterating over this till the point fast not equal to null as well as past next not equal to null and after that what we are doing is we are just incrementing our slow to slow next and fast to fast next so this is incremented by one degree and this is incremented by two degrees so that is uh fastest double of slope now what we do we just take three pointers so here head uh h1 which i talk here h1 is same as the head pointer so that's why we are not again uh reassigning it we are just using t1 which is representing head next then h2 which is representing the reverse form of slow so here you can see that this slope is the point from where we have to reverse the list that's why reverse slow will actually give a reversed um list l2 so header 2 is basically representing this list l2 now t2 is representing head to next now what we do we just run a while loop till the point to given not equal to nil and t2 not equal to null so here t1 and t2 are head next and head to next so while this is true what we have to do is firstly we have to make our head next equal to head 2 that is what we are doing here and then head 2 is equal to head so firstly head 2 next equals to t 1 that is this values next is t1 and t1 is here now what we are doing is we are making t1 is equal to t1 next so here t1 goes from this point to this point and before that we are making head equals to t1 that is now firstly our head is here now our head is pointing at this point now what we do we take uh head 2 is equal to t2 so that is now our head firstly our head value is pointing here and head next is pointing here then what we do we make h2 pointing to t2 and then again we are pointing t2 as t2 next so this is what it is written here so since it is a void function we don't have to return it because we are doing all the changes inside the head pointer itself so now let's try to submit this up so this is the solution for the problem pre-order list and if you want to assess pre-order list and if you want to assess pre-order list and if you want to assess the code then you can check the github link given in the description and this is it for this video thanks for watching | Reorder List | reorder-list | You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000` | null | Linked List,Two Pointers,Stack,Recursion | Medium | 2216 |
1,827 | there are some problems where half of the problem or the understanding of the problem is sifting through the information that seems kind of misleading or information that isn't exactly very helpful or not helpful enough to solving the problem and this is kind of one of those problems that i think of so we're given the instructions if you're given an integer rate nums in one operation you choose an element of the array and increment it by one okay and element to the array it kind of makes it sound like you can pick whatever element you want and increment it by one but that is true however we need to think of exactly what the goal is so the goal here is return the minimum number of operations needed to make the array strictly increasing okay so let's take a pause for a second if we boil this down to something much easier than thinking of the whole array and thinking oh we could pick an element and then increment it by one we think of something small well we have value one next to one we just increment the second one by one and we're good to go if we have one two and so on all twos then we just keep incrementing uh the two that comes next to a higher value than the previous value so suppose we have one followed by four twos like this we have one followed by four twos and then we just need to make it strictly increasing what ends up happening is you increase the third two by one and make it three and then of course you need to increase the second two by two to make it four okay and this is really a lot of problems how they're going to be solved is by solving something very small first and paying attention to well i have the rules and i have the goal is the information that i'm given perhaps information that seems or sounds a little bit like i don't really need all that information or it's not very helpful this is kind of one of those problems and how we solve this is first by saying n equals line of nums and then c is 0 that's the counter that we're going to collect we say 4i for i and range n minus 1. if nums of i is greater than or equal to nums of i plus one number of y plus one diff equals absolute value of nums i plus one minus numbers of i minus nums of i okay and what we want to do from here is say okay well now we need to increment uh the number of uh times that we need to add 1 to this particular value to make it bigger right so we say c plus equals diff plus 1 right because if we just add diff it could just it's just the difference it levels it out we need to add 1 to it and then we'll say nums i plus 1 num's i plus 1 plus equals diff plus one right so we replace that value for the value in the array so that we can update the number thereafter we return c run accepted submit outstanding | Minimum Operations to Make the Array Increasing | invalid-tweets | You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`.
* For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`.
Return _the **minimum** number of operations needed to make_ `nums` _**strictly** **increasing**._
An array `nums` is **strictly increasing** if `nums[i] < nums[i+1]` for all `0 <= i < nums.length - 1`. An array of length `1` is trivially strictly increasing.
**Example 1:**
**Input:** nums = \[1,1,1\]
**Output:** 3
**Explanation:** You can do the following operations:
1) Increment nums\[2\], so nums becomes \[1,1,**2**\].
2) Increment nums\[1\], so nums becomes \[1,**2**,2\].
3) Increment nums\[2\], so nums becomes \[1,2,**3**\].
**Example 2:**
**Input:** nums = \[1,5,2,4,1\]
**Output:** 14
**Example 3:**
**Input:** nums = \[8\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 5000`
* `1 <= nums[i] <= 104` | null | Database | Easy | null |
1,239 | everyone with Calvin here so let's discuss about weekly contest 163rd question maximum length of a continent string with unique character so we are given a array of string and then we can cut any of the string inside the array and but we still need to result in a unique character inside the concat string so we need to return the maximum possible length of the concat string itself so first example here so we have three string inside our array so you can see here if you ending concat with ue the concat character will have two character of u which end up is not unit characters anymore for the concat string so it's a possible concat so the possible concat with the longest length here is un concat with IQ or IQ concat with ue so in that case the result will be for the longest khon kaen string and take a look on the second example so see hits AR can be concat occator which result in the length of for CH a and AC T cannot be concatenated since AC already in a CH a also so CH AC T is not a valid concat but C hits a ER s is a valid content so it's become six if we try to con cat CH AR and then ers it's not a phallic on ket because see har already have are inside so we cannot concur with the ers so the longest one is its either's chaa RS or AC te RS which result in six and third example here is we have a to z in one string and basically that's the our maximum answer 26 and we don't have any other starting to con cat anymore yeah so how we going to solve this problem so this is basically a DP problem so the key of the DP here is from previous solve like from previous pick how many character is already inside our concat which here I represent using an integer so integer have 32 bits we just want to represent a 2z is inside our concat string or not so I'm using integer so 36 character can fit into the 32 bits so here the base case is if we already finish concat everything at that case I written 0 because this one it represent when we don't have any array of string then what will be the maximum content so we return 0 in that case and here so this is to calculate current character how many the current string how many character it will used up so here we get the string of current index and then check whether is valid or not why we need to check this just in case if we have a string that say ACA this string itself is already invalid so we cannot merge it with any other string so we will just keep in that case so here we iterate through the string and then here its character I manage it by a so we can fit it into the current used character like is it's a already axis or not is BRD axis or on until is that or the axis or not by offset 26 at most for Z for example and then we use an or operator so when it's not let's say a it's not there yet it's not inside the string then we will the current a we will mark it into the talent use character so we have the current news connector so we just need to find it with the previous concat string with it which is the used character and we check it with current news character if any of the current news character is already being used before means we cannot contain it so first case here is if we decide not to concat it then we just move on to next index and still use the previous use character but if we want to use it there is one condition which we need to make sure our current string is valid itself like there is no such case like ACA and then we need to make sure when the use character before concat with the current news character its result in zero so result in zero here means there is no overlap character between the previous concat and current string so if it's valid then we merge them together using an oar so the next used character will be the previous used character plus star mu scatter and then answer itself will be the current string link plus the next soft so next off will be we increase the index by one and she's the year's character to add up with the current news character so we'll have more character use on our next decision and for the DP itself we started stopped the output based on the key so the key here is the use character itself and what is the current index we explore because it might result in the same number of character being used but it actually being resulted from different string we pick yeah so that's it for this question thank you for watching see you on the next weekly contest | Maximum Length of a Concatenated String with Unique Characters | largest-1-bordered-square | You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[ "un ", "iq ", "ue "\]
**Output:** 4
**Explanation:** All the valid concatenations are:
- " "
- "un "
- "iq "
- "ue "
- "uniq " ( "un " + "iq ")
- "ique " ( "iq " + "ue ")
Maximum length is 4.
**Example 2:**
**Input:** arr = \[ "cha ", "r ", "act ", "ers "\]
**Output:** 6
**Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers ").
**Example 3:**
**Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\]
**Output:** 26
**Explanation:** The only string in arr has all 26 characters.
**Constraints:**
* `1 <= arr.length <= 16`
* `1 <= arr[i].length <= 26`
* `arr[i]` contains only lowercase English letters. | For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1). | Array,Dynamic Programming,Matrix | Medium | null |
300 | Hello everyone welcome to my channel good story with mike so today you are going to do video number 11 of DP concepts okay and before starting some speech you are a very simple statement but very powerful statement do it so hard that everywhere People in your circle should discuss, is n't it? Everyone starts aspiring and everyone starts knowing. It's hard for you to okay your consultancy and willingness. You can achieve your goal. Bill, decide your success. Look, everyone has a goal, they have to achieve, they have to do this in life, they have to do that. You have to do it but how consistent you are, how much match you are ready, you give it, only the give will decide whether you will really get it or not, it will decide whether you will get success or not, hence consistency and hard work. Okay, and let me tell you something. Recently, I have received offers from many educational platforms to collaborate, that is, they want me to create the contents of my channel for them. Okay, but I declined the offer because I am not able to do this. I know that if I create content then they will ask me to create content according to them, which I don't want, okay, I want that whatever comments come, whatever suggestions come, I should create content according to them, okay, so that it becomes easier for you. Not that the content made on the basis of any other platform is fine. You can tell me in the comments whether this decision of mine was right or not. You would know that I am present in all these three places and what we have read so far was given in One Di Beach. We had studied and all the questions were memorized, memorization plus bottom, you all are in agreement, it is okay, we had studied so many questions and all of them from bottom up and memorization are also okay, so what now, we will still study more in this 1db In Longest Increasing Subsequent i.e. L is Longest Increasing Subsequent i.e. L is Longest Increasing Subsequent i.e. L is one of the most important topic and our one of the most famous questions and all its variants, okay, we will make all its variants because it is very important, there are many variations in it, okay we all We will discuss the meaning of Longest Increasing Sub Sequence and what is today's video is on recognition and memorization. In the next video we will learn bottom up, it is better and such and please always remember that I have kept recognition in one video and bottom in a different video. I want to keep it out of the following because I want the entire stress to be on the bottom up. People are scared at the bottom. That's why I make a separate video for the bottom. Okay, if you remain patient, you will definitely do well. Okay, now learn the variants also. It's like this, you have to read a little bit, okay, wait for the variants in this video, after that the variants will also come, today's liquid number is 300, it is medium but it is going to be quite easy, okay, who will make the family method of DP before this today, okay We will make it in a very simple way, we will also see the example of transistor. Okay, so let's move ahead, Amazon Samsung, we have asked this question, many more people must have asked me, I have not mentioned it here yet, the question is very simple, an interior. Is given to you in the name of Return D Length of D Longest Strictly Green Sequence Strictly means it should be exactly increasing, not equal, it is not strictly increasing, right, striking method means it is bigger than this, like you come four six seven this It is strictly increased, it is okay, it should not be equal, so understand from this example what will be the length of the longest increasing sequence. Look here, you must be aware of the meaning of sub sequence, you can also miss any element, like 10 is written after 10. No, left it, wrote 5 3 101, so these are all sequences, ok, the whole Arabic is a sub sequence, ok, miss means you can keep an element or not, like this 1092, a sub sequence, hua ten tu Also, if there is a sub sequence then nine is kept or if these are not kept then you must know the meaning of sub sequence. We have to see the increasing sub sequence, so if we take mother like this then see what is increasing, I am seeing this, 5 after 2. After five, seven, after seven, 101 is visible, what else is visible, 10, after 10, 101 is visible, its link is only two, and what is visible, 101 is visible, after nine, 18 is visible, and so There are many visible but which one is the longest increasing sequence, look, this one is also strictly increasing, no element is equal, all are increasing, the first two are increasing, a question from 5 years, what is its length, do our answer It will be fine, it is clear till now let's take a look at how to solve it from scratch. First of all, we will build the instance. Before that, understand one very basic thing. Whenever it comes to finding out all the sequences, right? So to take out all the coins, we will always do those two things. Why do we do the take and skip thing? Earlier I told you that whenever we have to take out a sub sequence, we take Maa. In this, I have a sub sequence of 10 9 and 53, even though now it is increasing. There is no big sub sequence, you see, nines have been included, we have included take nine, we can also skip them from 105 onwards, this is also a sub sequence, after the sub sequence, whenever there is take one more. There will definitely be a matter of skip, okay by taking and skipping we will get all the sub sequences but here we have to remove them from the sequence but if we want to get the longest increasing sub sequence then we will definitely do these two, okay everyone is our best friend who helps us. There are three diagrams to write the code of Rickson, your theory will also be built from this diagram and you will understand how to approach such questions and whatever the variants of Alice are, the same thing will be applicable in them too. Okay, we will make its tree diagram by applying logic when you know that you are going to add G element, it should be bigger than this, only then it will be increasing, okay, only then you will be able to support it when it is bigger than its previous element. If it is big then which previous element have we taken, this one is right, it is big, it is bigger than three and one because the increasing is going on dividing by A. Now there is no X. If we want to put X in this subsequent and keep increasing. So I need you to assure that my last index is the index of the last element, let's take that P, that is cool b smaller give It should be bigger than the element. It is clear here that we will take the element only when it is long, when it creates an increasing sequence, then only we will take it. Okay, take and skip were there, but when will we take, we will have to pay attention. Only one will become increasing, only then will the element be skipped. So okay but only then we will be able to do take and skip for each index, let's take mother, for this index I am on the index only, so what will happen for this, we can either skip it, if I skip, then see my Increasing is being made, now nothing will come in it is empty, it is still fine and if I have taken it is fine, if I have fixed it, then my sub signal has reached zero. It should be small. Now I have taken zero, so I will write the index of the previous element as -1. write the index of the previous element as -1. write the index of the previous element as -1. Okay, Lord, I will write the previous element as it is not there yet. Okay, so I can take zero. Okay, now let's move ahead. So now see. Pay attention, I have taken the absence zero, so whatever element I take next in the future should be greater than zero, so I call zero as P, this is the element of the previous index, it is okay that I have also taken it, now in the future I Whatever element I will add in all this sequence, it should be big because we want increasing surgical. It is clear till here, so let's move ahead, my index will increase zero one zero three two three index here will flood further but I will not expand it. It will be a very long tree, you can do that yourself, I will spend it with this and you will see it. Okay, now look, the index was here, now here again you have two options, either you can skip it or you can take it. Okay, now see if you have skipped it then see what was your sub sequence already. If it was zero then it has become zero of zero and if you have corrected it then but what had I read? Before taking this rectangle index, before taking this rectangle index, you have to ensure that the previous element which I had taken, remember that P was the index P, it should be small, so look at zero, which is smaller than one, obviously, it is fine, meaning. What am I saying? Off, which is the previous index, it should be P <= which is the current index, it should be P <= which is the current index, it should be P <= which is the current index, I am fine, only then we can take it, see what will become of us, it was already zero, here it is, now we can take one, right? Okay, it is taken and now we have taken one, so now my previous index will become the previous element. Okay, now whatever element will be taken after this, it should be bigger than this one, only then it will become increasing, isn't it clear till here, so I would have written. I am here 010323 index here has become very big till now it is clear now see this here in this index I have two options I will take or I will skip now let's see whether I will be able to take the previous element which I Sa took this P, this is zero brother, can you take what is that one, then the same thing, zero is one, after that then you cannot take zero right because there is no increasing, so I am not taking it at all. Right here, I can't do a take at all, so I remove the take, here I will only be able to skip here, okay, here I will only be able to do a skip, so what do I do next 010323 and My sub sequence has become zero comma, till now it is clear, okay, now let's move ahead, here is my A, okay, you are very important, pay attention from here, it is better, now look here, I have two options. Should I take it or not if I am late to take it? Well if I take it then before correcting it I have to check whether I can take it or not. Do I remember what was my previous index? Was it on this one? Here too, it will be the same, okay, which element is one, and now I am taking G element as six, it is three, so we can take it because it will become increasing, otherwise see what will happen to me, what was earlier was zero comma one. So here it is, now I am taking three, neither is it zero, comma, one, comma, three, my sub sequence and increasing is also zero, one, three, this is correct, let's write it here. 010323 Here I had taken it and if mother takes it, I skipped it, okay then see what will happen here, zero and one were there, they will become zero and one and this is my P, which was this P of P. This will remain here and my P will be changed here. Which is the last element? We have taken the third one, so this is my P. Okay, I will write it in the second color. This one is pointing to the third one. Now whatever element I will take, that will be there. It should be greater than three, okay, here also I write zero, one, zero, three, you three, mine, one will go here, okay, go here, one will go here, okay, now give carefully, a very important verse is coming, now look here, pay attention here. Are there two options? Yes, let's see, this is take, this is escape. Can you take that? First, see which element is in this element, you are there and the previous comment is three. Can't take it, obviously zero is one, three is now. You can't take increasing, it will be a little, if you want increasing, then here you can take down, you will only have to skip, then you have skipped and your zero will remain the same and this is your P, so let's move ahead 010323 here. A, then let's see if you can do this, there are two options after this, okay, no, now the current element is three and the previous element is also 3, you want increasing, neither equal nor smaller, 013. Here, now the current element is three. Cannot be taken, it is strictly increasing, it is required to be greater than 3, it is required to have a greater element than this, then even take will not be possible here, only if you skip, then pay attention, here zero 3 is fine, so what does it mean that if we have exhausted all the elements, then one less is required. Now let's expand this branch and see. Okay, so if you scan this branch, then here I have two options, whether I take this one or not, if I take this one, then see what. I can take it, I have taken it, okay, now look, pay attention, okay here too, it came here, where did it go, it went here, then we have two options, either I will fix it or I will skip it. If I take it, then look, I am late, take it. Can I do it or not, okay, this is three, can I take this? Previous Index: It must have become my P Previous Index: It must have become my P Previous Index: It must have become my P because last time I took you, okay, if you are bigger than you from three of the ways, then I can take it. 0 1 2 3 done, this time my all sequence is fine and this time I will expand further zero one zero three two three index is out of bounds okay here our tomorrow is over okay and you can expand in skip also okay but now Pay attention to one thing, see how our answer will come, look here, remember from the tree diagram from above, when we took the first element here, we took one element, otherwise one, we must have done plus, okay, after this I said yes, okay. Out of the remaining, send me the length of the longest increasing sub-sequence, send me the length of the longest increasing sub-sequence, send me the length of the longest increasing sub-sequence, I will add it, okay then 1 + and I must have I will add it, okay then 1 + and I must have I will add it, okay then 1 + and I must have killed it here, okay then here I took it, see, take one more element. Ok, so here also I must have done OnePlus, now I must have said kill the recursive tomorrow whoever comes, I will add it here and send it above, it is clear till here, okay, so here also it is a skip, then there is no ID in the skip. Must have been done directly, must have been done yesterday, we are fine, now it is fine here, so I must have done the same in tech too, OnePlus then must have killed me yesterday with Rucker, rest of the people who come from here, send me the length of the longest sequence, it is fine, now see. Here I have to hit skip tomorrow, send me the answer that comes from there, then hit OnePlus recursive tomorrow, send me the answer from here, now look here, it is out of bounds, meaning I cannot get any more sub sequences and elements. So I have returned zero from here so one plus has become zero here. Okay, whichever max I got out of the two, I have returned the same, I will return the same. Okay, so one, then whichever mother you take, here only one will come, so one will return to this one. Have you done it? If this one goes here, then you become one plus one, so look, you have got something from this branch, this one must have got something from the branch, okay, less will come from there too, if you trade, if you draw, then whichever of these two It must be max, I will send it up, okay, you came from here, something must have come from here, okay, so I returned three and gave it back that brother, I have brought three from below, so 1 + 3, see 4 A. Now it will so 1 + 3, see 4 A. Now it will so 1 + 3, see 4 A. Now it will return above that brother, I have the formula and here I must have got something from the right side, mother, let's take S, I must have got the maximum of the two, that will be the answer, actually it will be only 4, now it will draw three diagrams, you will see it ok. If yes, then your final answer is going to be four, okay, it is divided by the diagram, okay, now the story I have told you, okay, the story I told you, how easy it is to convert it into code, look at it according to what the story diagram taught you. Now I will write the code, okay, let's start, prepare the code, how did we start? The index was here and we have not taken anything previous to it because in the beginning, what is mine is zero, we started from here and science came. If mine is zero, then there must be no previous one, otherwise the previous index is -1, I am late till now, it is clear, index is -1, I am late till now, it is clear, index is -1, I am late till now, it is clear, now I have to write the solution, which should be shown in exactly three diagrams, exactly the same item came, whichever mother I take and I remember it, I have taken the previous index correctly. So what did I say? Now we ca n't add any element so I will return zero. Okay, I will return zero. What am I returning? I am returning the longest increasing sub sequence. Okay, so right now there is no element. So the answer will be zero. The element cannot be taken out by aliens. Now it is not there, I have it clear till now. Now look, it is okay to write but remember I said that I will check every time whether I can actually do the tax or not. If previously I have not taken any element yet, minus one, if no element has been taken, then I can definitely take it, or if P is not minus one, it means that previously we have definitely taken some element. So it should be small, it is the current element which I want to take, okay, so what I am saying is that it was the previous element, if it is there then only I can fix it, okay, you solve it and bring it, so what is there here? Will it be I + 1? The what is there here? Will it be I + 1? The what is there here? Will it be I + 1? The index will be flooded further. I am fine. First is the second relief. If there was a previous index, then I + 1 or all the elements after I + 1 or all the elements after I + 1 or all the elements after I, who will be the previous element for them, the current one which I have taken, I was taken, right? Now this will become my previous element, it will become the previous index, remember, we used to do the same thing whenever we took any element, mother takes it, now I have taken three, look here P, this used to be the previous element, so the same. I am saying that now I have taken the rectangle helmet, see the previous index has become my eye and I have made the further eye bigger, so in this take, I can do it in this way, I can only skip, so I can do it anyway. I am not sure that this rectangle helmet was skipped. If you want to skip an element then it is very simple. Skip it equal and you simply solve it. Because we have not taken tomorrow in the calendar yet, then OnePlus will not do it. Obviously, you will return the answer by simply solving. Bring i+1 and see this time answer by simply solving. Bring i+1 and see this time answer by simply solving. Bring i+1 and see this time i will not change, meaning the previous sentence i will not change, still p of previous air will remain ok, so the previous index which is already there will still remain the same, till now it is clear, the same code as in the free diagram. It is written and in the last what is to be returned, the maximum of tax which is given among the two will be my answer, it has become clear till now, it is very simple, okay here, so what I always wanted to say in my memory is that brother, if you follow this trick diagram. If you will become complete or not, then I have not created it. If it becomes a very big tree, then you will see that there will be many repeated sub-problems many repeated sub-problems many repeated sub-problems and repeated sub-problems and repeated sub-problems and repeated sub-problems means that I can memorize them. Okay, so what do I always say while doing voice? It was said that where the reconstruction is happening tomorrow, pay attention to it, here it is happening yesterday, here it is happening tomorrow, you see both the variables are changing, this is also changing and see this is also changing, isn't it? Sometimes it is changing and sometimes it is not happening. Look, this one has changed here. Okay, so both the variables are changing, which means we will have to take DP of two dimensions to do movies. And you have got the memorization well that brother, everything. Before calculating, I will check whether we have solved the DP of current I and current T before and whether we have done the result or not. Before maxing the return, I will solve it. For these PKs, this is When the max result came, I stored it. Okay, so how many maximum states will there be for every element, infinite total, every element, you will have two options, how to go worst, in all the elements, you will have the option of taken skip, then your power will become N. Time complexity is ok. For take and skip you will have two options time complexity that is without memorization but what will happen if I am fascinated that we will visit only this much status max tu max ok how many statuses are there n² status neither How to do it, the time complexity will be off and squared. Okay, so you have understood the code. I think even if you don't see the code, you can code it yourself. Let's go to Let's Good and submit its code. So let's code it. We will make it exactly as explained in this video with the help of recognition and memorization. First of all, I am going to define agriculture again. What will agriculture be? If it is zero then I have returned zero. Till now it is clear. After that, the interior goes by the mother but in tech. When can I do it when P = either minus means I have I do it when P = either minus means I have I do it when P = either minus means I have not taken the previous key then I do not have to compare with anyone and if I have previously taken any element then I have to compare Right means I have to take the current element if So it's great be greater den juice of P is ok only then can take it how to take it what will happen 1 + why did oneplus do this because 1 + why did oneplus do this because 1 + why did oneplus do this because I have taken i thermal now which is the remaining element since i+1 for them Who will be the previous element? since i+1 for them Who will be the previous element? since i+1 for them Who will be the previous element? This current element will be right because now I have taken it, here it is ok, so the previous index will be the same as it was. The return will be either from maximum of take or from skip. The one who got maximum will be the same. Look at my answer, this is passed. But this is without memorization I think the time limit will be limited to one seat because look now we have written the exponential solution, look at the value of power of n, 2500 power of n is 2500 which is a very big number and definitely this time limit will feed that is why we have to We will have to do memos. Okay, so let's do it as memories. Look, I can't do it. If there is a seat in time here, I will take a DP to do the voice. Look at me in it. Two things are changing, right? The index is changing. If there is one this and one this, then I will have to take 2d, so I will make it 2501, I will take one extra, okay and in the beginning I will do everything from minus one, this is the shortcut, it is up to you to fill this space from minus one. You can also fill it with a loop. Okay, now before doing everything, I will check beforehand that if I have already stored the IF for this i and for this p, then the result will not be equal to minus one, so how can I do that? What I will do is I will return T of I comma P. Okay and if not stored then I will solve it first and before returning here I will store it but one thing pay attention here if the value of P is -1 then this So this code will be fat, no is -1 then this So this code will be fat, no is -1 then this So this code will be fat, no index - we may be a little, so I will index - we may be a little, so I will index - we may be a little, so I will also add here that P note should be equal to minus one, only then you will be able to check this, if P is minus one then you are seeing this one. There will be a problem, the index is never negative, so here I am giving this check that it is clear till here and look here too, we are doing memory here, so TI and P are doing it, so here too, it is obvious. The thing is that if P is not equal to minus one then only you can write TIP, otherwise if P is minus one then it will get fat, this code cannot be a minus one index, okay then how can you store it. Yes, it is ok to do it like this otherwise directly return here like this, it is ok only then you can check this, tip, because if P is minus one, then this code will become wrong, it cannot be negative even with the index, what did I do here too? I did the memory only when P is not equal to minus one. Right because if P is minus one then this index - can never be then this index - can never be then this index - can never be negative, so it will go to error A here. Okay, now let's run it and see, let's say farewell. Passed example test cases, after that we will submit it and see it. Now let's submit. All the options are exactly the same as written. Any doubt is resident in D common area. Video. Thank you. | Longest Increasing Subsequence | longest-increasing-subsequence | Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_.
**Example 1:**
**Input:** nums = \[10,9,2,5,3,7,101,18\]
**Output:** 4
**Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the length is 4.
**Example 2:**
**Input:** nums = \[0,1,0,3,2,3\]
**Output:** 4
**Example 3:**
**Input:** nums = \[7,7,7,7,7,7,7\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 2500`
* `-104 <= nums[i] <= 104`
**Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity? | null | Array,Binary Search,Dynamic Programming | Medium | 334,354,646,673,712,1766,2096,2234 |
52 | hello let's try to solve another lead code problem number 52 increase the two so this is totally the same as increase one yeah if you didn't detect my increase one video I suggest you check that because my code is totally based on that yes so I'm not going to explain the algorithm I'm not going to explain the descriptions because totally is the same only difference is here we are going to return our integer n so n is the number of distinct solutions to the increase puzzle so for this one we are not going to check the board we are not going to return a bot we just going to return how many different combinations for example this one we know it there are two and if any equals to one definitely it will be one and N is also from one to nine yes now let me explain my solution from increase 1 and then since a little bit and make it works for increase two so this is my code for increase 1 as we can see it's totally the same yeah so from here this is the board if inside the board it means all combinations of the board if we here return the result it will return a lens without the length of the result it should also work but here I'm not going to use it this way because it should be same simpler than that we don't need to initialize the board and we don't need to check the pod yeah to put it a capital Q or to cover it to the dot because we don't need to do that yeah and the question also didn't give us what the body looks like so from that we can make it simpler to change it to the above code yeah now let me explain the code so from here it's also the same I'm going to Define three set the column set positive diagonal set negative diagnose set and also here I will give a global variable self dot result because this is what I'm going to return I'm going to divide our backtracking function and it's also backpacks for those so it will start from a row zero and once it goes to row in I will use the self.res result plus 1 in I will use the self.res result plus 1 in I will use the self.res result plus 1 and then I have a return so this is only the difference because I'm not going to put the board inside my result I'm going to plus 1 because I'm going to find how many different combinations and also for the column for saying listen if it says not in column set R plus C not imperative diagnosis and R minus the same naught is a negative diagnosis so I can put everything inside of the set after that I don't need to put until Capital 2 inside my bot because I don't need to do that so I just deleted that code I just use backtracking after backtracking if I identified yeah if I didn't it didn't go to earn and if the C didn't meet this condition not in all those sets it means I will go backtracking so for the backtracking it's also the same I just need to remove from the column set I needed to remove this cell from the positive diagonal set I need to remove our process say negative diagonal set I need to remove our minus say so it's totally the same as the increase one now let me submit it to attack if it really works yeah as you can see it's pretty fast and it really works so for this kind of a lead code problem I think uh yeah we are giving two questions actually it's totally the same we can just change a little bit from an increase one to increase 2 to solve the problem yeah thank you for watching if you think this is helpful please like And subscribe I will upload the modded called the problem next list bye | N-Queens II | n-queens-ii | The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9` | null | Backtracking | Hard | 51 |
257 | we are given a binary tree and we need to find out all the root two leaf paths we know that a binary tree is a tree in which each node can have at most two children that is each node can have at most a left child and their right child in a tree the topmost node or the node that doesn't have any parent is called the root node of the tree and the bottom mask node or the node that doesn't have any children is called the leaf node we need to find out all the paths from the root node to the leaf nodes for example for this tree we have the paths one two five one three six and one three seven to solve this what we can do is we will first start the traversal from the root node and also during traversal at each node we will be recording the path we have taken now from this node we will check whether it's having a left note or a right node since it's having a left node we will first continue the traversal in that path now at this node we do not have any left node but we do have a right node so we will continue the traversal in that path now at this node we neither have a left node nor a right node that means we are currently at the left node and therefore we can stop the traversal and store the path to the result now coming back to Node 1 we can now Traverse through the right node from this node we can continue the traversal through the left node at this node we do not have a right node that means we have reached the leaf node and therefore we can stop the traversal and store the path to the result now coming back to node 3 we can now Traverse through the right node at this node we don't have any left or right not that means we have register Leaf node and therefore we can stop the traversal and store the path to the result finally this is the list of all the paths from the root node to the left nodes now let's call the solution we will create an array for storing the result and at last we will be returning it for traversing through the tree we will write a separate function we will start the traversal from the root node and initially the path will be starting with the root node since it's given in the problem that there will be at least one node in the given tree we don't have to put any null checks for the root node inside the function we will check whether the current node has a left node if it has a left node then we will call the function recursively by passing the left node and adding the left node value to the path likewise if the current node has a right node we will call the function recursively by passing the right node and adding the right node value to the path and at the beginning of the function we must check whether the current node is a leaf node if it neither have a left node nor a right node then it's a leaf node and therefore we can store the path to the result and return from the function before adding the path to the result we will join together the string elements with this Arrow string foreign it's working see you in the next video | Binary Tree Paths | binary-tree-paths | Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100` | null | String,Backtracking,Tree,Depth-First Search,Binary Tree | Easy | 113,1030,2217 |
322 | hey everyone welcome back and let's write some more neat code today let's solve another classic dynamic programming problem coin change and we get a pretty simple uh description so we're given a list of coins of different values and we're also given a total amount of money that we want to sum up to but we want to use the fewest number of coins possible to make up or to sum up to that amount and it's possible that amount of money cannot be made up with any combination of the coins that we have and then we want to return negative one if that's the case and luckily for us we're actually given an infinite number of each coin so in the first example we have coins of value 1 2 and 5 and we have infinite quantities of these coins the amount that we want to sum up to is 11 and basically you know just look at this what's the fewest number of coins we could do well of course we want to use a five because it's the biggest one we can use another five and then we just need a one left if we want to sum up to 11. so in this case you can see we only needed three coins these this is the fewest number of coins we needed so we can return three in the second example we have a coin of value two but we want to sum up to three we can try two plus two but we know that's four so we went over three so there's no way to possibly sum up to three so we return negative one there's no possible solution so your first idea might be can we just be greedy is the problem that easy can we just be greedy and let's look at this example so let's say these are our coins one three four five and we want to sum up to seven so when i say greedy i mean okay we wanna sum up to seven let's just start at the biggest coin we have so let's start at five so now let's look at the biggest coin again five if we add a five here we know we're going over the total amount seven right so we don't add another five well let's look at the four well we know five plus 4 is also going to be more than 7 5 plus 3 is going to be more than 7. okay but we found a 1. luckily we have a 1. so let's add 1 to it now we're at 6. so let's add a second one now we got to the sum seven so we basically went down from the biggest smallest coin values right that's what i mean when i say greedy let's pick the biggest one possible first so notice that this took us three coin values right so our result in this case would be three but is that the minimum amount of coins the answer is no because you know just looking at it we can tell we got a three and we have a four three plus four is seven that means the minimum amount of coins is actually two so this is a counter example we cannot be greedy if we want to solve it so the next thing you might try is like a brute force solution right so to do the brute force solution we need to implement some kind of depth first search or backtracking solution right so let's look at the same example one three four five and amount sum to seven so what would a backtracking solution even look like for this problem well it's gonna be brute force right so we have four coin values so that means in our decision tree we have four possible choices we can choose a one we can choose a three we can choose a four or we can choose a five in this case the remaining amount would be six because seven minus one is six in this case the remaining amount that we have to compute would be four because we're taking seven minus three which is the coin that we chose so we get four as the remaining amount right in this case we would have a three and in this case we would have a remaining amount of two so since none of these are zero once we get to zero we know that we've computed the total amount that we want but right now we have to continue going right we have to continue doing the brute force approach let's start at this side right now so we still have four coins right we have unlimited quantity so we can choose the coin one we can choose a three we can choose a four or we can choose a five if we choose a one we'll have a remaining amount of one if we choose a three we're going to get a negative one what does that tell us that tells us if we chose a five coin and we chose a three coin then we get to a negative value that means five plus three cannot be the amount so we don't have to keep searching here we can stop right we got to a negative value if we keep adding values to it's just going to become more and more negative right and you can probably notice that since these values are even greater 2 minus 4 is going to be negative 2 minus 5 is going to be negative 3. so we can't go down these paths either we don't have to search them anymore and so now here we're gonna see okay we can choose a one coin of course we can choose a three four and five but we can see from here that's not gonna work that's gonna lead us to a negative value anyway if we choose a one over here then we know we're going to finally get to a zero so this is what we want right we took a five from up here we took a one from over here and we took a third one right so then if we count how many coins we chose down this path we know we get three coins right and we get to a zero so of course we don't have to keep searching anymore so we found one possible way where we can sum up to the amount seven we know it has three coins which you know from the previous example we know that's not the minimum amount of coins but we found an algorithm that at least tells us a possible solution so we can kind of keep track of that the minimum coins we can set to three so now i'm gonna show you what happens when we go down this tree path even though we know that the solution is actually three plus four which is two coins which either of these is gonna get us to the correct solution i'm gonna show you what happens when we go down this one anyway so we can choose a coin one three four or five so if we go down this path we will have a remaining amount of five here we'll have a remaining amount of three here we'll have a remaining amount of two here we'll have a remaining amount of 1. do you kind of see how we're taking the original problem which is 7 and then breaking it down into sub problems like 6 and then breaking it down even further into five and not only that we have sub problems yes but do you also see that these sub problems are repeating themselves here we have a remaining amount of one here we also have a remaining amount of one so do we even have to compute this path because we already know if we have an amount one it takes only a single coin for us to be able to reduce it to the amount zero which is what we're looking for so since this sub problem repeats i don't have to compute it i can just borrow from over here so in that case we see the same thing happened though we use a coin one and we get zero and we see that okay it took three coins for us to get to zero right we took a one a five and another one from over here so basically we got the same thing that happened over here just in a different order and just to make this a little less messy i'm just gonna tell you that none of these are going to lead us to the optimal solution so now let's look at this case we have a remaining amount of four how many coins does it take for us to get an amount for well let's brute force it let's check every possible combination here we'll get a one here we'll get the value we're looking for zero that's great but let's just look at this last one with five we'll get a negative one meaning we can stop searching so this is awesome we got a zero and let's count how many coins did it take us to get to this zero we took one four and we took a three so this path is only two coins long we see our minimum is currently three but we can actually replace this now with a two because two is the minimum number of coins needed to total to amount seven so we know this is the correct answer but let's just see what happens with the remaining stuff so first let me just look at this one we see we actually already solved this sub problem over here so we don't really need to solve it again we know it takes one coin for us to go from one to zero and what about this three okay well we can do the same thing right one three four five and i'll just tell you from here we're not going to find the optimal solution going from four to three and more that's going to obviously be more than the current minimum of coins that we have which is two right now so this is not going to lead us to the correct solution but you see that once we compute this stuff then we have one last subtree over here right this original three but once we already solved the sub problems of this do we really have to solve the sub problems here no if we store it in memory if we have like a cache or you can call it dp we do not have to repeat these sub problems so the way i just solved this was called top down or top down memoization because we're doing it recursively but you can actually solve this with a true dynamic programming solution which is bottom up and it means exactly what it says so bottom up basically instead of solving the original problem where the amount is seven we solve it in reverse order we start at the smallest one which is zero right this zero over here so we wanna know what's the minimum number of coins we can call it dp of zero so for amount equals zero what's the minimum number of coins for us to sum to zero well we know it just takes zero coins right what about if we wanna know what's the minimum number of coins for summing to one well we can look at our coins we got a one a three a four and a five these will all cause it to be greater than one but we just want a one so we can take just this meaning it only takes us one coin to sum to 1. and then we can just repeat that process right so for a dp of 2 so we want how many coins does it take for us to sum to 2 well we got 4 coins right these 3 will cause it to be greater than two so we don't use those but what about this one okay we get a one so it takes one coin to sum to one but that's something we already knew so if we want to compute dp of two we can take one plus dp of one because we know these three coins are going to be too big but we have a one over here that's value one and we also know that's not enough right two minus one still leaves us with a remaining amount of one but we just computed that up here we know for us to get the minimum number of coins to get a value one it only takes one coin so that means that if we want to get amount two it takes at least two coins and let's say we repeat this process for all values for all amounts from all the way starting at zero all the way to seven over here so i computed it from all the way from zero to six but the last one we really want is amount equals seven so let's compute that dp of seven how do we get it well we still kind of have to check every single coin so what happens if we get coin one then we are com then we take the result of one meaning that's how many coins we use not the value one because we needed one coin with a value one and now we have a remaining amount of six right dp of six so how many coins did it take for us to compute dp of six well we already computed that it took two so we get one plus two equals three so that's one possible solution but is it the minimal solution well let's look at if we use the coin value three over here well it takes us one coin so we take one plus dp of four because that's the remaining amount we have to use if we take a coin value of three and lucky luckily we already computed dp of four it is one so then we get one plus one equals two and we know that this is the real result that we want but even before we know that we would repeat this process so technically if we do the bottom-up bottom-up bottom-up dynamic programming solution we are going to repeat this for the remaining two coins so for four we would get one so we'd have one plus dp of three because four minor because seven minus four would leave us with a remaining amount of three and in that case we know dp of three is one so we would have the total of two again so we see that there are actually two solutions and we know we have one last coin that we technically have to check coin five so we'd use one coin for value five and then the remaining amount we'd wanna compute is dp of 2 and we know that dp of 2 is value 2 so this would result in a 3 which is not what we want right so from these 4 values that we computed we want to take the minimum which we know is 2 so we can return 2 in this case so that took us forever but luckily the code is a lot shorter so just like we showed i'm gonna have a dp array and i'm gonna initialize this to be length of amount plus one because we are going from zero all the way to amount and the default value i'm gonna give each uh element in this array is amount plus one or you can do like infinity or whatever the max in is like math.max integer or whatever math.max integer or whatever math.max integer or whatever in your language but amount plus one is basically a max value anyway and we know that the base case for this is a dp of zero meaning if we want to compute amount zero that it only takes zero coins and now we're going to start computing every value in dp so for every amount a in range and we're going to do this in reverse order not or rather bottom up so we're gonna go from one all the way to the amount and we technically are still doing it in a brute force way so we are gonna go through every coin so for coin in our list of coins so we're trying to compute this a amount so we're gonna take a and subtract the current coin that we're looking at if this is non-negative if this is non-negative if this is non-negative so if it's greater than or equal to zero that means we can kind of continue searching right so this means we possibly found a solution for our dp so for this amount a we're going to set it to the minimum of itself and 1 plus dp of a minus c so this 1 comes from this current coin that we're using c and dp of a minus c comes from for example let's say our coin value was four and our amount that we're trying to compute a is seven basically we're saying dp of seven is equal to one plus dp of three because seven minus four is three so we're saying that this is a possible solution and actually that's the only thing that we have to do this is basically it this is like what's called the recurrence relation and so now the only thing we have to do is return what we're looking for so dp of amount so this is what we have to return but we remember one last edge case if we could not compute the amount meaning if so we can only return this if the value that's stored is not the default value so if it's not equal to amount plus one right which was the default value that we gave it so we'll return this if it's not the default value otherwise we're gonna have to return negative one meaning we could not compute this amount with the given coins so this solution does work and even though it's pretty efficient the time complexity is actually big o the amount that we're given multiplied the number of coins that we're given and the memory complexity is big o amount because we see we have a dp array that we're having a potential value for every single amount so i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon | 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 |
1,996 | This is a very interesting problem to be solved and the name of the problem is, if you beat the number then I have brought it very well. To understand the problem, you should understand that what kind of ghee is there in our body and in this simple vegetable. We will explain that if the definition of key takes the number Ghr, then now if the key is the button and the key is the difference and on the same side, if the attacks of sutras in nine different forms are taken after all, then what happened in this case that the semen is whatever it is the powerful situation. Se and in situ place weak character here we will say now here comes some more condition let's Bose again I am C1 and C2 character and its taking time is its defensive fiber Simran its test is vitamin but its difference is that Sawan So, there is no one here Begum, we will only count the one whose attacking plus defense system is there, if he is ascendant from any other quarter, then what will we do with him, that is, not even a single character will be counted one by one through the subscribe button and if there is talk in this fort. If we do then it is not that the sound is less and inside it is ok similar. Now its tags Yadav is more defensive and its defensive is less then we will beat. Inside it both attacks will have defense and it will be less. Now we have understood this much that we need to tell the being. How many beat characters are there, so if you try to solve this then the first thing that comes to my mind is to go pro, then I will do one thing that all the characters on the die, we will dry them on the side of their attacked power, if we do it in this way. Let's take the one with the lowest attack power, now we will keep him first, then after that, we will leave him, so I assume it's simple, I give an example and inside that example, I take some characters, gate, then I take one character, sew one. Took Situ for one, C3 for one, 8041 for simple ok, so now I will tell it to Shivansh, now I am selecting it and telling you that its cases are Attack 1 and Defense and 2 and its Tiger 2 and this will be cream and its The texture is that two and difference 41 and here we will take a simple one that we take a moment my to its three lord difference in the same way we will attack it and right here so here we have subscribed according to our Do it and subscribe, we can see so much, subscribe, all the things that I have, whether they are quick character or not, what will you have to do for them, their difference will increase by forwarding them to me, okay, then my difference power will have to be licked by each one. So friend, this is what I change the color of, otherwise it means that whatever character we do, we can make all the big buts with this, as you can see, after this you can change the color of this and this because it has attack, so it means If we try to fold it in this way, then our answer is that we should do it like this, let's say if there are two characters whose attack power is the same, then in that case, the one whose defensive power and the one whose maximum growth will be brought first. You understand, bring that in first because if it can be done like this again or what we can do is like we have taken here that the smaller one will increase then we can fold it in such a way that the biggest one will be the first one. By using questions, now we give the answer to this, I now because here we were facing problem, so what I said is that we will reverse it, like I said that this four one has come whose biggest attack is over head, your three descendant is its most More attacks etc. But when we type two beans here then what will we do with it, the one which has the least difference power will be kept first, okay and the one which has more power will be kept later and then 142 will come. Now what can we see from this? Abhishek, I got to see this, friend, if at any point of time we have used any character and made this choice, then you will know that this character has been attacked more than all the characters before it. If it is less then very right, I have to know only one thing that all the characters behind this character, is there any character inside it with the help of which it is less than this year, if it is less than this year, then if all the characters on this tractors, if its Which means that when I take it, whatever will be of his, up to the maximum, keep a reminder that he will leave me with himself, if the group's okay, if I talk about this character, that you are mine, this much is certain. That all these characters have the attack which is more as compared to this but if I look at it then check whether I remember the defensive vs of all the characters before this or not then you can see that There is no such person, nor is there even a single character like this one. Now let me talk about this. We only know that all the characters after this one, what is their attack power? This is the base, if we want to check that. Yes, and what will happen in this case, I will also have this character, Ayub, you understood it completely that we first thought that attack power can come, but what is the problem in it, what is the problem, friend? See, if we were filling the same type of then we were facing the problem that we were not able to qualify A, but if we brought this monotonous type of A which is a character then before that there is an attached substring of all the characters. What you have to do is you have to type that there is a character whose design receiver is more than my character for which I am checking, so let us take an example and solve it properly and see what happens. So limited, some examples of proper example, rough, let's take this example, okay, for now, this is the lady, and now what was to be done, the first word was to dry my dry ginger, in this way, the maximum of this juice, which is the difference power, attack power is very high. Keep it like if tank and if for then after that is his and then came three miss's anger came one and then fight next so what will I do this next my week character initially zero so first of all I am here and I am here with the maximum which Na maximum difference meet on, I don't have any option in typing, so if it is 200 then I will joke that there is someone who is defensive about it and is it small, I still have Comex, so I came to know that it is not small. If I am sitting then it means that I too can't be there, so I have updated the for here, now I go here and what should I do, is this my difference, is the maximum destruction I have done so far is smaller, yes man, look at yours. Idiot, what will I do, just update it here, I will go ahead and check whether the sub character whose difference is smaller than the house, then no brother, there is nothing like that, mine is bigger, so I will update it. I will give and I have checked all the characters and I will return within a day and now the biggest question comes that how will this shot be done? Now I have an egg, so how should I soften it? First of all, I need a tight person with maximum attack power and also what do I need that if there are two add-ons for this character and if there are two add-ons for this character and if there are two add-ons for this character and one with limited power, then what I need is that this is the first time, so what should I do, I will do all the things, okay, I will wait and I will set this positive like this and this sweater from the wool box. Now see in this case when I will soften these two, then both of them are the same, their pretty. These two schools will come first and the one who will request fourth, inside which is the smaller one. If it is echo of birth then it will come free and this one which is Barmer with character-tempo, and this one which is Barmer with character-tempo, and this one which is Barmer with character-tempo, then in this way I will soften either my ribs, in this way whatever option is available, inside we will solve the problem in this way, let us tell you. Did you understand that if you hybridize all the characters I have and I have gone to Edit Kishanganj to make everyone attack or negative, the one who has the highest tight power will go first and if by any deception, the pot power will go. So what problem would I see in them that if we have a smallest sorting algorithm then what we will do is we will put the smallest one first and once we have it soft then what we will do is we will take encounter and give a maximum difference like we had taken And we will start vibrating each one and I will check that the difference of this character has come is it a small house at the maximum so that means Naveen and I have increased the doctor and if not then I have increased my I will update the maximum properties but I will return the contract in the next day and in this way we will solve this problem. Now let's talk about whether it is taking time complexity, then it seems to be solid here, so in the shot, I will tell you the login and Then later together we have my group and the one who is riding once, so the total is the one and the login is done, we have the one who is my time complexity and I hope you like it, thank you Ba. | 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 |
77 | hello everyone welcome to my programming Club today we will be solving another daily read for Challenge and the challenge name is combinations so the challenge statement is like this given point dealers and NK return all the possible combinations of K numbers Frozen from the range 1 to 1 you may return the answer in any order statement is saying you will be given a range 1 to m and you have to make a k digit combination a digital combination you have to make choices these numbers and accordingly the combinations will be formal choices among there is a number this is the given range so now nothing to be noted is when you will be forming the combinations and you will be following the combinations for example this uh these two combinations one comma two here K was 2 and N was four so you were having one to four and you have to you will have to form uh two digit combinations if you form a combination one comma two and you form another combination uh these two are the same thing since order does not matter all right so it is to be noted that duplicates here are not allowed duplicates not allowed since uh in computation by default the duplicates are not allowed unless otherwise stated in the program so I hope it's clear to you now let's move to the constants part what are the constants and it's size is here given to be of order 20 so inside is of order 20. either less than n or equal to l these are the constraints let me quickly change the color so these are the constraints you have to form K digit combinations from this given range now what will be the group Force relating solve this what will be the good Force here when you will be generating all the combination let's say this is the given range and we want to end and this is the final combination that you have to make a digit combination that you have to make from this range so each of the number in this range will be having two choices either that number will be included in the final combination in this combination either that number will be included or not included so for each of these numbers we will be having two choices so it will be like this will be n times what is 2 raised to power it will time complexity will be 2 raised to power n of this Brute Force approach and N here is 20. 2 raised to power 20. let's check what's 2 HD power 20 is this number one zero four eight five seven six for two days to power 20 is one zero four eight five seven six so this is the number now it is lesser than then this to Power 8 operations since its magnitude is of the order 10 raised to power 7 so those of you who are not familiar with let me change the slide who are not familiar with how the and complexity of accepted solution varies according to input size I'll provide a link for our article describing this you can check it check that link that article show that article and come back to the solution and now I what I can tell is in one second you are allowed only 10 days to Power 8 operations so you know you order for your solution to be accepted it should be lesser than is to power rate operations otherwise it will if I get a clearly so this will not give us tle solution will be accepted but how will we keeping track that there are two uh thicker Parts in this solution I will be keeping number will be keeping track of already included numbers since the duplicates are not allowed duplicates are not but already included numbers in combination we will be forming combinations in this direction we'll have to write we will be keeping track of let me quickly change the color keeping track of already included numbers in combination duplicates are not allowed so this is one thing another is the order does not matter if yeah this is the only thing uh since the order does not matter if there are no duplicates uh your order will be the same so if let's say already included you try to include it again it will not should not be allowed and you have to also you have to uh yeah this second condition will be you have to check uh whether this type of conditions should not occur these two combinations will be the same thing so the ordering of community you have also try to also check the ordering of combinations only is not mattering if a number is included in the combination you should not consider it again in the combination so how will you be keeping check of this note now if you see the constraints carefully observe them inside is here 20 only and K is maximum size is also 20. so in order to store a k digit combination a digit combination for it I will be storing it if somehow we can check in or one time that whether a number is included or not number included or not in combination and this should be our concern so what we will be doing is uh we'll be storing the combination in the integer variable inside teaser variable is of 32-bit inside teaser variable is of 32-bit inside teaser variable is of 32-bit these will be the 32 bits how each of these bits can represent a visit in combination so we are only required we will be only required 20 bits 22 bits to store the combinations Max this is the maximum value of K so at Max uh 20 digit combinations will be made 20 digit combinations so these combinations will be in the range 1 2 raised to power 20. if you consider uh this will be the range one to two raised to power 20. the numbers from 1 to 2 raise to power 20 can be present combination States combinations or say combinations let's call them States different combinations we are calling them States so numbers from 1 to 2 is to power 20 will represent them which is nothing but uh what we have to do is we will check for number from One two raised to the power 20. and if you take another slide we will check from numbers from one less to power 1 2 raised to power 20 and if the number of set bits in these numbers happens to be equal to K is equal to K then it is the combination we are looking for K digit combination then it is indeed the create Egypt combination we are looking for counting the number of set bits uh what are the setbacks signal integer of a integer variable law is of 32 bits so we will counting the number of bit sets out of these 32 bits and if there happens to be equal to K so it will represent a k digit combination I hope it's clear to you why it will fit in a number because we for each number we were having two choices and such uh at Max 20 numbers were possible since size was 20 so 2 raised to power 20 and this we are iterating from uh this range one two raised to power 20 and you may ask okay we will know if a number is representing a valid combination a valid here digit combination but how will be forming uh that K digit combination from that number of to convert uh representation number let's put it representation number the presentation number to a digit communication this will be your next portion so what you will be doing you will be using bit manipulation to check which number which bit is set you will take a variable num and initialize it to 0 because the range is from 0 to n okay and then what you will do is you will keep on the iterating for the digits of that number that is representative representing a number till there are no set bits putting over this represent ing number from the right to left from the least significant digit to most significant bit sorry I called it's built from the only significant so this is so what we will be doing and as soon as we found a match that let's say this was the number and here num value was one and this was the what is what it is the second bit towards say the possibility so the zeroth bit and here ends value would be 2. now say this bit is set then you will include 2 in your combination now let's say you encounter five for the numps value here and this visual set so we will uh five to your combination so in that way you will be converting this representing number two home combinations so I hope it's clear too if it's still not clear to you uh it will be more clear to you in the coding part now let's including to the coding part what we have done is we are checking from one two raised to power 20 so this is the maximum States if state is nothing but that is a combination of digits that is nothing but a combination of digits and if this combination is representing a k digit combination then we will consider it will be checking if it is a combination the number of in number of said into its check if it happens to be equal to k then it is indeed that combination that we are looking for and we will convert it into a list for say combination this will convert the state into the combination informal best uh what we are doing is we are added we are iterating from the zeroth bit to the endless bit from right to left and at each iteration we are increasing the value of num and if the current bit happens to be a set bit we are adding num's current value to our combination and uh last we will be adding that combination to our answer and we'll be returning our answer so this wraps up the solution of the today's lead code challenge thank you for watching thank you if you have any doubts you may ask them in the comment section thanks | Combinations | combinations | Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n` | null | Backtracking | Medium | 39,46 |
122 | what's up nerds welcome back to t time with your favorite software engineer so i actually broke my monitor with the webcam so that's why i've been gone so long but i finally got it fixed so i also got a new desk that's why it looks different um so today i'm gonna be going over best time to buy and sell stock too but first make sure you guys subscribe i'm trying to hit 10 subscribers a day i like five so far i also have a slack channel in the description where i'm hosting a lead code competition every month uh with cash prize so it's not too late to join we just started this month november 2020. anyways the description reads say you have an array prices for which the i element is the price of a stock on day i design an algorithm to find the maximum profit we can complete as many transactions as you like can not engage in multiple transaction at the same time so you must sell a stock before you buy it again so if we have seven one five three six and four the only thing we're going to want to do is we're not going to want to buy seven obviously we're just gonna wanna buy low and immediately sell um so when it's higher that is so we're gonna buy one so five minus one is four and then we're gonna buy three and sell it at six um so four plus three is seven and then here um we're gonna want to buy at one and we could sell it two it would give us one and we could sell it three again it'll give us uh one and then we could sell at four again it'll give us one and we can sell at five give us one for a total of four so basically what we're doing is buying at one and selling at five um but you could also just calculate the difference between each of the prices because sorry it has something in my throat because it's getting higher at each uh day so we could just calculate the difference between each of these um and loop through so that's a really easy way to approach this problem so let me go to the whiteboard basically what we're going to do is we're going to have a profit oops profit equals zero and um so we're just going to loop through actually we're going to start at one because we're going to want to check to see if uh if this is higher than this then we're just going to add it to profit it's basically mimicking us selling it um and then we can just buy it back if it's the next day is higher so i less than prices dot length i plus and so here we're going to check to see exactly what i just said if this stock is higher than this stock then we're just going to add the difference between the two to our profit so if prices of i is greater than prices of i minus one then profit plus equals um precision by i and i'm sorry if it's hard to see let me make it thicker verses of i there we go that's better prices of i minus one sorry i like it thin when i'm actually writing for myself i notice you guys can't see it that well probably so if that's the case so we just loop through and then we close our loops and at the end we're just going to return profit so this is just a really easy problem um well i mean it's not i guess it is an easy problem but uh you just got to be able to pick up how to solve it can if you do brute force it's just so much more complex than you really need to make it so and profit equals zero or into i equals one i less than prices that length so like i said now we just want to see if this one is higher than this one then we're gonna add it and this one it's actually not so but when we check this one this is higher than the previous one so we do add the difference so if prices of i greater than prices of i minus one then profit let's just add it to the profit prices of i minus prices so that's the difference between the two and then we just want to return profit so let's run this so that test case works and it's accepted my memory usage is messed up but um so we're actually not using any memory issues so this is uh constant so of one for uh space complexity we're not using any data structures or arrays and the runtime is just oven we're just looping through the entire array once so this is pretty much the optimal solution and that's all i got for you guys if you guys enjoyed the video and learned something smash that like button and i'll see you next video | Best Time to Buy and Sell Stock II | best-time-to-buy-and-sell-stock-ii | You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**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.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104` | null | Array,Dynamic Programming,Greedy | Medium | 121,123,188,309,714 |
797 | hello all uh welcome to another lead code problem so today we are going to solve a graph based problem which is 797 all passed from source to Target so if I read the problem description it's a given a direct graph with nodes and from within nodes level from 0 to n minus 1 when all possible parts are 0 to n minus 1 so you have a graph given where nodes are there and they are labeled from 0 to n minus also lessons around four nodes so if they are labeled from 0 1 2 3 that is and 3 is basically u n minus one and reaches to the end that is your Target that is n minus 1 now so in this example if you see that so since it is a directory graph so there's arrows so you can drive some zero to one but not from one to Z and then you can see here you can go from y 0 to 1 and 1 to 3 so that is one path I will not be here and then you can also perform zero to two and two to three so this is another problem so that we have to return and the data section is like that you have to you have a list of lists so a Zero's position you are given one two that means zeroth node 10 these two one and two nodes that is zeroth node can reached to one and two more and that first position can reach to three so first is 23. three and the last version that three is cannot go anywhere so there is no uh oh there's no Edge there's no path from uh three so this that's what is empty okay so how do we solve this problem so in order to solve this problem I'm going to use uh a DQ well I'll keep pushing well when I start the DQ traversal I'll start with the node 0 since we have to start with the node 0. and in this node 0 uh when I'm start uh I don't have any paths so only initial pass only will be one so that is my first base condition so this is I'm going to push into my DQ okay so now I'll have a look where now I have to do a best sources and I keep reversing so from 0 to node what are the path available so I can see that one and two so that's from the list if I go and extract zeroth position so I have one and two as a path available for zeroth note right now what we can do is I'll do a traversal and then I'll just run the DQ I'm gonna pop out the first element which is there the element which is there in the D key so uh now if I pop out this one so see I'm gonna get a zero and then this one so that's basically your node and into the part current part now for the zeroth node and to find what are the next node available I think it I think Traverse from zero so if I look at the list so I have one and two as a possible node so what I am going to do is I'm since I can reach one and two so I'm going to append this path into the existing path node and then I'll push this nodes into the D key so since I can just reach 1 and 2 from 0 so what I am going to do is in the DQ I'm gonna push 1 and then I'll um increment the existing path so in this one part I'll add the another note which is one and then same thing for two that is 0 and 2. so now my DQ has two elements now so this is going to be a kind of a triple uh I'm going to push into DQ so now I have reached one and there are other these two now again I have to do further but I have not received my target note because my target node is three because I'm looking for n minus 1 right which is three so now again I'll explore the first node because that is my uh that is into my DQ so I when I pop again DQ so I'm gonna get 1 and 0 1 so if I just go up a little bit so now if I pop again so I'm gonna get one and zero one which is a my path now you can further explore the one based on the link uh the data structure that we got so one can go to the third node right so I'll again push a new element in the DQ with the third node and the path will be 0 1 and I'll add three same thing I love and pop to from this particular node I can reach to 3 and then I'll increment the path list and add sorry Pathways and add three here now both element that is one and two elements popped up so nothing left from this but I added two more elements right that is three zero one three and then 3 and 0 to 3. so when again I pop up this element I see that this is my target element right Target element equals node in this case I'll add this path into my result set same way for this also I'm going to add into my result set because once I pop up here I see this is my target element so whatever paths so far I have Traverse that is going to be my researcher and at the end this resulted is going to be my final result so let's look at the code it's a code uh as I said I need to find the what is my target so that is going to be length of graph minus one so in this length of graph is 4 minus 1 that is the target note that I'm looking for and there I am starting from zero so that's why I initialize the first node is 0 and then so far since it's a base condition so base condition I'll add 0 as in the path itself if I don't add then only I'll get is one and three and two or three because but I have to start from zero so I'll add 0 so and then in this result I'll be returning the path that I have done so once I start reversing the DQ so when the pop out this element so 0 to be my node and this is my goodness node is not equal to Target correct because HTM as zero question now I am going to explore the graph so for the zeroth now what other for this zeroth node what are the nodes I can reach so in this case I can reach in one and two so I'll add this one and two into the DQ that is the node that is one and then append path that is your zero plus one and this increase for this version and then this value again continues it will pop out the first element in one and then same gives who else for the two and then it will keep doing it and after that when it reaches to the Target node it will add in the result and the result will be uh return to the function so if I run this it works fine for the board test cases you can go ahead and submit this all right thank you thanks for watching this video hope you like it bye | All Paths From Source to Target | rabbits-in-forest | Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**. | null | Array,Hash Table,Math,Greedy | Medium | null |
1,894 | hey everybody this is larry this is miko with q2 of the biweekly contest 54. uh find the student that will replace the chalk hit the like button hit the subscribe button join me in discord if you like it um if not that's fine too but you know i got nothing to say about that one uh okay so for this prom you know you may be tempted to do a simulation and a simulation means that you just you know go through the loop keep on subtracting until you're done uh the key thing to note though for that is that you look at constraints and k is equal to 10 to the ninth so that means that if every element is one it's going to go for each it's going to be a lot of pain right because if you're tending i mean it doesn't matter how many elements as long as you know um if you go through each element you know one at a time and it's ten to nine times it's gonna be pretty slow so then the other thing is that you know you try to find an invariant for this problem and this invariant is that the truck the number of chalk needed for each loop doesn't change so and because it doesn't change you can just simply take the sum of it and then just do some math around on that math but uh um yeah so then because you don't need to know how many loops it you know but you know that you're subtracted you know you're doing a repeat subtraction of the sum and that would speed things up a lot of course uh and of course if you know you're making that leap the next one is just the mod operator uh which is what you do when you think about repeated uh repeated subtraction or division i guess but the other part of it because you want to know what's left over and then after that it just becomes a simulation this is pretty much defined in the problem so it's just writing what the problem tells you to do and of course because you only go for the array uh the linear way twice one wants to get the sum and want to do this is going to be linear time in total uh and yeah and in space we don't use it's all one extra space because well i mean you look at the code right um that's all i have for this one i think yeah let me know what you think let me know if you have any questions you could watch me cyber lived in the contest next know so oh okay so i might be wrong oh hope i'm not off by one okay really worried about that one to be honest | Find the Student that Will Replace the Chalk | merge-strings-alternately | There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student number `0` again.
You are given a **0-indexed** integer array `chalk` and an integer `k`. There are initially `k` pieces of chalk. When the student number `i` is given a problem to solve, they will use `chalk[i]` pieces of chalk to solve that problem. However, if the current number of chalk pieces is **strictly less** than `chalk[i]`, then the student number `i` will be asked to **replace** the chalk.
Return _the **index** of the student that will **replace** the chalk pieces_.
**Example 1:**
**Input:** chalk = \[5,1,5\], k = 22
**Output:** 0
**Explanation:** The students go in turns as follows:
- Student number 0 uses 5 chalk, so k = 17.
- Student number 1 uses 1 chalk, so k = 16.
- Student number 2 uses 5 chalk, so k = 11.
- Student number 0 uses 5 chalk, so k = 6.
- Student number 1 uses 1 chalk, so k = 5.
- Student number 2 uses 5 chalk, so k = 0.
Student number 0 does not have enough chalk, so they will have to replace it.
**Example 2:**
**Input:** chalk = \[3,4,1,2\], k = 25
**Output:** 1
**Explanation:** The students go in turns as follows:
- Student number 0 uses 3 chalk so k = 22.
- Student number 1 uses 4 chalk so k = 18.
- Student number 2 uses 1 chalk so k = 17.
- Student number 3 uses 2 chalk so k = 15.
- Student number 0 uses 3 chalk so k = 12.
- Student number 1 uses 4 chalk so k = 8.
- Student number 2 uses 1 chalk so k = 7.
- Student number 3 uses 2 chalk so k = 5.
- Student number 0 uses 3 chalk so k = 2.
Student number 1 does not have enough chalk, so they will have to replace it.
**Constraints:**
* `chalk.length == n`
* `1 <= n <= 105`
* `1 <= chalk[i] <= 105`
* `1 <= k <= 109` | Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards. | Two Pointers,String | Easy | 281 |
791 | hello everyone so I'll be solving a medium lead code problem today called custom sort string so let's read the question first you are given two strings order and S all the characters of order are unique and were sorted in some custom order previously so we are given two string order and S and it says that order has unique so that's an important point to note that they are unique characters so there isn't any repeated character over here and then next it says is permute the characters of s so that they match the order that order so this order string was sorted more specifically if a character X occurs before a character Y in order then X should occur before Y is in the permuted string written any permutation of s that satisfies this property okay so what's trying to say is that we are given two string order and S so order dictates so you know how in normal alphabets we know a comes before b comes before c Lex lexico graphically so same way there this is this custom there is this uh string order which is custom sorted so just imagine that now in this case C comes before B and B comes before a and that's the order that's the New Order which uh order string defines and then s we need to rearrange s such that we are following this order right and then it also says that okay it also says that if it matches then it should essentially match this order if there are extra elements we can put it anywhere right because it says over here in the example it says that since BCA already exist in order so it's uh sorted BCA and since D is a extra uh character it can be put anywhere else that's what it says that since D does not appear in order it can be put at any position in return string so these are all accepted string we can put D first we can put second we can put third or we can also put it at the end as it does over here right so it's pretty clear right so the only thing is that we need to follow this pattern whatever this uh custom sort is we need to rearrange s so that it follows that pattern and if there is a extra character you can put it anywhere that's uh I hope you understand this so what we will be doing in this case is one important point we need to noce that over here the um sorting really matters or the order in which the character occurs is very important so we need to store it some way and one of the easier way to store that piece of information is essentially making a map right so if we uh make a map and we for every character we note the index of it so that's the simplest way to do is hey I'm going to assign c as z b as one uh as 2 so that way I'll know that c comes before b comes before a right so once we make that map we can use that map to actually rearrange it and uh create a new string out of it so let's see let's do the first part of it which is store the uh indexes of this uh per character in the string so let's just say um let me make an ordered map first where we will store this piece of information so that would be sh map with int and we'll just call it as index right and then when we'll iterate in this string order and then we'll store all the U indices of all the characters so in IAL to zero and I'll go till uh order. size so the end of it and then we'll keep on increasing until we reach the end and over here I will just say order whatever that character at I position is and then I'll just assign it I right so now uh C is assigned with zero B is assigned with one a is assign with two and so on and so forth so once we have that now what we need to do is we need to use that map to recreate the string right so for that right now I chose unordered map because the sequence doesn't matter right all we need to hold is that every character should be mapped with a index that's all we want we don't care if B comes before like in this particular uh container we don't care how they are formed right but in this string s we will care for uh for the sequence of it right so one of the best ways is to actually use map but in this case we'll be using multi map right I'll show you just in a second why I'm using a multi map instead of map so okay now I will be using this piece of information to know which character comes before which character so that's why I'm creating a map from into to char and the reason I chose multi map is that there can be repeating uh alphabets so in that case I need to have a container which can hold it should be a map but it should also hold not just unique values but two key can uh have multiple uh same value so that's we will only get that property in a multimap so that's why I'm just using multimap and then I'll just name it m and then I will iterate in string s so I'll be iterating in string s so I'll just say s and then I'll call okay so now what I'm going to do is if I'm going to check if this already exists so I'll see if the particular character already exist in order then we care about it if it doesn't for example in this case d does not uh happen to be in order so we can just put it anywhere so I'll just use this uh condition that if x. find so idx doind if I find this particular a dx. n that means we actually found it in our uh unordered map that means it exist in that case we want to store it right so let's just say m do insert and then we will be inserting where that position of uh this character is right in this particular map so it's going to be idx of a right and then we're just going to insert a as a second uh as a value right so once we have that then else so in else case we'll be encountering or we'll be handling the case where the this particular character doesn't even appear in order so as we as I initially told right it we uh if it doesn't exist in order that character we don't care we can just put it either in front at back or any other index so that's my personal decision I'm going to put it at front because that's easier right because on zerth uh position I can put it so instead of how it uh in the given example the D is appended at the end I'm just going to do it in at front just because it's very easy for us to do it right so I'll just say m do insert the value over here would be the position would be zero and the character is a now just think about it if I'm doing zero over here so I'm already using the zeroth position for this particular uh character I actually need to do 1 plus this so that I'm actually not looking because this is actually zero index so a c as told it would be assigned to zero B is 1 C is uh two but now since we are I'm already appending D at the first one or any character which does not exist in order like at the first position now I need to actually shift it so it's going to be 1 plus right and once I have done this now we know that in multim map we are storing the position and multim map already sorts so now I know that this particular string is already sorted according to the order of uh the string provided so now once we have that now all we need to do is build a string right so how we can build a string it's very easy I'm just going to itate key value in multimap which is M and then I'm going to find okay I also have to actually create to string variable answer which I'm going to initialize with a null string or like empty string and once I have empty string I'm going to just keep on appending so answer plus equals to B right so every time we are we will be going in this multi map and since this is already sorted right the I'm using this property of multi map which gives us a sorted map and why I'm using multim map rather than just using a normal map because I can also have multiple values what if there is uh a b c d right when there are multiples I need to also store that multiple key map to a same value and that's why I'm using multimap instead of map so once we have that so what this for Loop does is that it will rearrange it would be actually d CBA right d because D does not exist in order and that's why I'm just using a index zero because that's easy right any character which does not exist in order I'll just append it or like I'll put it at the FR front of the string and so my string would be very different so if you see over here the output is dcba not CB a d right because D is the character which does not exist in order and that's why I just inserted it the first so and it's it also accepts right that as it says that it doesn't matter if there is a character which does not exist in order you can put it anywhere and that's why I just St it at zero so okay this first case passes let me submit it uh what did I miss oh okay I think I did not return the answer let me just see answer try run it runs and let's submit it all right so it got submitted right so that's the solution for this problem I hope you understand if you don't just put whatever question you have in comment section I'll take a look and I'll try to respond as soon as I can but this is um medium level problem and it's pretty easy right if you once the only trick is that you have to use two maps right one is unordered map and the next time you have to actually use multi map so that you actually rearrange and it automatically does it for you since I'm already using multimap it just rearrange and just have the index according to whatever the indices were initially stored so it's pretty uh good problem to solve I hope you understand this problem I that's it for this video I'll see you in the next one thank you | Custom Sort String | split-bst | You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**. | Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right. | Tree,Binary Search Tree,Recursion,Binary Tree | Medium | 450 |
228 | welcome to october's leeco challenge today's problem is summary ranges you are given a sorted unique integer array nums return the smallest sorted list of ranges that cover all the numbers in the array exactly so for instance if we had this example here we're going to return zero to two because that covers zero one two in all the range then four to five and then seven because seven doesn't have a range um here with zero two three four we can see that we're gonna return zero and then 2 to 4 and 6 and then 8 to 9. so how we solve this well i'll show you how i did it say that we had this example right what we're going to do is store three variables we'll store the start the end as well as the current pointer so what i mean by that is we'll start with initializing two points we'll say this is going to be the start and this will be the current and we'll both point these at zero right now what i'll do at first is have nd going to none and when we move on to the next one we're going to increase our current pointer to one and we'll check hey is this number equal to the current point that we're on right now and it is right we can see that one equals the current point or one so then we'll update our end range to equal one then we'll increase our pointer to two move on uh we'll see that two is indeed equal to the number right there with current so n equals two and once we see that hey no it doesn't equal um the current point or equaling three doesn't equal that so it's no longer in the range we have our range here zero to two and we will output that out now once that's finished what we have to do is uh reset our end to equal none and our start to equal the current number that we're at four and we can just move on um increase our current pointer to the current point right now four and then we can just check the rest all right so that's how i'm going to do it let's see if we can code this out what we'll do is we'll have the start the current and the end start is going to equal num0 same with the current pointer num 0 and the end at first will equal none now what we'll do is say four n and nums from the very first number or sorry the very second number uh we are going to first increase our pointer to equal one and we'll ask hey is this current number is equal to our current pointer because if it is uh then all we do is set our end to equal the number that we're on right now otherwise what do we do well it depends right it depends on whether we've found a range or whether this number is like on its own so if not end then we'll have to just output a string of the current number uh and i should say i'm sorry not the current number the start um and we'll also see here yeah that should be it and otherwise if we have both we are going to append a string of the start plus this arrow sign plus the string of the end now one quick thing to note once we find that this current number that we're on is not equal to our pointer we need to reset everything otherwise this current pointer is going to get all wonky so we'll have to reset start to equal n the current to equal n and n equal to none now one problem with this algorithm is the very last number it's not gonna because we put the current point up here it's not gonna add this um last range so what we'll do is just add that at the end um this isn't really advised but it's a trick that i used to do quite often when i you know the data engineering so that should be it let's see if this works um this should return oh i gotta first initialize our output off and i just realized i need to take care of the empty edge case as well okay so look there we go 0 2 4 5 7 looks like it's working let's also check if not nums there's nothing in there we'll just return an empty list and let's go and submit that and accept it so time complexity wise this is of n and it's going to use constant space because we only have these three variables now there are better ways to do this is but not more clever and efficient ways to kind of do the same thing but you know this worked and i think this was most self-explanatory so i'm just gonna most self-explanatory so i'm just gonna most self-explanatory so i'm just gonna keep it alright so thanks for watching my channel and remember do not trust me i know nothing | Summary Ranges | summary-ranges | You are given a **sorted unique** integer array `nums`.
A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive).
Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,2,4,5,7\]
**Output:** \[ "0->2 ", "4->5 ", "7 "\]
**Explanation:** The ranges are:
\[0,2\] --> "0->2 "
\[4,5\] --> "4->5 "
\[7,7\] --> "7 "
**Example 2:**
**Input:** nums = \[0,2,3,4,6,8,9\]
**Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\]
**Explanation:** The ranges are:
\[0,0\] --> "0 "
\[2,4\] --> "2->4 "
\[6,6\] --> "6 "
\[8,9\] --> "8->9 "
**Constraints:**
* `0 <= nums.length <= 20`
* `-231 <= nums[i] <= 231 - 1`
* All the values of `nums` are **unique**.
* `nums` is sorted in ascending order. | null | Array | Easy | 163,352 |
260 | hey everyone welcome to lead code 260 single number three so we'll be given an array of integers in which all numbers appear twice except two numbers that appear only once we have to find these two numbers and return them for example in this particular array the numbers that appear only once are three and five so we have to return these from the function this does not seem like a hard thing to do we could sort the array and compare the adjacent elements or maybe we could use a hash map to count the number of times an element occurs but the constraints given to us state that we have to come up with an algorithm which runs in linear time and uses only constant extra space sorting runs in big o of n log n time and using a hash map would require big of n extra space so we have to come up with another approach this is where bit manipulation comes in let's take another example the unique numbers here are 5 and 3 and let us write down the binary representation of each of these numbers all of these numbers fit in four bits so for the sake of simplicity i'll just write down four bits here all the remaining bits will be zero now let us compute the bitwise xor of the entire array the xor operator gives us one if both the input bits are different and it gives us a zero if both the input bits are the same when we compute the bitwise xor of the entire array by performing xor of the numbers one by one in the final answer the last bit of the xor will represent the xor of the last bits of all the numbers similarly the second last bit of the xor will represent the xor of all the second last bits of all the numbers in the array and similarly we get the second and the first bit like i said the xor of two bits is one if the two bits are different and zero if the two bits are the same so for multiple bits if we have an even number of ones like we do here the xor is zero but if the number of ones is odd like we have in the second place then the xor is one what we'll do now is that we'll choose any set bit from the xor of the entire array that we have just computed we can select any set bit and there is guaranteed to be a set bit we'll never get the xor output as all zeroes first let's see why it is guaranteed that we'll have a one bit in the xor so we know that the xor of a number with itself gives us a zero now since we'll iterate over the entire array this eight and this eight will eventually get cancelled similarly this 9 and this 9 will cancel each other and this 7 will cancel each other so the xor we're left with is just the xor of the two numbers that appear only once and this xor cannot be zero since the two numbers are different from each other and they cannot possibly cancel each other effectively the xor of this entire array is just 5x or 3. okay now that we have the guarantee that there will be a set bit in the output xor we'll select any one of the set bits just to keep things uniform let's go with the least significant set bit since the xor of the entire array is just the xor of the two unique numbers we know that one of those numbers will have this particular bit set as one and the other will have it as 0. here 5 has this bit as 0 and 3 has it set as 1. and both the unique numbers cannot have this bit as the same value because if they did then it would have never appeared as 1 in the xor now we'll try to use this bit to get the numbers let's divide the array into two groups group 0 and group 1. group 0 contains all the numbers which have this bit as 0 and group 1 contains all the numbers which have this bit set to 1. note that i am making these groups just for explanation in the code will do all of this within constant extra space great now if we observe we see that all the numbers in group 0 appear twice except one number which is 5 and similarly all the numbers in group 1 appear twice except 3. for both groups we just have to find the number that appears only once in that group and we are done we'll have the answer which is 5 and 3. you may have already done this in lead code 136 which is single number so we just simply take the xor of all the elements in group 0 the elements appearing twice will cancel each other and will be left with the unique element in group 0 on taking the xor 8 and 8 cancel each other and 9 cancel each other and we're left with only 5 and we do the same thing with group 1 the 7's will cancel each other and we'll be left with the three we can just return x0 and x1 in the answer alright so now let's write the code for this i am currently in visual studio code but i will run this on lead code in the end so this is the code we are given to begin with let's create a variable to store the xor of the entire array we'll initialize this q zero i will explain at the end why we are using a long hair instead of an int next we iterate over every number in the nums array and for each iteration we set x equal to x xor num so at the end of the loop x contains the xor of all the elements in the nums array now we'll create a mask for the least significant bit of x a neat little trick to get this mask is just to perform the bitwise and of x and minus x let's create two integers x0 and x1 to store the xors of the numbers in group 0 and group 1 respectively we then iterate over the array once again for each number we check if that number belongs to group 0 or group 1. if the bitwise and of num and the mask give us a non-zero value then the number belongs non-zero value then the number belongs non-zero value then the number belongs to group 1 so we set x1 equal to x1 xor the number else the number belongs to group 2 and we set x0 equal to x0 xor the number now after the second loop x0 and x1 contain our two numbers the numbers which appear only once in the entire array so we just create a vector of end containing x0 and x1 and then return it okay now why did we use along here if we look at the constraints given in the problem we see that the numbers can go as low as minus 2 raised to 31. while computing the mask we use minus x if x is negative 2 raised to 31 then minus x will not fit in the integer data type so we use the long data type all right guys let's now run this code i'll copy it and paste it into lead code that's good now let's submit it great we have a successful submission finally let's do a time complexity and a space complexity analysis we have one loop here that runs over the entire array that's big o of n and we have another loop here that runs over the entire array so that's another big of n in total we have big o of n plus big o of n which is just big o of n as for auxiliary space that would just be a constant big of one alright guys thank you for watching please hit that subscribe button it would really help me out a lot like this video if you found it helpful and feel free to leave your feedback in the comments i'll see you next time | 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 |
212 | hello guys now it hurts of the word search to profit let's see the province statement give a 2d boat and a list of words from the dictionary find all words in the port each word must be contracted from letters of sequentially agency sell well agency cells are those horizontally all virtually never there same letter cell may be may not be used more than once in words as either words the bird I put eat and oars you must not all in products the lowercase letters A to Z is where we have many words and a one word we definitely can search one word one time but the time complexity will be very high so this is a stream relational problem so we will think about the try their structure how do you take use of try in this situation well as we have tried so we can prove this backtracking um procedure for example we iterate the whole matrix and if I find this is exist in the try node so which is a root children yeah we will keep searching if and see if we term there the whole word is exist in this port in the case we will save time and once we search we will find in though also we will enter the string equal to none and we will prevent Azure duplicate things so basic this approach eight backtracking and we used to try to save time to do the true from me there yeah I want you to say that true yeah okay so let's get another yes they're here neither is out with array list and then s catcher if the board equal to now or the board don't less equal to 0 we simply turn this out then we need a try so we will use a totally try node and the we will then we will search the board in the I go to 0 unless them for less i plus the for inter j0j left M board $0 j plus the for inter j0j left M board $0 j plus the for inter j0j left M board $0 j plus if yes because we are first try in the try if in a travel cheaper to the DFS thing the finally we return the Rita this is the basically structure now we treat first so we need a try no and as usual we need children and this case we do not need is word we just need a word because at last we should return no strings so we should turn you save the word it later either work and the children will be new try 26 more there the first search for the pizza no ok this is a try node and there we should our New York and we will pass it into the future trial route we also need the words mr. Hemant is enough we will write to the boy yeah under the stream of the word okay because every word in the world and also the for-loop the curved word equal also the for-loop the curved word equal also the for-loop the curved word equal to the street and we keep I do it's easy I finally will build these to try okay and what is the condition we already have the root right and if the root children never again first against the truck which is odd i J yes if the root children see - a i J yes if the root children see - a i J yes if the root children see - a is not in which means we have a final first two carat in the weekend we can do the gift f DFS search to check if the whole street is containing the truck so private avoid the effort let's see what pyramid do we need well basically we have needed a board right we also needed a position over this is a current character because we shouldn't move either horizontally or vertically and though we also needed try note which is a current try note um doing it NEC yes we should pass the resulting sugar kosher okay let's try to write it um let's first check if the other bounder I less than there okay this is the one case yes you got it if border I J equal to shop we return why because that's you will see if I do this I will ne the picture because we do not want to return back he said actually saves the extra space we will not use another 2d array q as a vegetarian Somali change their tutor Shabbat you indicate that we have it shipped and uh if curve if Curt well we have another kept pushing through the board i J right okay and they've the courage holder and the e minus a equal to not really have the containing the English I will just return else will lead to them mmm is the one case and now I get if the curve word not equal to now we have funding to write so we should add it into our final result so we added a current word then do not forget to set it you know because we do not want to add duplicate into our result and we will sell to the board I J we go to the shop because we don't want Vita again then we do the five directions sir deficit I trust one J curry for two children see yes is um yeah actually we can easily write is heuchera equal to Curt children C minus eight right moving it down right so yeah so this case we can just write Kirk and the result and ef-s fold ef-s fold ef-s fold I'm s1j her without the FS hi J plus 1% I'm s1j her without the FS hi J plus 1% I'm s1j her without the FS hi J plus 1% the result yes old i J nice one result and finally do won't do not forget your aesthetic because it's a backtracked we aren't choosy we return oh we resonated to the sea okay so we fill this permit both IJ and the Tri is the route and the result yeah I think we have finished the state well this seems right okay yeah okay we have finished and they're not bad thank you for watching happy coding see you next time bye | Word Search II | word-search-ii | Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique. | You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first. | Array,String,Backtracking,Trie,Matrix | Hard | 79,1022,1433 |
435 | welcome back to outgod.js today's welcome back to outgod.js today's welcome back to outgod.js today's question is elite code 435 non-overlapping intervals non-overlapping intervals non-overlapping intervals so you're given an array of intervals where interval i is equal to start i and i return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping so the intervals non-overlapping so the intervals non-overlapping so the question is self-explanatory it's pretty question is self-explanatory it's pretty question is self-explanatory it's pretty intuitive so we just need to return the minimum number of intervals we need to remove in order to create an array where there are no intervals that are overlapping in the first example we need to remove one three because there is an overlap between one two and one three as soon as we do that we have no more overlap so as you can see one two ends on two three starts on two so that is not considered an overlap and then two three and three four are not overlapping either in example two we just have an array consistent of one two so we need to remove two of those in order to create an array where there are no overlapping intervals so how would we go about solving this well the first step is to always sort the input array and we are going to be sorting this by the second values within this rate so we're going to have a sorted values that look something like this so these have now been sorted and we can map them out onto our diagram now say we start at position one within this so we're going to start at position one so this value we'll call this current so we'll have the current value we'll have a start and end point of previous as well so we'll call this one previous and in order to see whether there is an overlap here we compare the last value of prev so the end of pref with the start of current if there is an overlap then we need to keep some kind of track of how many times we find an overlap so we're going to have account variable which is going to be set at zero and every time we find an overlap we're just going to increment that so at this point as we stated in the question this is not considered an overlap so when it's not considered an overlap we reallocate prev to current and current to the next value within the array okay so this is going to have start and end is current start less than prevent it is indeed so we can increment count here and we can move along so we update current to here stays here and then we look at prevent with current start and we check to see whether there is an overlap there in which case there isn't so we move along and as you can see there's nowhere else to look so we just return count so the reason why we take and sort by the second value within this array is because say we had to say we had an input array like this if we map this out and we ordered them via initial values so say we go up in 10 so say we ordered this by initial values we're going to have 1 100 111 212 and 11 22. so this is going to be our sorted array okay so if we map these out if we follow the same solution as we did above we're going to compare say we start off at index one we can compare current with previous so current start is going to be compared with previous end so is current start less than previous end yes it is so we increment count so count is going to go to one right and then we move this along so we move current up here we compare it to start current start is less than prevent again so we increment count to two and then again we are going to increment count because there is an overlap there as well and we have an output three but the actual answer to this is two there are only two overlaps and i'll show you why so with this initial input say we ordered it by the second values so we're going to have one and eleven we're going to have 2 and 12 11 and 22 and 1 and 100 this is going to be our sorted array that we're going to prove so as you can see it's in reverse so if we run through this quickly so we're going to have current here forever here compare prevent with current start there is an overlap here so we can increment count we're going to update this so current's going to move up here is there an overlap between current and previous here so current start and previous end there isn't here so we don't increment counter in this case we just update previous to current and we update current and then there is one more overlap in this case so this is incremented to two so that is the final answer so we always need to make sure that we sort this via the end values so time and space analysis time is going to be o n mark n because that is what is required with sorting and space in this case is going to be o 1. so initially we need to sort intervals via their second value so taking a and b and it's going to be a1 minus b1 so that's sorted the intervals by the second value then we need to create a count variable which is going to increment every time we find an overlap and we need a previous which is set to zero so we're going to loop through this array starting at one i is less than intervals dot length i plus let's say that current equal intervals at i to make this more readable so if current at zero so current at start is less than intervals prev at end so it's less than previous at end we can increment count else what we need to do is we need to update previous to i okay and then it's just a simple case of returning count so let's give that a go submit it and there you go | Non-overlapping Intervals | non-overlapping-intervals | Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104` | null | Array,Dynamic Programming,Greedy,Sorting | Medium | 452 |
140 | hey what's up guys Chung here so today let's talk about this is problem number 140 a word break - yeah this one is 140 a word break - yeah this one is 140 a word break - yeah this one is marked as hard yeah I would say it's between the heart and the medium yeah it's not that extreme hard but it got some tricky point and you need to think about so okay so let's take a look so you'll give it a none in empty string s and the dictionary word dictionary containing a list of and then non empty words and you need to add spaces in s so that uh so that out the words you got after adding the spaces out in the word dictionary and you need to return all the possible sentences here for example this one you can add like space and the cat and cats and the underdog and yeah right so that you have three to two results here same thing for this one pineapple yeah pineapple right so you add here and here you have basically you have three options here and for this one basically you can write basically if you add cat here and then send the an OT right basically no matter how you break this words there's no way out other words are in the find that word dictionary so in this case you just return empty right so how do you I mean think of this kind of problem right so I think intuitive way will be we just start from the beginning right let's say we start from the beginning and then we just check this okay so we try to break right so for each okay let's say for example this one we see a cat here right we see a cat and then we see a cat is inside the word extreme then we know we finally find out like a word and then the problem is how about the rest of the string here right so once we have cat here we have the red string here so the restaurant in sand dock right we need we want to know with the current word cat removed from this from the string can we have a valid like results from the substring well if there is how many of them right and so that will lead us to a recursion to a recursive call right basically so once this is once we find a cat here and then we which pass the rest of the string to this recursive function method itself right and in the end so this recursive function will return like all written what will return with current ass write with corn ass what are the possible a word breaks we can get with a corn stream right and then once we have this part we basically which is simply for each of the possible result return from this recursive call we add this cat at the beginning of that list right and then we just pass it along right pass it back so that's how we do the recursive call okay I'll try to write this so we have a cat's right cat send sent doc right so the first one we find is the cat right so and so the left side does this cat right so this is a cat and then what about the other side that's a as a and the do G right so since they already have a word here then we just simply leave it here right and then we look at stand here right so how about stand then with the same word since we're doing a recursive call right and then for the stand send dog well we'll still also start from beginning if an as a and D okay so I Cindy well I Cindy is in the it's in this so we're gonna have a lot like another that's a and D right just to remove from the string right and then we're gonna have what this is like the previous right previous and then we're gonna have a talk here so here we got a talk yeah and this one okay see oh so that's so at this moment we're gonna have a like another start another like a recursive copies it should be the string talk right and then we with a string talk we see oh we find a talk right then we'll go just like this one we're gonna find a talk right that's the word right we that's the word we find from the recursive call and then the this one's gonna be empty right in this case so this one is empty string right so that's when we reach the end after the recursive call right and this one let's see what we have a so one thing to be notice here so once you see of empty string here you need to return like a empty array here so that when we do the drawing I so remember well every time when we find a we find that like card number and we have this bill to a recursive call this recursive call will give it will return us an array right the rate has the other possible combinations we can get from this current string if it's empty then we need to return like an empty array here so that it can be it can a form a valid result with the start here right that's like basically idea so for each result returned from this from the previous recursions we just add the stand at the beginning and which is recursive return it right we add right then recursive call we add that's how we get the final results right so because since we are doing this like since we're doing this every time right when we do a card here we're doing a for loop right basically inside what every time we have a string here we do a for we do put from the beginning to the end we try other possible streams to see if we can form like a valid like a word break with the current string with the current word and the remaining strings right and then yeah then let's take a look at this one right this the cats and then dog so in case we cannot form anything how can this one are guaranteeing that we'll have an empty right and okay so for example let's say let's see there's like dog let's say the dog is not in the let's see the dog was what did I do let's see the talk is not inside the word dictionary right for example and then at this stage right at this stage basically will not be finding this like will not find this one basically when we loop through the D o and G we never find out matching world right so that's but basically that's when we will just a stop we'll stop the basically will not be returning like a array of empty array basically what is returned like empty list with nothing inside there so that when we when this one when this recursive car goes back descend trying to find anything inside this return the lace it finds nothing right so that basically what it's not going to join create another modern valid string based on this recursion call and then this one goes back here and in that case this is pre disliked recursion call also BM empty and then that's why that's how we get is empty in the end okay so let's try to code this thing here let's say this is like the backtracking concept here so we're gonna have to find a backtracking method right backtrack right with the string right and then what and D uh let's see hmm backtracking okay if right like I said if not ass right if as it's like empty then we need to return like empty of empty string right because in the end we're gonna so let's say the current words right the current words what's the current words right and let's see so the car know where it's gonna be a array right and we just do a for loop right for character in ass right we loop through the character from beginning to the end right and then what do we doing a new word right and let's define a variable here this new word that's the ass - oh yeah actually so I need a ass - oh yeah actually so I need a ass - oh yeah actually so I need a neither index not the value itself let's range right nice ass here so and basically we cut out the words until this I here right and then we check if new world a new word is in the oh yeah so this is a small trick here so every time you word list a list type and he want to compare you want to do a the chair doing a in trail in this one it's always a good idea to convert this like word list to a work to a set that will speed up the to look up a lot because if it's a list the time to look up a annamund from the list it's all ending right but with the sad it's going to be a it's going to be one so it's constant time so we do if this one is in the word set right and then we just which need to pass the rest string into the recursion car right we're going to define another variable here I would call it rest the word breaks right I think this is good enough to backtrack right backtrack gonna be ass from I plus one right starting I plus one to the end after of the world of this string here right that's how we do a backtrack here and right and then for each write for each the world rest for each word break we got from the from this recursion call right word breaks right we are we need to basically we need to append this thing after this new world right so and then we are adding able to tour current to our current like word breaks current word breaks right a pendrive appended to the current work break so Harvard doing a pen so we're gonna since this thing is gonna return like a list write a list of a list yeah so this word break is a list of word right oh god got separated by the red space so we need when we do a we cannot do a pen here right because the apparent we need this new word at the beginning right otherwise the sequence will be reversed so we can use a small trick here so to instead of using a panel we can either do a cue to use a cue in here or we can just do like do this right to a new word we put it inside here when we convert this in your word to arraign right and then to a list and then we add that to the rest of after of the list of words in this case we're gonna have like a new list right so that's that okay so and then in the end of this thing we what we do right we return right which is simply return current right the current word break right so basically this the current word breaks will have the or give us all the possible other possible like breaks which the current ass right remember here so we have a s we have four dopey right basically we are looping through all the possible words from this ass and then with this which this like a new word in my separated from the string which are okay so if the remaining strings can give us a valid arrest word work breaks if it is which means if there is anything returned from this backtracking recursion function we will be basically we add this new word we already have with the rest of the with each one of return from this backtracking master in the end we add this one to the will append this one to our current records right so here backtrack ass right so we return basically we can return this is going to be the word breaks right where it breaks equals to that right but India remember in the end so right now currently this word breaks is a list of lace but what we want is the is a list of string right so we can simply return like to adjoin right join by that by the space right join forward break right Oh since we're returning like a array at least here in caps break okay for right forward break in word breaks right that's how we basically it's just simple for loop here and we added to erase this is like a simple way of writing in Python otherwise we can just have another for loop and then for each world in this one which do it this one we assign it to at least a variable it's just like an easier way to write it in one line here okay so I think that's the basic of this problem but I think but if you guys look closely there's a like a drawback of this solution we are doing a for loop on each of the ass right and for each of the ads let's say we have a this lets it as equals to a right and then no it's like a AIAA right and the word dictionary is like it says AAA and a all right so let's say we have a long list of a here right so in that case right let's say we loop through the wheel loop you know what let's say there's like another one here sorry there's a like another like word dictionary it's called a and when we loop through the word diction here so we cannot have League like so we'll be finding a right so two aces in here and then three threes also we're gonna have 3 a's right and then we'll keep going into this loop basically we'll find three words in the first four loop right AAAA and at the seven days and for each of them right will be divide this one will use the new word and it will pass the rest into the backtracking so the rest in the backtracking will also become consider consisted of the of all the a's here right so we are basically we are processing this the same strings over and herbs for many times right because when we look at this one look at the rest of the string there Oh a and we'll be looping through those aids one more time and then we found a again a 3o years and the 70s k again we will do this over and over right that's kind that's basically waste a lot of time so the easiest fix will be I will just simply do a memorization right with a recursion call alright so what do we just define like I'm a man dictionary right miss the you can do this we can do like addiction right so every time right before returning to the returning which save the current so basically this memory our dictionary will store for current at the key will be the string ass and the value will be a list of Lists basically this one tells us for this string as what are the possible break words it can contain all right the possibilities for the breakout of words so write as equals to current word write breaks and so that and then before doing at anything we can just simply check right if as in the man right if it is we just simply return the value we have where we had previously processed right yeah that will greatly improve our performance okay I think that's all we need to write here let's try to run it oh yeah one let's see what did I miss here yeah what am I doing here I'll return right we'll return it alright return this thing cool yeah let's try running yeah cool yeah basically that's it right so let's do a quick recap here so the key concept here is the for each of the current we basically will loop through the current ass right loops through the corners every time when we find out a valid word that appears in the word dictionary we just basically pass the rest it has the rest string into this backtracking method and once we get the result from it will pace it would do a cross join right basically for each of the results from here we add our current word to it to construct the new a new word break list and then in the end we'll return this list and the one that we also using this memorization like technique to save the to speed up the code all right and then so if the freedom if this one if there's no valid word break for this string right so what will happen here it will so anyway so India no matter how many valid word we have already find previously at the last level of recursions when we do a for loop right now it will fill up here basically we'll never find whenever find this like new words right basically this new words will not will never be in this were like works at all right so in that case we'll just go all the way down here right to return so whatever great return returning an empty list here right and then this one will go back to the previously caught which is here right then in the previous car done so the next line will come back here and this rest the word breaks will be the one returned from here right no what's the valley which is empty right the empty list and the moment to a full loop basically we're not going in inside this is for loop because there's nothing in the rest word break so there won't be any loop here and so in that case the previous like the previous record the previous recursion car will not add anything to this current word breaks and then it will also return the empty and then it goes down or goes back on until it reached on the top and this will also be empty right that's how the this problem works right okay I think that's it for this problem I hope you guys liked it and thank you so much for watching the video and I'll be seeing you guys soon yeah bye | Word Break II | word-break-ii | Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\]
**Output:** \[ "cats and dog ", "cat sand dog "\]
**Example 2:**
**Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\]
**Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\]
**Explanation:** Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** \[\]
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 10`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
* Input is generated in a way that the length of the answer doesn't exceed 105. | null | Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization | Hard | 139,472 |
1,689 | all right let's talk about partitioning into minimum number of a decimal binary number so this binary number is uh a digit that is either zero or one so uh without any leading zero so uh these are that's a binary number and this or not it's because they are some integer which is not zero or one right so you are given a string and so represent a positive decimal number and then you have to return the minimum number of positive decimal binary number you need to uh need to sum up to them so you are actually about using zero and one uh yes we'll just draw that one so you are basically using 001 to actually add 2n right so uh this is unless so you can use a change in always so you can add 32 to subtract the binary number to subtract the decimal binary number and then two to zero right so how do you actually do it so this is supposed to be straightforward and since we are using the binary number so the base scenario is what from one to the length of the end of the i mean the end of the end right so the best integer we can supply is one right so you cannot have two one because this is what this is not just a banner but this span is one right so you can say 32 minus 11 21 and then you're still going to minus 11 so it's gonna be about 110 so i know okay here is 110 right so i can use 110 for my last binary number and then this will be what this will be zero right so you have to know how many steps you have to go through so this is one this is two and this is so uh this will give you a quick note the problem is what uh if you notice like if there is a bigger number in the entertainment i mean in the streamline you are definitely unsteady i mean the maximum number set this is because if you only subtract twice i subtract twice this binary number uh three d minus one and minus one you have to remain one you are not actually add up to the end so uh so you need if there is a maximum number in the earn you have to have at least a maximum number step so uh i hope you get it so i need a return value so right i mean we hit resort and our return result and then here's a problem i need to convert my own to trolley right and then i will just have to uh find out my individual pins um in now i put the c minus u so i would say okay what is the integer for this one uh basically uh you just keep updating from x this is pretty much it right uh i made a mistake and here we go so submit yeah pretty much it right so let's talk about timing space this is going to be time all of them uh you are checking every single character in the string or the frame and this is going to be a space constant and this is a solution and i'll see you next time | Partitioning Into Minimum Number Of Deci-Binary Numbers | detect-pattern-of-length-m-repeated-k-or-more-times | A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not.
Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._
**Example 1:**
**Input:** n = "32 "
**Output:** 3
**Explanation:** 10 + 11 + 11 = 32
**Example 2:**
**Input:** n = "82734 "
**Output:** 8
**Example 3:**
**Input:** n = "27346209830709182346 "
**Output:** 9
**Constraints:**
* `1 <= n.length <= 105`
* `n` consists of only digits.
* `n` does not contain any leading zeros and represents a positive integer. | Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times. | Array,Enumeration | Easy | 1764 |
316 | hello guys welcome back to tech dose and in this video we will see the remove duplicate letters problem which is from lead code number 316 and the data structure involved is a monotonic stack so before looking at the problem statement i would like to announce about our dsa live training program which is a three months live training course and in this course your commitment will be to solve two to three problems per day and we guarantee that you will improve your interview results and you will definitely improve your conversion rate of cracking an interview so that you can get the best possible package you can using the counter offers now you will also be provided guidance throughout your preparation program throughout the course and even after the course whenever you require and you will be given performance based referrals if you actually perform well if you are done with the assignments then we will refer you to the companies you like and this will involve live doubt clearance as well and we will discuss all the topics from basic to advance in a detailed way now in order to get more information about the course you can contact on our whatsapp only number which has been shown here and we are starting on first week of june now let us look at the problem statement now in this problem it is said that given a string s remove duplicate letters so that every letter appears once and only once you must make sure your result is the smallest in the lexicographical order among all possible results so let's look at some examples in order to get a better understanding now in this case let's assume that your string s is bc abc now according to the problem we have two goals the first goal is to remove the duplicate letters now if we remove the duplicate letters from the given string we might have multiple strings possible so if you can see it is b c a b a c abc and there may be other possible strings as well but all of them must be of the same length which is the number of unique characters now once we are done with the first constraint the second constraint says that we have to take the smallest lexicographical string in our answer now out of all these possible unique letter strings we have to take the smallest one in the lexicographical order we can take the smallest one in this case it will be abc and so the result will be abc in this case for this example now how to solve this problem now let us look at the simplest solution which is possible so if the given string is bc abc then what we can do is we can try to take all possible subsequences that is we will generate all possible subsequences all possible unique subsequences which is the same as the decision tree diagram of the zero one knapsack as we can take two options for each item you can assume each letter being an item and you can either exclude the item or you can include the item so each of the letters will have two choices so if the size is n then you will have a total of 2 to the power n such combination by multiplying all the possibilities right so the second thing which we can do is we can return the lexicographically smallest string as our answer so we can solve this by using the backtracking in order of 2 to the power n time right so this is the simplest solution possible and obviously this will take a lot of time and if you look at the problem constraint it says that n is less than equals to 10 to the power 4 so 2 to the power 10 to the power 4 will be an extremely large number which will actually not pass in our test cases so we should always aim at something less than equals to 10 to the power 8 operations in order to pass on lead code or even in the interview so this is definitely not going to pass but this is the simplest possible solution now what to do you can think about maintaining the increasing order of the string so that all the letters are uniquely included right so how to maintain the increasing order now if you have studied stack then you will know that you can use a monotonic stack and maintain either the increasing order which is the monotonically increasing stack or the decreasing order which is the monotonically decreasing stack now in this case it is about the increasing order maintaining the increasing order and the second constraint was you do not include letters more than once so let's try to maintain the increasing order now if you maintain the increasing order using a stack now what will happen now let's just process the example number one now in this case if you see b the stack is empty so you will push b into the stack and you go to c now c can be pushed over b because b is a smaller letter right so c can be pushed over b now when you see a then a cannot be pushed over c otherwise it will cease to be a increasing order stack right so in order to make it a monotonically increasing stack you will have to keep popping out the elements from the top of the stack unless either the stack is empty or you find a smaller element than a so we will pop out this c and b and then the stack becomes empty so you can push this a on top of the stack now you go to the next element which is b now b is larger than a so you can push b over a and then you can go to c and you will see that okay c is greater than b so you can push c over b now what were the unique letters in this case the unique letters were a b and c they had different frequencies but these were the unique letters so in this case you will see that if you form all possible unique strings or the unique subsequences whatever you can get you will see that abc will be the smallest one and you got the correct answer here which is abc this is completely fine now let's use this technique in order to solve the second example now in this case we will again start with b and so let's push b on top of the stack because the stack is empty now you see that you get a c so c is larger than the top of the stack so you can push c over it now when you see a cannot be pushed on top of c so you pop c now b is also larger than a so you pop b now you can push a into the stack and then you see b and you will push b on top of the stack because a is a smaller element and then you are done with the entire parsing of this entire string and whatever you get you got a b is shown as an answer but you will see that in this case our unique letters are abc so definitely whatever is the answer will definitely contain abc in some order but you see that it is not including the same okay so in this case the answer should have been bca and not a b so this is a wrong answer now what went wrong in this case the problem is that we are just maintaining the increasing order but we are not caring about the frequency of the elements right so let's try to solve that problem so the problem is we may remove something which may never occur in future so we saw in the second example that we were removing this c when we saw this a but since c is never occurring in future it is not occurring in future so i should actually stick with c i should never exclude this c from the top of the stack it should always be present in the stack but we are removing it so we should not have done this in order to avoid this problem we have to track the frequency of each character and make the decisions based on it so let's look at an improved solution which is we will maintain the increasing order using a stack and we will also maintain the frequency of each element and let us try to solve this example which is bcab now in this case when we see b i will push b in on top of the stack then when i see c is larger than the top of the stack so i'll push c over it when i see a i mean whenever i keep including the elements i will have to keep decreasing the frequency of that element right now when i see a then a can i remove a i mean this c from top of the stack so since c is larger i should remove it but then you will have to check if c will ever occur in future if the frequency of c is actually zero then it is never going to occur in future and so i cannot remove it and uh if the frequency is larger than zero then i can remove it okay because i will include it later in this case the frequency is zero so i should not remove it and instead i will push this a over it right and when i push this a the frequency will be zero the frequency of a will be decremented by one now when you see this b now b is larger than s so b will get included and the frequency becomes 0 and in this case the answer is said to be b c a b but you will see that this answer is also not correct this is a wrong answer because the answer is actually bca we should include all the elements exactly once we should not include them more than once so how did this problem come the problem came because we are actually not tracking the elements which we have already included right we are not tracking it so we have to track such elements so the problem is we may include an already including letter i mean the already included letter so the solution for this is to track included letters using let's say a visited array okay so now we will further improve the solution and in this case we will say that we will have an increasing order we will maintain an increasing order uh element stack by using a stack we will maintain the frequency of each letter by using an array and we will also take a visited array in this case i have named it as seen that whether we have already seen that element and included in the stack right so let's process the given example bc a b now in this case when i see b i will push this b on top of the stack because the stack is empty and so i will have to decrease the frequency of b and i will have to also mark b as seen okay because b has been included into the stack now when i see this c then b is actually smaller so i can push this c over it but before doing that i should see if c was already included in the stack so it was not included because it is marked as false so i'll mark it as true because it is now in getting included and the frequency of c will also decrease to zero now when we see a then we will see the top of the stack it is c first we will have to see if a is already included you will see that it is not included because the scene is false here now we will compare it with the top of the stack and you will see that c is a larger element so should we pop it in order to see if we can pop it we have to check if c is going to ever occur in future you will see that since c frequency is 0 it is never going to occur in future so in this case you cannot remove this c and so when you cannot remove this c and if a was never included you have to include a here and then decrease the frequency of a and now you move on to the next element right so a is seen now when you move to b then first thing you check is if b is already included you will see that yes it was true that b was already included and if it is already included i will just decrement the frequency because i have seen this element and i'll just move on to the next element and this is how we will process the entire string and whatever gets into the stack you will get bca and that is your final result so you saw how we transitioned from maintaining an increasing order using a stack and also including the frequency so that something doesn't get removed which is not getting occurred in future and then we also included the visited array which is a scene array in order to solve all our problems right so i hope you understood why we did a combination of all these three data structures two arrays and one stack now the time complexity is just order of n because we have passed this entire string only once and the random access on the frequency and scene array is just order of one so the time complexity is order of n let us now look at the code in this code you can see that the string s is given and i have taken a frequency array which is for 26 letters since the constraint says that s consists of all the lowercase english letters so i have found all the frequencies and then i have taken a monotonically increasing stack and i have also taken the vector scene which is an array scene which will mark all the elements which have already been seen this is the loop which will process all the elements one by one so whenever we see a character we will see if it is already included into the stack so if it is already included into the stack i will not process it i will just decrease its frequency and continue to the next item of in the for loop otherwise if it was not included then i will check the number of items to be removed from the top of the stack right i will have to check how many items i can remove from the top of the stack so if the stack is not empty and also the top of the stack is having a larger element than the current item then we will check for the frequency that the frequency of the top of the stack must be greater than zero so that i will be sure that it is going to occur somewhere in future because if it is not going to occur somewhere in future i cannot remove it from the top of the stack and after removing all the items if it is possible or not possible after that we are going to push the current item on the top of the stack and then we will mark the current items seen that means the visited as true and i will also decrement that items frequency okay and once all the items have been processed that is all the letters have been processed then the stack will actually contain the entire string in the reverse order so we will have to take out all the items and we will have to push it into our answer string and finally we will return the answer string as our result okay so this entire operation takes order of n and this is by using monotonic stack so i hope you were able to understand the entire explanation if you are interested and serious about interview preparation for your upcoming interview drive or for your upcoming interviews then you can contact us on our whatsapp and get the entire details of the live interview program if you like our video then please hit the like button and subscribe to our channel in order to watch more of these programming videos see you guys in the next video thank you | Remove Duplicate Letters | remove-duplicate-letters | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i. | String,Stack,Greedy,Monotonic Stack | Medium | 2157 |
29 | hey guys let's take a look at number 29 divided two integers we need to divide we need to create our own division divide division yeah without using multiplication division and operator and mod operator yeah this R is naive approach is just keep doing subtraction right I'm not sure whether they pass or not the time limit anyway so let result equals R 0 Wow divide 10 is bigger than divisor divided in subtract divisor two from divided and the result plus 1 and finally we return the result it I think it's time limit exceeded it should be the time would be old and / M should be the time would be old and / M should be the time would be old and / M huh what ah God a sign okay sorry let sign cuz one if divisor dividing it could be - oh yeah sign okay both could be - oh yeah sign okay both could be - oh yeah sign okay both could be signed okay how can we get the sign okay so if widen is smaller than if bigger than zero and the divisor is bigger than 0 if both of them are bigger than 0 if their sign are different okay sign cause -1 divided math.abs cause -1 divided math.abs cause -1 divided math.abs dividing divisor equals math I guess so and finally we will result of the same let's try to improve this one so zero so it's saying ah God - Ciro it's good it's saying ah God - Ciro it's good it's saying ah God - Ciro it's good it would be zero anyway sighing quiz minus one zero because it's speaker so divide it and the result plus one hey ah God I should do here both of our my bath community south hmm the sign is minus 1divided b11 and big same so zero and then plus one so it should be one it's copy pay and forgotten to update my dance so now my brain is not working let's try to improve improvement would be like let's say we want to calculate get what overflow god script there is no such thing as overflow for this small int so would math max minus 2 proven like in front to get to 22 divided three unexpected what it should time then excited okay sure definitely gonna be exited improvement thought is that actually we're going to write it into three like got three improvement is actually I can we can stop its subtracting three what's the time I should do it like if we do it in the reverse way we can get a three and x 2 plus 3 we got six and plus three plus six we got 12 and then plus 12 we got 24 so we can get these array get these back by what by adding right and once we find the largest one so this will actually be 3 times 2 and this number of a power of 2 times the face is 3 and we just compare it and we're if we found something is right rights we stop when we are going to surpass the target like for 22 we stop at 12 right so 12 no we substract subtract so we got 10 and then we try to extract subtract six is four and then we try to extract 3 equals 1 so the result would be the index rec indexes series to know the base should be 1 2 4 8 right so we write here we plus 4 and here we plus 2 here we plus 1 so actually we get 7 so that is right okay actually these we need to store this because store these base and these two because we cannot use multiplication wow man okay we create a an array called cost which is based on to cast a base on divisor let base it's a equals Z 1 Wow face that equals 1 Delta J equals divisor while J is smaller than well J is smaller than divided with based on to well push I base on the visor well push J and then remove J 2 but it's not ok this should be 2 so plus I J plus J it was n right I J is bigger than but that the array will keep the numbers which is smaller than them so then we will collect the result for let K equals based on divisor tenth case bigger than zero okay - mice tenth case bigger than zero okay - mice tenth case bigger than zero okay - mice okay let result Oh God this should be one my bad this one it's true three are this poor one plus one is two plus two is four yeah it's right okay it's result be 0 and if based on divisor k if divided is bigger than it if then we should do we should result plus base on divisor know based on - okay because it's smaller so based on - okay because it's smaller so based on - okay because it's smaller so we should add it right so and then get K to the next one until K to the zero so and then you should return result of course we also have the sign problem okay you need to copy the sign and do the bloomin ization should make them all positive integers and finally we need to return the signed results let's take a look mmm gives us see you okay maybe we should use 10 this 10 3 would be better example to expect a tree Oh should be - one of sorry while the I really like to subscribe lead cold but it's expensive okay I got the wrong answer if okay we console.log justify the case on to and console.log justify the case on to and console.log justify the case on to and based on divisor three yeah this right so because we get three six ah God it's like this man I don't know where these make difference Wow let's do okay the base is 1 2 3 6 it's right and well would get 3 dividing is 7 because it's bigger than ah god I bet we need to do the subtraction man yeah it should work now I was trying to like for eighth time still run Esther my god wow I'm not really I'm really bad at algorithm love this one at this one there would be no one won ah God it should be maybe equid we should I'm really not good at the boundary yeah still not right man okay yeah okay god I want to give her Philippe algorithm problems man I just want to go back to my home and do some yeah to some awkward culture thing crease on being make my small restaurant I will don't want to do algorithm problems so yeah it passed comparing Chara naive proud knife solution it's much complicated so the time complexity how much it would be actually it's the length to time we first we generated the have generated the main threat meant of the generator to temporary array to holds the intermediate results so that will cost us cost out how much is N and M actually should be lock to right this and after that we Travis the again so we should time is two so in a general it will be a block divided by M so it's much better actually yeah that's all for this one we should pay more and more attention on the edge cases which is first one is so the minus number or the bound boundary yeah I'm not really bad at this so see you next time | Divide Two Integers | divide-two-integers | Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`.
Return _the **quotient** after dividing_ `dividend` _by_ `divisor`.
**Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`.
**Example 1:**
**Input:** dividend = 10, divisor = 3
**Output:** 3
**Explanation:** 10/3 = 3.33333.. which is truncated to 3.
**Example 2:**
**Input:** dividend = 7, divisor = -3
**Output:** -2
**Explanation:** 7/-3 = -2.33333.. which is truncated to -2.
**Constraints:**
* `-231 <= dividend, divisor <= 231 - 1`
* `divisor != 0` | null | Math,Bit Manipulation | Medium | null |
322 | hey what's up YouTube Welcome to another video so I'm not sure if I uploaded this before I definitely have this video in Spanish but I went and watch it in Spanish and definitely I did not like the explanation that I had before so I'm going to redo this video and hopefully uh clear some things up uh so the problem is called coin change and essentially you're given an integer array of coins representing the different number of uh coins that you have in order to get uh you know a desire or Target amount so it says return the fewest number of coins that you need in order to make up to that amount so essentially U make the most efficient solution um if the amount cannot be made up by any uh coin combination return minus one and in the example here you have one 25 and the amount is 11 so you can see that the most efficient way to get an 11 is 5 five and one right cuz you can probably get it you know um with five twos and then a one but obviously that's not the most efficient so uh two fs and a one is the most efficient and then you have example two where uh you only have uh two um unit coins or a coin worth two whatever and the amount is three so that's not possible therefore the output is negative one and uh so how many coins do you need in order to get zero well in order to get zero you need zero coins so the output actually is a valid one which is zero and not negative one and the way they show the example is actually very conspic I don't know if conspicuous is the right word but they do this on purpose so you have to like um make sure that you're thinking of this and accounting for this so I have this here coin change and let me see if I can make this bigger um right so this's the example but there's a caveat here uh probably the first thing that you think is oh uh this seems very simple I'm just going to um you know do a greedy algorithm uh trying to get the most amount um without over passing 11 so I'm going to do uh you know five is that larger than 11 no five is that uh larger or equal than 11 no two so I have 10 is 10+ 2 larger than 11 yes okay move on to 10+ 2 larger than 11 yes okay move on to 10+ 2 larger than 11 yes okay move on to the next one and so on and so forth there's a problem with this and that's why this is not the solution is that and of course they're not going to put this in the uh description because whoever is testing you on this wants you to realize this and know that whatever you were thinking as a gritty solution is not the right one so I'm going to put up um an example here with one three and four and the amount I'm going to make it six so notice how now things change see how now four so if I choose one coin worth four is that larger or equal to six no okay so how about now if I choose three yeah that goes over that's seven uh then I choose one that's five I choose one again that's six and like the amount of or the combination of coins solution I'm going to put _ W meaning wrong would be4 and you can tell right away obviously that the most efficient solution is a three so then you go like okay so definitely this is not the correct solution so what is it that you can do in order to get the correct solution well the second thing that you have to realize and I was doing some pseudo code here but realized that was not really helpful um what you need to realize is the following um you can do uh in order and I'm going to do the example with this particular um example the 1 three and a four right uh that way it's not too hard because then problems can get you know if I do 11 there's 11 uh choices at some point but with six so there's let's say that you choose you have you know from your choices you have a one a three or a four so let's say you choose one and you choose one so you can go ahead and choose one um six times until you get six or you can choose three and then one right so four five and six or you can choose three and then you're done or you can choose 411 and then so the number of correct choices that you can have here are uh well with the one can actually be you have 1 three one or 113 uh yeah 1131 you get the point right so there's multiple choices where you get six you know going by this route or choosing like 1 three or 113 or 1113 Etc so and by the way this doesn't get as nasty because the amount is low but with 11 the number of possible combinations it's even more and what you have to realize here is that you're repeating work so how do you realize that you're repeating work well let's go with the six and not with 11 again um so one possible choice is you do one and I'm going to choose a three just to save ourselves like some time so that's five and then the last one right well this would be to the right actually so this would be here that would be there and then you would choose one more time sorry this is A1 excuse my poorly drawn ones but then that would get you six agreed this is exactly the same as saying one then three then one right so we have the five there one because the number of combinations is exactly the same they're just in different order and same thing if you choose uh you know uh one then one again Jesus okay that's a very poorly drawn one so one and you get the gist so these are the same so what can we do well since we are redoing the same computation like we know that three ones and 1 three is the correct answer to get a six not the most efficient but it's a possible answer uh we don't have to repeat this so what can we do we can me memorize essential um compute and save that computation somewhere so uh what we can do is um bot I believe it's bottom up but essentially uh tabulate or compute and save our um calculations so I'm going to be doing the following um I can leave that there and I can bring this to the bottom so we can see what we need to compute or better yet I'll just copy and paste this all right so I'm going to put all of this here okay jokes on me uh there you go so what can we do so in order to get six uh what we do is we computate this and this is going to be our dynamic programming or we can put cash or whatever uh nor you normally see DP but either or is fine what we are going to do is compute how many coins do we need in order to get a specific value prior to getting the full amount so what do I mean by that so let's say how many coins do we need to get zero obviously zero therefore dp0 will always be zero uh something very important all of this we need to initialize to so I'm going to put dp1 dp2 dp3 uh all the way to six and I will write all of this down uh dp5 dp6 so again all of these are equal positive Infinity because we want the biggest value um in the positive direction uh which by the way in goang actually you use um Max integer of 32 bits I'll explain later why but since you can do this in python or any other language uh positive Infinity is fine and there's a reason why um obviously you want to get the minimum value of two so you know for a fact that since this is the max value whichever other number you put compared to Infinity that would be the minimum value that's why we use Infinity um so what I'm going to do is the following I'm going to start with coin one and I'm going to paste these values and I'm going to put them over here so what's dp1 you want to so you're going to iterate through the coins right and um the way that we're going to be solving this is I is going to be assigned to the coin value and you want to make sure that you can get the minimum of um DP I which I'm going to put uh coin one so in this case D Coin one is just dp1 or DP I minus coin + coin + coin + one so why do we want to do this um let's say that we're calculating something different and let's say that we're using a bigger coin uh if we use a very bigger coin uh um trying to see if this is useful right now but essentially uh I'm trying to think if this will be useful right now um actually no never mind not a bigger coin so essentially when we're doing a loop first we assign it to the coin and then we increment Plus+ so I'm going to say we increment Plus+ so I'm going to say we increment Plus+ so I'm going to say like I is equal to coin and then I ++ so like I is equal to coin and then I ++ so like I is equal to coin and then I ++ so right now this is going to be equal to zero of course but let's say uh I'm going to get rid of this and I'm going to put the minimum let's say for round two it would be dp2 or it would be DP 2 minus one there you go uh which you know this ends up being uh dp1 + this ends up being uh dp1 + this ends up being uh dp1 + one and so this is precisely and I'll put this back as so coin which in this case we know the coin is one right so we have coin is equal to one I is equal to coin and then in the loop we increment I okay um what is the one signifies that at least you need the coin itself so what does that mean um what is dp1 so you're going to be looking previously where uh dp1 was computed which in this case it was just initialized to Infinity therefore this infinity and it's um you know infinitely uh big or positive hence this is just too big and then I minus in this case uh one so uh 1 minus one which is dp0 in this case dp0 is just zero and one is you know the coin one itself therefore this becomes one uh we do the same thing with d 2 so dp2 here is just um you know positive Infinity 2 minus one is just dp1 so dp1 we set prior that now is 1 + one is just we set prior that now is 1 + one is just we set prior that now is 1 + one is just two so then now here we put two and we do the same here with dp3 so previously dp3 was just positive infinity or we have 3 minus the coin which is one which would be dp2 and dp2 is um you know two so 2 + 1 three and um you know two so 2 + 1 three and um you know two so 2 + 1 three and essentially you can tell that since this is the coin one all of these are going to be equal to you know uh D4 equals to four uh and I'll change this to four dp5 equals to 5 and dp6 equals to 6 right so let me just write that down and I know that I'm being very thorough but hopefully me being very thorough will help you um understand un understand this and this is A4 this is A5 this is A6 dp5 dp6 right so all of this would be whatever the amount equals because we're using okay how many coins of six how many coins of one sorry do we need to get the six coins makes total sense right nothing too complex here but now we are going to then go to the next iteration and then our coin now is going to be equal to uh three and let me make a space for clar clarity and I'm actually going to copy all of this and then we'll change it let me move this here okay uh I guess I'll make a new text yeah let me see if I can move it okay um okay so now we're going to delete this because obviously these are not correct anymore and since we're by the way since we're using coin 3 we already know that we cannot get one or two uh by doing this calculations so we can automatically say that you know one stays in as one two stays at two and then you go straight at three so previously what was dp3 so we know that dp3 is three so what's the minimum between that or dp3 minus coin which is uh you know three so dp3 ofus 3 is dp0 so 0er + one remember the one uh so 0er + one remember the one uh so 0er + one remember the one uh signifies the coin itself of three of course so here we just put one same thing we do with four so dp4 which is four previously right four or uh DP of 4 minus 3 which is dp1 plus one so dp1 is one and then one plus one is just two so in this case we have two then we go to Six previously I mean sorry dp5 so dp5 previously was five so what's the minimum between five or DP of five minus coin which is uh 5 - or DP of five minus coin which is uh 5 - or DP of five minus coin which is uh 5 - 3 is 2 so dp2 is 2 so 2 + 1 3 so we're 3 is 2 so dp2 is 2 so 2 + 1 3 so we're 3 is 2 so dp2 is 2 so 2 + 1 3 so we're going to put three instead of five then dp6 so dp6 was six prior and then dp6 minus coin which is three is dp3 so if we go to dp3 which is 1 + 1 now is two we go to dp3 which is 1 + 1 now is two we go to dp3 which is 1 + 1 now is two and uh are am I missing one more coin I think we have oh yeah four we're missing the four so now the last round is going to be with a four and we'll see here how the four is actually not the most efficient to get six uh so coin here is four then I'm going to go ahead and copy all of this get rid of what we don't need to compute and oh I just realized that I was covering okay here are the answers maybe I was covering a little bit of the answers but here are the answers um okay so let's go ahead and do this and same thing with three and well four actually we can compute it but again since coin 4 is bigger than uh 0 to three we don't need to compute those again so p uh previously dp4 we had that it was two right because I'm referencing this uh way I'll delete this so I don't confuse you guys uh dp4 was two but in this case um you know dp4 2 or dp4 minus 4 which is 0 + one is just one right 4 which is 0 + one is just one right 4 which is 0 + one is just one right because of course uh with one coin we get the amount of four uh dp5 we have that previously was three now we have uh 5 - 4 which is dp1 so 1 + 1 is just two 5 - 4 which is dp1 so 1 + 1 is just two 5 - 4 which is dp1 so 1 + 1 is just two and you know this is more efficient than the previous dp5 and then dp6 we have that previously um it was two so two a minimum of 2 or dp6 - 4 which is dp2 + 1 minimum of 2 or dp6 - 4 which is dp2 + 1 minimum of 2 or dp6 - 4 which is dp2 + 1 dp2 which is 2 + 1 is three and dp2 which is 2 + 1 is three and dp2 which is 2 + 1 is three and previously we have just two so instead of changing this to three of course we're going to leave it as two because two is the most efficient uh amount of these two or the minimum U value of those two so then if the amount is six we just have to return uh DP amount which that will equal to two and that is how we compute the answer and we'll call we'll code it right now if for some reason let's say that you're Computing but uh you know let's say that there's no solution you're going to have infinity and then um here when you do DP amount you check that you're not returning Infinity um so you'll see right now when I code it uh so I'm going to be doing this with goang because you guys have to ask for some goang programming so let's go ahead and do that and I'm going to be doing the following DP I'm going to initialize my slice to a slice of integers uh I'm going to put a length of amount plus one because remember uh zero doesn't account for all the coins we'll have to put all the way from one and six plus a zero index therefore amount plus one um yeah uh the next thing that we want to do is put the infinity inside of the slice so I'm going do for I'm going to range through the amount I'm going to do DPI is equal to uh math and um pay attention to this I'm going to put Max integer 32 why do I put Max integer 32 um especially with infinity I think in goang Infinity gives like an error you can use that with python and uh and JavaScript and you won't have a problem but with Goan you do seem to have a problem if you do uh there's like I didn't want to delete all of it if you do in and you put one for Max infinity and by the way so that's a float 64 so you have to convert this to an n and then here you know you add that I think this will get this still will give you an error so that's why I use uh Max in 32 uh you can even use U so on sign integer and that will give you a right answer and you can see that um you can use uh 32 bits because here is 2 to the uh 31 um so that's essentially um 32 on sign bits possible um combination of numbers or bits so that's how you know you can use this but you know this also works but you can use end whichever you rather now dp0 we know that it's zero so we want to also make sure that we have that uh because prior we would had this and then we can move on with our solution where we can um iterate through each coin so for each coin as we did in the example uh range through the coins that we have right so for each coin of coins or for each coin in coins uh we want to do the following we want to assign I to the coin amount and then as long as the as long as I doesn't go over the amount uh we are going to increment I and what we're going to be doing is DPI will equal the minimum of as we said before DPI or DP of I minus coin + one before DPI or DP of I minus coin + one before DPI or DP of I minus coin + one uh where again the one uh signifies the coin itself and then if everything goes right well not return we don't have tary and goaling but you would do if um DP amount is equal to math Max in 32 then and this does have to be like this return1 because there's no solution otherwise you return uh DPA amount and for this you just create a quick function um there's already builting functions in goling but I don't think lead code has this uh so if a is less than b return a otherwise return B and that's it and let me get rid of this so you can see like the solution I can actually like make this a little bit smaller so that's the complete solution uh I know that this can be annoying in goang to have that auxiliary but again uh there's a Min function and sort functions and whatnot in goang already built in it's just that I don't think the elad code compiler has it so I'm going to run this and I have a mistake R cannot range over amount variable time int oh sorry DP um not the amount um which I think we'll be able to do that in go 1.22 but that in go 1.22 but that in go 1.22 but anyway so the solution is fine I ran the code and now I submitted it's 9 milliseconds it renes between 3 milliseconds and 11 milliseconds honestly it's not really important the important thing is that this's a dynamic programming uh solution which is one onedimensional uh Bottoms Up uh or bottom up yeah bottom up or top bottom anyway uh the one dimensional D dimensional dynamic programming um so hopefully with this you have more clarity on how this works if you like this video give it a like subscribe and I'll see you on the next video bye | 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 |
41 | Hello everybody welcome back to hike my name is panel Jan and today we will solve the question first missing positive we will first of all try to understand the question then we'll try to understand the approach to solve it and finally we will code it in so look at the entire video watch the entire video end to end so that you can completely understand what we are trying to explain here all right so let's get started first missing positive given an unsorted integer AR nums return the smallest positive integer that is not present in nums you must Implement an algorithm that runs in O of n time and uses o of one auxiliary space let's take one of the examples let's take this array as the example and try to understand the logic behind the code that we going to write so 3 4 minus 1 and 1 the easiest way to solve this question is to sort the array but that would require o of n log in time and that is not given we are going to solve it in O of n time and O of one auxiliary space okay so look at the approach very carefully I'm going to show you how we are going to solve it so we going to iterate through the array the numbers that should be present it's a array of size four the numbers should be 1 2 three and four these are the numbers that we are looking for so what we are going to do is we have a three over here so we going to swap it with the number that is on the third position so I'll write the positions these are not indices these are positions one 2 three and four so I'll swap it with the number on the third position so let's swap this so this becomes -1 4 3 becomes -1 4 3 becomes -1 4 3 1 now minus1 is not in the range that we're looking for it is not between one and four so we move ahead four now we swap it with the number that is on the fourth index now this becomes minus1 1 3 4 we have swapped these two numbers now we get to one so we'll swap it with the number at index one at position one sorry so we're going to swap this and this number so it's 1 Min - one 3 and it's 1 Min - one 3 and it's 1 Min - one 3 and four now minus one is not in the range that we're looking for we move forward three is at the right position it is already at position three four is also at the right position it is at position four and we come out of the air now this is the array that we have left now once again we iterate the array in the first position we looking for one and we have found one in the second position we were looking for a two but it's minus one so two is the missing positive integer in the array okay so let's try to code this now look at it very carefully so first of all we will calculate the value of a variable n this will tell us which numbers we looking for numbers from 1 through n now we will iterate through the vector and if the number that we looking for is inside the range that we're looking for if nums of I is greater than zero and nums of I is less than equal to n so this is the range we looking for if the number lies in this range we have to take this number to the correct position we calculate the variable position a of I but nums of I minus1 and if nums of position is not equal to nums of I if this is not the case if the number is not already at the current location we will swap the two values now we have taken this particular number to its correct position but now there is a new number at the I location and because of this for loop I will move forward and this incorrect number will stay there so we have to do a i minus after this all right the for Loop is over after this we have all the numbers at their collect correct location so we'll run another for Loop so at the zeroth index we should find a one at the first index we should find a two and so on so if that doesn't happen if nums of I is not equal to y + happen if nums of I is not equal to y + happen if nums of I is not equal to y + 1 what do we can simply return I + 1 what do we can simply return I + 1 what do we can simply return I + 1 here but if we have all the numbers in the array let's say the array is of size four and we have 1 2 3 4 then five is the first missing integer so in that case we will return n one let's try to run this code so you can see all the visible test cases have passed let's submit this and all our test cases have passed thank you so much for watching if you like the video make sure to uh subscribe like and share the video thank you so much guys see you in the next is | First Missing Positive | first-missing-positive | Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1` | Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n) | Array,Hash Table | Hard | 268,287,448,770 |
740 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem delete and earn and before we get into it i want to mention that this problem is actually very similar to another problem that we've solved on this channel called house robber it might not seem like it but when you do kind of interpret this problem you can boil it down to being very similar to house robber so if you haven't solved that problem before we've actually solved it on our channel so i recommend checking that out if you struggle with this problem but now let's actually get into it so we're given an input array of nums and we want to maximize the number of points that we can get by performing the following operations we can pick any number nums at index i and we can delete that value to earn all of the points are worth the value itself so if the value is four we get four points but the catch is after we delete that value and earn the points we have to delete every single element equal to uh one less than that value so basically nums minus one and every value equal to nums plus one so basically if we earned and deleted a four that means we also have to delete every five and every three in the input array but we don't earn the points from deleting these two neighbor values to the original value so that's kind of the catch here and what i'm really going to be focusing on with this problem is kind of simplifying it because the explanation kind of makes it more complicated than it needs to be one is that the input array can actually have duplicates right so it could actually have you know multiple four values but obviously if we delete one of the four values then we have to delete all the fives and all the threes so if we're going to delete one of the fours we might as well delete all of the fours and earn all of the points associated with them so what we're going to do with our input array is actually eliminate all duplicates to make this a little bit more simple so we're going to take the input array eliminate all the duplicates but before we eliminate the duplicates we want to make sure that we count the number of occurrences of each value because we don't want to you know lose how many we actually had if we had three occurrences of the four value we want to still remember that because when we delete it we want to remember that we earned 12 points right three times four and the second thing is uh we're going to actually sort the input array because that's going to make it really easy for us to check okay this four we chose this for we earned the points that means we have to you know not include the three which is right to the left of the four and we cannot also include the next value which is five so sorting is also going to help us in this case and once you do these things that i mentioned you sort it and you eliminate duplicates this problem becomes really similar to house robber and let me show you why and by the way house rubber is a one-dimensional dynamic programming one-dimensional dynamic programming one-dimensional dynamic programming problem and now let's actually explain the solution okay so let's say the actual input array was this two three five seven but we sort it and we eliminate all the duplicates so we're actually left with this array but we make sure to count how many we had so we keep our count in let's say a hash map that looks something like this so now we want to know what's the maximum amount we could possibly earn and we're actually going to handle this with a brute force approach but that brute force approach can actually be optimized to be a very easy dynamic programming solution which is also very efficient and the intuition behind that is this first of all if this was the house robber problem we're just given some values like this and we all we know is we can't uh take adjacent values so if we take this two we can't choose the three if we choose the three we can't choose the two or the five but we can choose the seven you're probably seeing how the house robber problem is similar to a problem that we're solving right now the only difference is with the problem that we're solving right now it's not about adjacent values that are right next to each other it's about the values themselves right so two and three are adjacent because two plus one is equal to three right three minus one is equal to two so that means we cannot include both of these right because we remember if we do include the two we have to delete the three and we have to delete any ones that exist in this case there aren't any ones we know that because this is the first value in the array if there was a one it would have came before it but notice how the other values in the array three five and seven if we choose a five we have to delete all fours and all sixes but none of those even exist in the array and for seven if we earn the seven we have to delete all sixes and all eights but those don't exist either so actually we're perfectly allowed to include the five and the seven and actually the three as well we can include all three of these values but if we do include all three of these we can't include the two because two is right next to three in terms of the value itself okay so this is starting to get a little bit more easy to understand now before i actually just jump into the dynamic programming solution i want to give you at least a tiny bit of intuition so if first if we were solving this the brute force way with recursion this is what we would do we would create a decision tree we'd start at the first value okay we can either choose to include the two or not include the two if we don't include the two then the max we've earned so far is gonna be zero next we get to the three so if we included the two can we include a three nope we definitely can't so we're going to actually skip to the next value five so are we allowed to include a five yes we're allowed to include a five with the two right and that's going to be one of our paths five uh or don't include the five right we don't have to include it in that case our uh total uh would be uh 2 on this side if we don't include the 5 if we did include the 5 it would actually be 2 plus 5 which is 7. now on the right side over here where we did not include the 2 then we could choose to include the 3 or not include the 3 so that's going to be one of the decisions three or not include the three which is going to be zero now with this decision tree the time complexity is going to be something like 2 to the power of n but we can make it more efficient with a dp technique called caching the way we would cache this is based on the index that we're at right so for example at this position right we were our index was over here we were at the three right the way we could cache it is by saying like okay up until you know starting from this index what is the maximum that we could earn uh you know from the remainder of the array and then we could cache it and then we wouldn't have to do repeated work right and that would actually make the overall solution be big o of n but and we're going to take this kind of main idea and translate it to a real dynamic programming solution which is actually a little bit more easy to code up and let me show it to you now with dp it's one dimensional so let's create a one-dimensional dp array and what each one-dimensional dp array and what each one-dimensional dp array and what each of these positions is going to represent is uh you know for index 0 what is the max amount that we could earn from the first value of the array that's what's going to go in this position what's going to go in the second position is what's the max amount we could earn from the first two values of the array similarly what's going to go here is what's the max we could earn from the first three values and finally what's gonna go here is what's the max we can earn from the entire array so as you can tell this is gonna be our return value but to build this value we're gonna need the previous values as well so let's see how we can do this so just starting at the first position uh what's the max we can earn from two well two itself right if we did include this two okay so what's the max we can earn from the first two values though well we have a choice we could include the three we could earn the three right how many points would that give us well we can see down here we have two occurrences of the three value right so the amount that we could earn from that is going to be 2 times 3 which is 6 right so is 6 going to be the max we could earn from the first two values well maybe we could actually include the previous value as well too maybe we can add this to the 6 value and then put an 8 over here can we do that well no we can't and how do i know that because if you look at this value 3 and then you look at the previous value 2 you see that 2 is exactly 1 less than 3 that means we can't include both of them we have to make a choice we include this one or we include this one so how we can determine which one to actually include is going to be the max of two or six which one of those values is larger of course it's 6 so we're going to put a 6 in that position but you know if 2 was bigger we would have put the 2 over here so basically what i'm getting at is the value that goes here is the max we can earn from this portion of the array it doesn't necessarily mean we have to include this three in the calculation for this position okay so next value over here we have a five value and how many occurrences of five do we have one so we can earn five points by deleting this value right so can i put a five over here well let's take a look at behind us this is a three right it's not a four if it was a four then we couldn't include this value either but it's a three that means we're allowed to earn from both of these values so what i'm saying is we can take this 5 and add to it the 6 value that came before us so we can say 5 plus 6 so the value we put here is going to be 11. now if this was actually a 4 of course we wouldn't be allowed to do that so does that mean we just put a 5 here no because it's not just this value we can choose we delete this 5 but we can still include all values that come before the four value so what i'm saying is uh we put a 5 here plus the 2 that came right before this one right so we'd put 5 plus 2 that would be a 7 but in this case this actually was a three value so we can put 11 here and actually i'm going to change this seven to be a six just to make this problem a little bit more interesting so let's change that to a six and down here let's also change this to a six so now we're at this six value we can delete this six value how many points are we gonna earn from that it's gonna be six times two so it's gonna be 12 points that we earned from that okay so we can put a 12 here plus are we allowed to also just you know earn from all of this as well we could if the five was not like the one value away from a six but since five and six are right next to each other we're not allowed to do that so we cannot include this 11. but at this point you might start to realize that we only need to look at the two previous values so from here if the first previous value is adjacent that's okay because we know that the second one is definitely not going to be adjacent so we can just take that 6 and then add it to this as well right so what we can say in this case is 12 plus 6 is going to go here that's going to be 18. but it's not always going to be the case and that actually ends up being our result if you're clever you'd realize that this dp we have an entire array here but we don't need the entire array to compute any position for example to compute this position we only need the two previous values we don't need the whole array so when i code this up i'm not gonna have an array i'm just gonna keep track of two values and i'm gonna call them earn one and earn two so earn one and earn two is going to be the previous value earn one is going to be the value that's even before that one and remember every time we compute a value for example this 18 that we just computed it represents what's the max we could earn from the array up until this point in this case it's the entire array so we have our return value this 18 is the return value maybe i over complicated things for you right now but i think it'll be more simple when we actually code this up right now and by the way you saw that the time complexity with this dp solution is big o of n but remember we're actually sorting the input array so the overall time complexity is going to be n log n from the sorting now let's code it up okay so remember what we wanted to do is eliminate duplicates from the input array nums we can do that just by passing it into a set constructor and then we can convert that set back into a list by passing it into a list constructor and after that we want to make sure that it's actually sorted so we can pass it into the sorted function and that'll return the array in sorted order and it feels like cheating when you do it with python but i don't think interviewers would actually care i don't think they want to see you implement you know eliminating duplicates and all that they want to see you actually implement the real problem but before we do all of this we want to make sure that we actually count the occurrences of each value we know that's going to be important in python we can just pass in the input array to a counter and that'll return a hashmap with the counts uh but of course if we really needed to and the interviewer wanted us to we could code this up pretty easily with a hash wrap i'm just trying to save time and focus on the real problem that we're solving here and we're gonna have two variables that i talked about earn one and earn two initially we're going to just set these both to zero because we haven't even looked at the input array yet and then we're going to start iterating through the array so for i in range length of the input array nums and the first thing i'm going to do is just take the value that we're looking at index i and just figure out how much we can earn from that current value because we know that calculation is going to come up later on so let's say uh nums of i multiplied by the count of it which we stored in count it could be one it could be two it could be a hundred who knows let's just get that count and multiply it and the first case i'm gonna worry about is the case the difficult case where we can't earn uh where we can't use both the current value and earn two which is the previous value and how do we know if that's the case well we know if the previous value is 1 less than the current value and we can figure that out first by making sure that i is greater than 0 and if nums of i is equal to nums of i minus one plus one you might think that this should be a minus one but let me just explain it to you because i always make the same mistake the current value let's say it's a four let's say that the current value is a four if that's equal to the previous value which let's say is a three plus one then we know that we can't use both of them because the previous value is one away from the current value and the else case is basically going to be if this is not the case which means we can use both the current value and the previous because they're not adjacent values okay so now for the actual computation first i'm just going to go ahead and put earn2 in a temporary value because we know the way we're actually going to be doing this is we're going to be taking earn one and just setting it to earn two because remember what each of these earn one and earn two represent is for an array that looks like let's say one two three uh if earned one is over here let's call it e1 and e2 is over here e1 represents what's the max we could earn from this portion of the array e2 represents what's the max we could earn from this portion of the array as we iterate through the array we're going to take e1 and then shift it over here and when we do shift it over here what that basically means is we just assigned e2 to this variable and when we get e2 is the one that we actually have to compute right e1 was just assigned to the original value of rn2 but earned 2 actually has to be computed because what that represents is by adding this new additional value what's the max we can earn from the entire array right so that's what we're gonna have to compute with earn two because earn two always represents what's the max we could earn from that portion of the array uh so how are we going to compute it well it's going to be the maximum of two different values and those values are current earn right let's say current is at this index right and let's move these back to their original values we're trying to compute what's the max we could earn from here so let's say we earn this three but we're not allowed to earn this two so if we earn this three we're going to add to that value what earn one was right earn one is over here which is at a value that's not adjacent to this one so that's one possible computation the other is if we just take earned two by itself right because we're trying to compute what's the max we could earn from this entire array we don't necessarily have to include the three if we do include the three then we're also going to include the one if we don't include the three then we can just take what's the max we could earn from this array not including the three it could end up being the maximum maybe i'm over explaining this i hope not but that's the main idea that's actually all we have to do here and the else case is pretty similar the only difference is that we are allowed to use both current earn and earn 2 if we want to if it results in the maximum so once again let's set temp equal to earn two oh i just noticed up above we didn't even use the temp variable we want to put temp uh assign it to earn one we know at the end we're going to be assigning earn one equal to temp but before we do that we want to overwrite earn two we want it to be the max that we could earn from this portion of the array and that is going to be just we don't even need a maximum actually we're just going to take current earn which is the current value plus earn two because we're allowed to use both of them so why not why do we even need earn one because we know earn two is always going to be greater than earn one or equal but that's the entire code so what are we actually going to return remember earn 2 is always going to be the maximum so by the time we get through the entire array it should represent what's the max we could possibly earn so let's run it to make sure that it works and as you can see on the left yes it works and it really is about as efficient as you can get for this problem so i hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching | Delete and Earn | delete-and-earn | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. | Array,Hash Table,Dynamic Programming | Medium | 198 |
92 | See, we are going to ask questions in this video. Lead Code 92 Reverse Link List 2 questions which are going to be a bit complex. If you are feeling lazy or sleepy then do not watch the video. Watch it only when you are active. Because you will not understand otherwise I am telling you so the story is something like this is our link list, ok there is no problem, in the question the head of the link list will be given and left and right will be given i.e. what is this right will be given i.e. what is this right will be given i.e. what is this index, what do we have to do. The link list which is coming between left and right, including left and right obviously, we have to reverse it like see here what is left and what is two i.e. what is left and what is two i.e. what is left and what is two i.e. one to two indexes are starting from one. If there are, then left is two, that is, two is fine here, there is no problem and right four is 1 2 3 4 fine. Please note that this is the index, not the values. If it is fine, then your link list from index two to four is that. It will reverse, the rest will remain as it is, okay, this is our question, let's start, now see, if the head is null, then there is no use of going ahead, it is correct or there is only one element in the head, i.e. head dot is only one element in the head, i.e. head dot is only one element in the head, i.e. head dot nex equal. Even if it is equal null, there is no use of proceeding. Obviously, what will you do to reverse an element or if it is left equal right, then there is no use of proceeding. It is correct that in all these cases we will return the direct head as it came. Just return it as it is, brother, go, okay, but now we will handle all the cases, apart from these, okay, in the last video, we had reversed the entire link list of normal Puri, so what we had taken a previous pointer in it. Okay, we took a next pointer, we took a current pointer, do you remember, okay, in childhood, when we were small children, we used to take two pointers, one was taken current, which we used to put equal to the head, okay, which we used to point to the head. Now the current is also pointing, this is the meaning of this line and used to take a pointer, list node is equal to null, that is correct, let me explain something to you before moving ahead, okay listen sir 1 2 3 4 5 6 Let's leave five as it was in our example. This is our left pointer, this is our right. We have to reverse the list coming between them. Okay sir, let's do one thing, let's increase it a little more and write nine here. Let's take it for a while and write seven here, okay now see what I will do, I will run a pointer named current from here, okay here it will be previous, that means null will be previous, I will keep increasing them till we get to the left. If you don't reach then it's okay, then I will reach, the current will be mine here and then our previous will be here, okay, I want this is a normal loop, this is fine, the previous will be here and the current will be on my left. Right now, the beautiful list that we had was so much, okay, what will I do, I will store this one somewhere, let's call it somewhere, do I point to pointer to start, what does start mean, where we are starting from reverse? It is okay to turn, that means two are okay sir and I will keep one more pointer to start for later use. That is correct then I will have two pointers to use later. Pointer to start and start is okay now left and Let's remove the right one, you are getting confused, this is my current pointer. Now see, when we were little kids, we learned to do reverse. We took three pointers, we took the current, we took the previous, we took the next, what is next to current. So we will still do the same thing, we will take three pointers, previous, current and next and reverse them, this is what we have been doing, right, we will reverse it, I will tell you how to do it, don't worry when it will be reversed, then we will play with them, pointer to start. And it's okay from the beginning, now let's start, look, let's go line by line, you will understand, don't panic, don't cry, okay sir, see, this is the same condition of mine which we had just written on the lead code, then what have I done, okay, upset. Don't worry, you will understand, I have taken the current pointer, I have taken a previous pointer, like I told you, okay here brother, then what have I done, I have taken a counter, simple, okay, what am I doing, I have run a loop. Bha, I have started a small, cute loop and I am saying that I will continue this current till it reaches the left, it is correct, I told you the same thing, it is written the same, see while i is not. We are doing equal to left i plus, it is ok and we are increasing the current and making the previous equal to the current, before increasing it, this is the right thing, obviously we will check null if ever null pointer exception comes, right? We are doing current dot next because here we have checked that the current is not equal to null, we are okay, so after that I have made the photo here in front of you, okay brother, look at the current which is at the beginning of the window. Okay, it's here and where is the previous one, just first, there is no problem, so look, I have written the same here, I have taken a pointer to the start, okay brother, why have I taken the one which is pointing to the window, I have taken it because of this. Look 9 one I agree I have made it beautiful somehow four three and two is correct and this is as it is five seven I understand this pa sa this is this na one this is fine and we have reversed this list Okay brother, now tell me sir, point punter to start is needed, now see, whom should I point to one, I will get point to four, isn't it right, so for this you need to understand the point and current, I have written here, start is written, see a pointer. I have taken the start, here is the start, why have I stored it because I look at the start, what is this, what is the start, two, okay, two, I have this, I will get it pointed, five will get my answer, that's right, things. Gharai opinion will be cleared, ok sir, I have understood that we have reached the window, we are looking at it, ok brother, now I will start reversing, till now we were just preparing, we were reaching the window. We have reached now let's start to reverse it. We have taken whatever weapons we have for our next pointer to start and start. Okay, let me tell you one thing, now we are starting to reverse it. You see, brother, this is different. The list is okay in the world, that is, shoot them now, we have stored them, okay, this is a very good thing, that is, we have nullified the previous ones, this is right because we will point the null to two, okay, so that's why Here I have written 'Previous is equal to null'. Okay, we are going to written 'Previous is equal to null'. Okay, we are going to written 'Previous is equal to null'. Okay, we are going to start a new one and we will need that because we do not want to point two to one. Actually, you are understanding the thing because right now the previous is equal to one, so we We will remove it and will make the previous one pointed with tap, that is correct, let's move ahead sir, what to do now, okay, we had taken a pointer, that too is here at the moment, we will increase this aa, till when we will keep this aa. Do not reverse the entire list. This is correct and how to reverse. Pay attention. Right now my list is this. Okay, I have to reverse it. We have studied it in childhood. Okay, this is previous. This is current. Okay, let's run a loop. Then while current is not equal to null so and so, something like this is ok, then what do we do, we put current dot next previous, ok it gets removed, previous current comes and current reaches further, next is a next pointer. OK, then we do the same work, increase the next, make the current point to the previous, make the previous point to the current and make the current point to the next means that the current will become this and this link is broken. You are seeing. The work is being done slowly, okay, these two and three have turned, how many operations have been done, two operations have been done, that is, I know where it will be now, it will be here, okay, and look carefully, look at this one which Right, this one, we have not created the link yet. Well, as soon as we create this link, what will happen is that the current will point to the previous one here, then it will start pointing to the one that is ahead i.e. this was five. Okay, let's go sir, now it seems. start pointing to the one that is ahead i.e. this was five. Okay, let's go sir, now it seems. start pointing to the one that is ahead i.e. this was five. Okay, let's go sir, now it seems. Yes, brother, two, three and four have now been reversed and this will be the previous one, right, that means, come, how many times have we had to run, when he will point to it, then this list of ours will be reverse, that is, come, run us. Pada right pv bar ok now see sir the whole code is ready ok this is our initial condition we took the current pointer one previous pointer took one i took one we prepared the counter weapon ok we ran a loop So that our current one reaches the starting of the window and we have taken two pointers, pointer to start and start, okay, we have nullified the previous one so that we can start a new one. You will see that I told you what we will do until i which is right + 1, where we had to i which is right + 1, where we had to i which is right + 1, where we had to take i to here we had to reach right + 1, that is, take i to here we had to reach right + 1, that is, we will keep doing reverse until i comes to right + 1. We are doing i+P we will keep doing reverse until i comes to right + 1. We are doing i+P we will keep doing reverse until i comes to right + 1. We are doing i+P and it is playing with the pointer. This is the same code which is used to reverse. Just told me that we had done reverse thrice. Ok, I have also checked the current is not equal to 2. Very good thing. Okay, this list has been reversed, so now let's see how the shape will be. Okay, and why are these things written down? Now look carefully when the shape will become 91. One is pointing to two. Do two. Nala is doing the right thing because we had taken the previous one, Nala is doing three to two, four is doing to three, it is good sir, no one is doing point to five and it is okay, let's see the points. What is the point here, what were you doing, brother, pointer to start is fine, no problem, let me do it, let's say PTS, there was a start pointer, start is fine, sir, no problem, don't worry, where is the previous one? Brother, the previous will be here, I had told you in the diagram that the previous reaches here, the current reaches here, I had told you like this, my work is done, look carefully, what do you want now, tell me, these are the reverse ones, obviously they are the reverse ones. One is pointing to two. No problem. Two is pointing to the tap. Ideally, see what should happen. Ideally, I make it here: 9 one, 4, 3, Ideally, I make it here: 9 one, 4, 3, Ideally, I make it here: 9 one, 4, 3, two, 5, it is fine, it should be, that is, Two five should be pointed, that is, here I have written start dot next ill two, that is, it will not point to the tap, look carefully, it can create a little mess, look carefully here, it is okay, now the tap is pointing to two. I was doing the first two points, the fifth one is fine if the pointer to start is not null, now what does it mean, look carefully, it may be that what is given to you is not left, what should be the start, that is. You are understanding that you have given the start of the link list, okay then what will be the pointer to the start, in that case you are not understanding anything, your window is starting from here, brother, somewhere. There is no point in going till here too, but the start is from here, so what is the pointer to start? Otherwise, it will be null. Well, if the pointer to start is null, then it is not null, leave it is null, there is another part. No, if there is no tap, then this will be run. If there is tap, then we are returning the previous. Sir, what is the meaning of directly returning the previous? Look, it is written especially for you, if left is index zero. Do you understand, left is index zero, then this. Will become the new head, think and see, if I have to start from zero, my work is fine till four, look till four carefully, do it till four, I have to reverse it, that is, how the list becomes 4 3 2 1 9 5, that is the right thing, that is. That it becomes four and is not a head. Is it understandable? I have written here that if the pointer to start is NULL then return the previous one and return this one and it will become the head, but as in this case. If some elements are coming in the beginning. Some elements are coming in the beginning then make the pointer to start dot next equal to two previous. What does it mean that point inter to start dot next is pointing to two now i.e. one is now two. pointing to two now i.e. one is now two. pointing to two now i.e. one is now two. Pointing to but who should have done one should have done four should have done that means pointer to start dot next is equal to two previous do two now look nine is pointing to one neither is pointing to one is doing four To four, to three, to two, to whom he is doing. Look carefully, to whom he is doing two. To five, to whom he is doing five. To seven, his work is done. Look, the photo has arrived, okay sir? This is my question, okay, I hope you have understood brother, it's okay, Nana, if it hasn't come, then check again, it will come, don't worry, let's run it, let's see after submitting, 100% see after submitting, 100% see after submitting, 100% at 98, very good time complexity, big of n. We have not done anything, we have added two loops, but those two loops would not have happened even if we had added two loops, but here it is happening in a single iteration. Okay, first we went from one to two, then from two we went to four, but it is complete. Are you understanding, are you not even going completely, are going till the right, but time complexity is big of n, let's end in this space, we have not taken anything, so big of one is ok, thank you, this video is a record of 40 minutes. What I am recording is fine at the moment and whatever will be made, I think it will be of 15 to 20 minutes, that is, my effort is very much and if you go away after seeing it, then whatever humanity is there in you is not left. is absolutely also e | Reverse Linked List II | reverse-linked-list-ii | Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass? | null | Linked List | Medium | 206 |
94 | hey guys persistent programmer here and welcome back to my channel so in this channel we solve a lot of algorithms and go over legal questions so if you haven't subscribed already go ahead and hit the subscribe button smash that like button because that helps me create this content for you guys so without further ado let's go ahead and look at today's problem we have the problem binary tree in order traversal so first let's understand what does this mean what does the word in order traversal mean so in order traversal follows these three steps so first what we need to do is look at the left and then we need to traverse to the node so we need to print the node and then we need to look at the right so this is the order that we need to follow in a given binary tree and then return all the values of the node to solve this problem in an iterative way we need two things so we need a stack which we are going to pop our values out of and we also need the result list that we're going to return so this is what is going to be returned um and what is going to happen is we are going to start all the way here from the root and we are going to keep traversing to the leftmost node so if i had to write the pseudocode it would be something like this so let's say if root is not none then we need to keep going to we need to keep adding to the stack so we'll so this will give us the order that we need to access things from um so we will say st dot append this root and we are also going to change this pointer to the left side because that is the priority because the step one is left so we are going to keep navigating the route to the left so to do this we will just simply set the route to root dot left so what's going to happen um when it is all the way to the left and the root is none then this if is no longer going to be applicable so for example um let's go through one of the iterations so it's very clear um so first of all we have three here and yeah so there is something here in the root and so what we want to do is we will append this three to our stack here and then we will say root equals root dot left okay so then we are here right so this is three's left and this is three's right so we are here at the left um and then we are going to also put that value in our stack as per this statement here um and then again we'll try to go to the root.left and now in this case it to the root.left and now in this case it to the root.left and now in this case it is none so what we need to do is we need to pop out of this pop this value out of the stat so we are going to pop this out and we will so in the else condition we are going to say node equals dot pop so the way the stack works is a leaf structure which is the last in first out which is exactly how we want it so the last element there was nine so we're going to put the nine here in our res so we will append to res so just write res here and then we are going to access that node's right so this is the pop value right this is being held in this node variable so we are going to point the root so this is the trick we're going to point the root to this node's right so we need to now navigate this third step which is the right so step one was left all the way which we did and then step two um was to encounter the value right and then we put that in our res and then step three is what we're doing now which is putting the root to node dot right and this is the node that we just popped here so nine so again this is none so it's not going to go into this if statement here right so it's going to come back to this else statement so far we have done all of nine and we are going to go back to three so then the next thing that is going to be popped out of this is three and when something is popped we are going to put that in our res here so three is here and then what we need to do is access three threes right so we've accessed threes left we have encountered for three and we're going to access this subtree now which is three's right so here we are um again setting the root to threes right here which is um all the way here at 20. so root equals no dot right so again here we need to do the three steps so lab node right so now we are now we're evaluating this node right so we're up here so there is something in the root so this 20 will be placed in our stack here so just ignore these two because we've already processed them so we are going to put in 20 um and then we are going to navigate to root equals root double left so we are going to 20s left here so again we need to do the one two three steps here so we've currently processed the first step of 20. so here at 15 we are going to go to 15's left and that's going to return null so when something returns null that means we need to get that um yeah so we went to 15 so 15 should have been here um so when we are at null we are returning um we are going into this else here and we are popping that value so we will put the 15 here right so this is the processing of the second step of the node right and then we are going to try and go to 15's right so we go to 15's right and there is a none here so when there is a none we're finished processing this and we are going to so we have popped 15 from here so currently there's only one item left in this stack here so when we are done processing this we are back here in our step two which is to register the node itself so if we look at this again we have put a um none as the root so root equals node.right so 15's right was root equals node.right so 15's right was root equals node.right so 15's right was none so we're back here and then when we're back here we need to put that we need to pop that note out as part of this else so node equals stack dot pop which only has one item currently which is the 20 so that is going to be popped out here and then put in the res and then we set the route to root node.right that so the node we just node.right that so the node we just node.right that so the node we just popped which is 20 so we set it to that item's right which is going to be here in seven so when this is actioned um we will check if the root is not null which is not so then seven is going to so currently the stack doesn't have anything i'll just draw a fresh one here so it's more clear to understand so it only has seven up and then again we do the three steps here one two three so first we go to sevenths left and that is none right so when that is none we are done the processing the first one and then we're at step two which is to process the node itself pop out of the stack here so node equals sd.pop and this is how we get the equals sd.pop and this is how we get the equals sd.pop and this is how we get the seven here and we're not done yet because the part three is the node root equals no dot right so we point the root to um okay seven's right and then that is none so when that is none uh so we've already popped this out so when that is done the stack is empty so we need to put all of this in a while loop to check if the stack is empty or not and we also need to check if the route is there or not so when these two conditions are met then we go into the while loop so currently the stack is empty and that should return our res which is the last step awesome so i'm back in the code and what i'm going to do is um in a while loop check if um the stack is not none or um the route is not none since these are the two variables we're using to navigate um so either of them should be populated um for the if and else statement to work in this loop so what i've done here is already have the res list that is set to empty and the stack list that's also set to empty list so first of all i will make sure that if the node if the root is not none so if root i am going to go to the left so i will put this value in the stack so we'll say stack dot append and put this value in and then i will navigate to the left side of that root so root equals root.left equals root.left equals root.left okay else i will pop from the stack so we can call this node or temp node so node equals stack.pop stack.pop stack.pop and what i'm going to do is save this node's value in the res so this is how we're encountering for that step two so i will say res.append so i will say res.append so i will say res.append is going to be node.val is going to be node.val is going to be node.val and now the third step is to go to the right so i will set root equals the nodes right that we just popped so node.right okay so this is how we're node.right okay so this is how we're node.right okay so this is how we're maintaining that order of left node and right and lastly i will return the reds here which is collecting all the node's values here okay so let's give this a run okay awesome accept it and submit yay success | Binary Tree Inorder Traversal | binary-tree-inorder-traversal | Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively? | null | Stack,Tree,Depth-First Search,Binary Tree | Easy | 98,144,145,173,230,272,285,758,799 |
463 | in this problem you are given a grid and that grid cells represent either a piece of land or water so uh inside the grid one will denote land and zero will denote water so this is a binary grid and outside the grid everything is water and there is just one piece of land and it's clearly mentioned in this question that you are given just one piece of land so there will not be multiple pieces so here what we have to do we have to find the perimeter of this island so in parameter we will calculate this on the region highlighted in yellow that is the outer regions so this is one unit all the cells are of one unit so this is one so you have to outline this land and then count how many edges you find so in this case it will be 16. we have 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 we started from here so how we will calculate it so here it's a simple problem but i will try to give multiple solutions so that you get good understanding of how to solve it uh if you want to solve it using dfs then also you can use that depth first search and it will be a recursive solution but in this problem we don't require dfs and we can do it with just one pass of this grid iteratively only so let's look at both the solutions i hope you will gain some understanding of how to write recursive code as well as iterative code so first we will look at the simpler or more easier approach which will be iterative approach so here what we will do we will start from this row we will scan this row wise so first row then second row and in each row we will scan all the cells so if this is m cross n grid we will look at all the m cross and mn cells and what we will do we come here we look its neighbors so there are four neighbors these four neighbors are allowed not diagonal only four neighbors so we will initialize a parameter initially perimeter is zero then we look at each of the cells we come here we see how many neighbors it has it's a water so we don't even consider we come here it's a land so we know that we have to find its parameter so we will never come back at this cell so that's why better look at all its na all its side all of its four sides which of the sides have water so in the top we have water left we have water right we have water but bottom we have land so three sides are surrounded by water so this will be three these edges one two three so ah for i equal to zero to row minus one so this is rho or you can say m or rather r and j equal to zero to column minus 1 and if grid i j 0 then we don't need to see if it's water then we are not bothered only when we find a land we look at its sides then continue don't process it else what we will do you can do multiple things you will first add a bound check that i is greater than 0 then see whether i minus 1 exactly left cell is water or not if it is water add 1 to parameter look at its right if its one add one to water add one to perimeter similarly look at all the four neighbors so accordingly ah if left is water perimeter plus similarly if right is water then again plus top is water again plus bottom is water again plus so here we added three let us run through it perimeter was zero so what we did we added three when we encountered this land then we come here water nothing to do then we come to next row i becomes one so we come here we see which sides are water left is water top is water bottom is water three sides so add three then we come here all four sides are land so nothing to add here three sides are water so again add three then water land again look at its sides two sides are water then water nothing to do then here three sides are water here two sides are water and then we reach here and that's the end of this loop let's add it three 12 then 14 16 so it's 16 which is correct uh we can do it uh recursively also if you like so let's see the recursive solution we will follow the dfs approach so we know that we have just one piece of land so we will start a dfs and it will visit all the nodes and in dfs we need to keep track of wasted nodes so initially these are 0 or 1 values so whenever we visit a land we mark it as 2 that will denote visited so we look at this row we start row wise and whichever is the first cell where there is a one or land we start dfs from there so we start dfs from this is zero through and one column so start dfs from here and also pass one global value sum or you can call it parameter so what we will do we will first mark it widget so grid let's call it i let's call it j in general so market visited then what we will do we will look at its neighbors so we look at its three neighbors four neighbors three of them are water only one is land so we add some three times obviously we will write more code here and just for simplicity adding this three so here we added three marked it as visited and look at its neighbors whichever is land if there is no land which is unlisted then we are done we return so this is now marked two since visited then we look at its left right top bottom only one side is land so we come here and trigger a dfs here so it will call dfs or if it's a small so dfs this is row one column one again look at its neighbors nothing to add so this is now wasted its neighbors are this and also this so trigger a dfs here so this will call dfs 1 0 and here 3 sides are water so it will call sum plus equal to 3 similarly it will be listed and come back to here next unvisited is this come here look at its neighbors again 3 will be added so here we had added 3 here we added zero here we added three then come back here and trigger dfs here also we added three then backtrack next unlisted is this one so come here look at its neighbors two sides then mark it wasted this side is wasted come here again trigger dfs here look at the four edges two is water market wasted next neighbor is this come here market vested look at its sides three sides and now there is three neighbors are water one neighbor is land but it's wasted so dfs stops here and whatever is the value of sum we return so it's 3 that is 12 plus 4 16. so this way also you will get the same answer so i will write this both codes in c plus but in java and python i will just write the iterative one so this is the problem and i had taken the same example and here you don't need to worry about edge cases that is empty grid also they have given that there is exactly one piece of land so that means the grid is not empty so first let's write the iterative solution let's save the row and column into a variable we will need it multiple times if its water we will just continue and not process further for this value of ing and you can do multiple things here one is that you add check like i is greater than 0 and grid i minus 1 j is not land then add 1 to it but here two checks are required one bound check and one the value check so better to take perimeter four beforehand so we have added assume that all four sides are water and then whenever we encounter a land we will decrement it so if here we are done with one step obviously we will write for all four neighbors but if you are adding perimeter checking if it's water or not then if it's this row 0 i is 0 then we will not have this neighbor this grid i minus 1 j so we will have one another check that if i is 0 then we will definitely add it since grid i j is 1 it's land otherwise we would not have come to this line of code so we need 2 checks if i 0 or i is greater than 0 and grid i minus 1 j is 1 is 0 then add 1 so to avoid that we added 4 beforehand and whenever we encounter a land we will decrement its value so here we simply need so it will automatically add uh these values as water and we will only be checking within this grid if it's land we will decrement since it's guaranteed that in the top there cannot be land so there is no point in checking so these are for four neighbors and this check is just bound check that we will only look for this cell we will not look below it and left of it similarly for this cell we will not look at right of it for this cell we will not look at left of it so on the outside it's assumed that it's water so no need to take care of that and finally return perimeter and this works for this case let's submit and the solution is accepted so it's around this range now we will write the dfs solution or recursive solution so let's comment it out and again initialize this so if we encounter a one then we have found a piece of land so we will start dfs from there we will define this dfs shortly we need to pass the grid we need to pass the row and column and we will also pass the parameter by reference or you can also make it member variable of this class and finally we will return perimeter now let us define this dfs and we will mark it with it so for that we can use make it two so two denotes listed and only cells which were earlier 1 are converted to 2 0 remain as 0 so what we will do we will check if i is 0 that is first row or grid i minus 1 j is 0 then perimeter plus so first we will whatever cell we are at we will mark it wasted we will look at its neighbors how many sides are water we will add that to perimeter and then for each of the neighbors which are unvested we will trigger a dfs so first let's add the parameter we can mix it in one also but that will add few more conditions i want to keep it simple here so if it's i equal to 0 that is first row or last row then automatically perimeter we will increment by one since those sides are water if not we will check if top or bottom are zero or not so these are for top and bottom and we will check for j for column columns that is left and right so if it's last row or grid i plus 1 j and same for columns so we have incremented the perimeter looking at the sides now we will do the dfs so if i is greater than 0 and uh grid i minus 1 j equal to 1 then dfs i minus one j and or i less than grid dot size minus one and grid i plus 1 so here we look looking for top neighbor here we are looking for bottom neighbor so i plus 1 j and ultimately this dfs will visit all the lands and also keep track of perimeter now let's see line 33 and the answer matches so let's submit and we got some heap overflow so here is the mistake it should be grid zero dot size for number of columns and this solution is accepted now in java and python we will do this iterative version only and the solution is accepted in java and we are right here around 99.93 and we are right here around 99.93 and we are right here around 99.93 that's good and finally we will do it in python and we have not con we did not convert that to back to one in our earlier dfs solution in the end you can uh again run through this grid and wherever you find it to replace that with one so you can do that but that was not required here and the python solution is also accepted | Island Perimeter | island-perimeter | You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water.
Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
**Example 1:**
**Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\]
**Output:** 16
**Explanation:** The perimeter is the 16 yellow stripes in the image above.
**Example 2:**
**Input:** grid = \[\[1\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0\]\]
**Output:** 4
**Constraints:**
* `row == grid.length`
* `col == grid[i].length`
* `1 <= row, col <= 100`
* `grid[i][j]` is `0` or `1`.
* There is exactly one island in `grid`. | null | Array,Depth-First Search,Breadth-First Search,Matrix | Easy | 695,733,1104 |
137 | how's it doing Mondays so in this video discuss about this problem single number two given a non empty array of integers every element appears three times except for one which are B's exactly ones fine it's single one note 0 algorithm should have a linear and time complexity and could you implement it without using an extra memory so let us consider some example first so in the first example two is present three times and three is present uniquely so we're done three in the second example zero and one are present three times and 99 is the unique element so we're done ninth-inning so element so we're done ninth-inning so element so we're done ninth-inning so now let us see how we can solve this problem so over here I have taken an example so in this example if you see carefully number one two and four these represent three times and the number three is actually unique so somehow we have to return this number three it's correct over here I have represented these numbers in their binary format now this number one is actually present three times this number two is present three times three is two then only one and four is fluent three times now what I want to do is I want to sum this 0 8 bit for all the numbers and similarly I want to sell all the one at bit and all the to admit so let us do this thing so for 1 this is 1 so it is 2 then 3 times so the contribution is going to be equal to 3 from here the contribution is 0 from here this is 1 and it is present only one time so this is 1 into 1 which is 1 again this is 0 so we will get 3 from here and one from here so the total is going to be 4 for the one at bit you can see that this is 1 over here and since the resplendent 3 times so we will get a contribution of 3 from there and it is 1 again so it is present only one time so it doesn't divisionist 1 i'm from here as 0 so it is 3 plus 1 which is again 4 for the second bit these all are 0 and only one is there so it is 2 then 3 times so the contribution is going to be 3 now one important point over here is these sums that is sum of 0 8 bit or sum of one at bit or the sum of two 8 bit or so on these sums are actually going to be of the format of 3n or 3n plus 1 why I'm saying that 3 or 3 between breasts one see if we are getting a 1 in a number which is 2 then 3 times so we are getting a contribution of 3 right so we'll always get the contribution in the multiples of 3 from the numbers which are present treated only the number which is present one time in case it is contributing in that case only we are getting this 3n plus 1 right because from all the other numbers we are getting a contribution of 3 so it's going to be equal to 3 and correct so in case the particular bit is set in the unique number we are getting it in the format of 3n plus 1 so what do I mean to say is that if I do this thing then I will be able to know which bit is set in my unique number and which bit is not set in my unique number so basically in cases thumb is equivalent to 3 n plus 1 of the format of 3n plus 1 we can say that this I get bit is set in my unique number and in case it is of the format of 3 and I'll be able to say that this I admit is not set in my unique number now why is this information important see the unique number is 3 in this case if for 3 I know that this is the sad bit and this is the unset bit would I be able to convert this thing into 3 I will be able to rate so that's why this information is important now the second question over here is how will be how I will be able to check for a given number n whether the I 8 bit is set or not see 4 here if you see 4 I was checking for the second bit for like for the number 4 so over here the number is dependent in the binary format so we can simply check it but normally it will probably present in the format of decimal so how will I check whether the second bit in 4 is sad or not so actually there's a standard technique to solve this problem so let me just show you this thing so in case let us consider now a number given to you which is something like 21 so 21 in the binary format will be something like 1 0 this is a 0 8 bit first bit second bit third bit and 4 bit so in case I have to check for this suppose I project for this one admit this bit is set or not what I will do is I'll create a mask so this mask value is actually one left shift I this I stands for the I admit so in case I have to check for this vennett bit this will be equals to one left shift one which is equals to 1 zero correct so let us take an end of an and mask so n will be something like 1 0 1 and mass is 1 0 and over here all zeros so if you see if I'm taking an end of these two numbers for end these all these things and all this thing is going to be 0 because in masks it is 0 for end to be 1 for a particular bit to be won both the bit should be 1 so actually the dependency is only over here so in case this is 0 we are going to get a 0 and in case it is of 1 we are going to get not equals to 0 of we can say greater than 0 so we can say that in case and mask in case this value is equal to 0 we can see that the current bit the I 8-bit in see that the current bit the I 8-bit in see that the current bit the I 8-bit in n is actually 0 and otherwise it is one so this is how we check for the I 8 bit in a given number n so this though now let me read the code for this question and then things will be more clear okay so now we will create a variable called result it will be initially 0 and we will have two more variables that is some and mask now since there are 32 bits I will iterate over each of the better so forth and I equals 0 I less than 32 I plus so the current mass is going to be equals to 1 left shift I and the sum is equals to 0 now I will trade over the numbers are given to us so forth in and end nums what I will do is in case and mask in case this value and mask in case this is not equals to 0 I know that this current bit I is not set in the number and so simply increment sum by one correct and finally after this loop is over will check in case this sum is not a multiple of three in case this is not equals to zero so in that case what we will do is we know that this current bit is actually set in my unique number so what I will do is I simply say result or equals mask correct so after this is over will simply return the result so let me just sum it is good and cot accept it so I guess that's it from this video in case you have learned anything from the video you can hit that like button and you notice about my work you may consider subscribing to my channel | Single Number II | single-number-ii | Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**. | null | Array,Bit Manipulation | Medium | 136,260 |
1,932 | hello everyone uh today we are going to look at another lead code problem which is uh category of art where we need to merge a PST into single BST so BS is basically binary service tree so we know that binary search history is something where everything in the left is less than the root node and then everything on the right is or greater than the root note that's the basic property of the binary service tree now look let's look at the example here so it is given that this is one benefici oh this is one binary secondary and third tree this is the list of input that we get and then we want to merge them to create a final three and then validate whether that tree which is created after Mars is a valid BST or not valid balances three or not so now if I look at this example here so I have download here so how we can do merging here so basically if I look at the first one the root note is 2 and then secondly the root node is three and the third the root node is five now out of these three I need to determine from where I need to start emerging for that the value one thing we need to see is the which are the root note is not the leaf node of any other tree in case of this root node true is a leaf node of these three in case of this root node it is a leaf node of this tree but in case of 3 it is not a leaf node of any other tree right so my starting position will be this particular oh this is my start root note from where I will start doing the merging now once I identify what is my starting position starting root node I can do further merging I can then after that we can apply the merging of the boundary now let's say if I try to merge this one so two matches with here so I'll add this node here basically so this is one node and this is I'll delete this particular tree so this node is this particular boundary is merged now the remaining tree is five and four this could know in this case 5 matches here so I'll update this tree again this root tree and then move uh sorry I'll just delete this one you know it is this one okay now this is actually it's on the left hand side so I'll move this one now if I validate this boundary so everything on the left this piece is less than three and everything on the right basically is greater than three so this means this is a valid VST okay so this is a logic here now if I go back to the code section so what I need to do is in order to determine as I mentioned what is the starting point of my uh root 3 out of V3 what is the starting point so I need to determine this so what do I do is basically I identify all the leaf nodes first so 1 2 5 and 4 and out of these Leaf nodes I try to identify which one is not the root note of any other tree so if I look at one two five and four so two is already root node and 5 is already root note of another tree so these two cannot be my starting point so starting point can be this node so I'll identify as a root node root 3 and assign into the this particular root so this is my starting point in case of it don't find into it I'll just return that entered now in the at least remaining trees basically this is 5 and 4 and 2 and 1 I'll put it into this particular tree and let's open it because now I want to use this for this list for the merging purpose now in from this particular list I am preparing a keep key value pair so why I need this basically just for the searching purpose so this once I have this uh let me just clear it a bit let's see so basically what I want to do is create a dictionary that will hold the root node value and the corresponding tree so when I am creating the so once I know this is my root note uh starting point now I'll create a dictionary for two one 2 and then 5 this uh this 3 and District so in the dictionary what is what I'll have is let's say uh to let me take a so 2 is going to be my starting and then key and value will be the tree up true and then next is file value will be T of 3 or 5. so basically the tree entire tree here okay I'll tell you why I prepare this particular key later on so I got this particular dictionary which holds basically two and then to the tree for the two and then root Note 5 and the tree for the file okay now I'll start I'll have a helper function which does the merging from which basically Traverse City and then tries to merge it now if I once I call the helper function in this helper function I'm passing the root tree which is my starting three which is this one and the dictionary we chose the this information the key in which is root node value in the tree and then in Phi and then entire tree now if I try to check whether the root value is in the dictionary now when I start the three traversal I am at this particular position which is three node right so 3 does not matches my with mother do any of the dictionary values so I'll just ignore it and then I'll do the left tweetaversal and then corresponding right return so once I go to the left it traverser will I reach here which is 2 now root values to whether root value is present in dictionary yes because my dictionary holds 2 and 5 right and 2 is present in the dictionary it is a present in the dictionary then I'll extract the tree and then assign all the left node to this node and then all the right node to this node and then I pop the dictionary I'll remove this particular tree output dictionary now only remaining value is y and 4 in the dictionary again I'll do the for the traversal so now it goes to the right one right when it again goes and again perform the same operation as I explained for two it finds that there is a match or file then it will assign the left node of O left node of I which is 4 to this node and then right node in this case there is nothing to this now if it is there it will sign and then pop up the dictionary now all the tree in this tree and this tree has been popped up so there's a lightly this tree my dictionary is empty and also three traversal is under there is no further uh note to travel right so finally the root that I get which is updated tree I need to check whether it's a valid balance test you're not so I have a very common logic to check whether it's a value BST or not based on this function if it returns a valid BST and also the dictionary is empty because nothing is left in the dictionary I'll return the final tree as our reset if not if I if both the condition doesn't matches I'll return the null value so that's what the entire logic is it kind of just lengthy and messy but this is how it will look it works in case if I don't find a varied BSC for example in the second case I'll just return I don't do any immersion after the margin in case if you in case if we for example here 5 and then six everything has on the left hand side should be less but in this case 6 is greater than 5 so it's not a valid tree so it will return in that commercial uh if I run this so it will evaluate yeah test cases works fine and I can just go ahead and submit it okay cool thanks for watching this video | Merge BSTs to Create Single BST | grand-slam-titles | You are given `n` **BST (binary search tree) root nodes** for `n` separate BSTs stored in an array `trees` (**0-indexed**). Each BST in `trees` has **at most 3 nodes**, and no two roots have the same value. In one operation, you can:
* Select two **distinct** indices `i` and `j` such that the value stored at one of the **leaves** of `trees[i]` is equal to the **root value** of `trees[j]`.
* Replace the leaf node in `trees[i]` with `trees[j]`.
* Remove `trees[j]` from `trees`.
Return _the **root** of the resulting BST if it is possible to form a valid BST after performing_ `n - 1` _operations, or_ `null` _if it is impossible to create a valid BST_.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
* Every node in the node's left subtree has a value **strictly less** than the node's value.
* Every node in the node's right subtree has a value **strictly greater** than the node's value.
A leaf is a node that has no children.
**Example 1:**
**Input:** trees = \[\[2,1\],\[3,2,5\],\[5,4\]\]
**Output:** \[3,2,5,1,null,4\]
**Explanation:**
In the first operation, pick i=1 and j=0, and merge trees\[0\] into trees\[1\].
Delete trees\[0\], so trees = \[\[3,2,5,1\],\[5,4\]\].
In the second operation, pick i=0 and j=1, and merge trees\[1\] into trees\[0\].
Delete trees\[1\], so trees = \[\[3,2,5,1,null,4\]\].
The resulting tree, shown above, is a valid BST, so return its root.
**Example 2:**
**Input:** trees = \[\[5,3,8\],\[3,2,6\]\]
**Output:** \[\]
**Explanation:**
Pick i=0 and j=1 and merge trees\[1\] into trees\[0\].
Delete trees\[1\], so trees = \[\[5,3,8,2,6\]\].
The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
**Example 3:**
**Input:** trees = \[\[5,4\],\[3\]\]
**Output:** \[\]
**Explanation:** It is impossible to perform any operations.
**Constraints:**
* `n == trees.length`
* `1 <= n <= 5 * 104`
* The number of nodes in each tree is in the range `[1, 3]`.
* Each node in the input may have children but no grandchildren.
* No two roots of `trees` have the same value.
* All the trees in the input are **valid BSTs**.
* `1 <= TreeNode.val <= 5 * 104`. | null | Database | Medium | null |
1,929 | hi my name is david today we're going to do number 1929 concatenation of array and we're going to be solving this in javascript so we have a function that wants to get concatenation and then take some nums here we see is an array of nums and here's the example and it wants us to return a new array where it just concatenate concatenates both of these together so we have one two one and then one two one so just add this again to itself so how we can solve this is that we can use this current nums so we array and then just loop through it again and push these new values to itself so but before we do that like a normal for loop and arrays we do um for the i equals zero i is less than uh the array so norms.length but in this uh the array so norms.length but in this uh the array so norms.length but in this case if you keep pushing it's going to keep getting longer so first you want to find create a variable of the length of the noms array so create original nums length and we set it equal to nums.land so this is the indicator of nums.land so this is the indicator of nums.land so this is the indicator of when we're going to start our for loop after that we can loop through gnomes and inside of it we can push the nums of i um two nums so we'll loop through here uh get the one and we push it to the back two pushes the back one pushes it back and we do this the length of it so zero one two we do it that many times and we can just return numbs at the end great so here we do cons original nums then equals number now we do a for loop for let i equal zero i is less than original nums length i plus and inside of it we just push it in the array so nums dot push nums index over and we can just return numbs sorry this needs to be in parentheses great we got it so now the time is basic complexity so since we're doing a loop of nums so it's going to be o of n where n is the length of nums and then a space complexity since we're adding to this original array the original length is also going to be the same of o of n where n is the so that's how you solve this problem thank you so much | Concatenation of Array | maximum-value-at-a-given-index-in-a-bounded-array | Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**).
Specifically, `ans` is the **concatenation** of two `nums` arrays.
Return _the array_ `ans`.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[1,2,1,1,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[0\],nums\[1\],nums\[2\]\]
- ans = \[1,2,1,1,2,1\]
**Example 2:**
**Input:** nums = \[1,3,2,1\]
**Output:** \[1,3,2,1,1,3,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[3\],nums\[0\],nums\[1\],nums\[2\],nums\[3\]\]
- ans = \[1,3,2,1,1,3,2,1\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 1000`
* `1 <= nums[i] <= 1000` | What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1]. Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down. | Binary Search,Greedy | Medium | null |
1,312 | Hello Hi Everyone Welcome Back To My YouTube Channel Su Again Be Destructive Avatar Difficult Questions Minimum Installation Steps To Make A Simple Improve Special Public Number One Two Three For Lips Expert Mr Topic Company Hi How To Do And You Must Need To Find The Number Of Little Boy Doing A B A That Deep Sleep And Display Should Me Enwei A Chief A Palindrome Number Four Drops Two And Mid Term Will B C D E F G 234 That Will Follow Enter Number Fans Options Ko Tum Susuk hindi language by id use rahegi set number functions which can also give me blood and e agree with number to the number you all subscribe divya according to the question alarm show agency abc person's policy rather difficult question petrol with a b c d A B C D 32.11 Infection and the Problem D 32.11 Infection and the Problem D 32.11 Infection and the Problem List Corrupt A B C D A Plus etc Vitamins Old One Should Reduce Minimum Number of Information Dance Show Liquid 10500000 Can Do the Last Concern and 125 Dishes Sapoch 0.2 Such 100 Possibilities 180 Interactive Fee And That Organism Same Pimples Nandish Embedding Blast Beginning Test Start Asking Tips BCCI SDS Loop's Condition ABCD Beerwa Half Fuel Available BC To 0.5 Vishsheed Fuel Available BC To 0.5 Vishsheed Fuel Available BC To 0.5 Vishsheed Dictionary App Has Been Done So Let's Move Ignorance Will Remain Next Directly This 1515 Not Match Any Possibility Of Difficult Problems Statement 225 And Add Last Sector-21C Resident Mother Died So Last Sector-21C Resident Mother Died So Last Sector-21C Resident Mother Died So Ifin Kids Already Subscribe Person Clear Indication Mau UP Are So Let's Move To So Acidity Are Five Richest Elasticsearch And Office Timing Su Samaj Yeh Ko Majboor Clock Of Measurement Mist Number To Make In Distinct From Is Difficult To Make Art Of Living Room Previous And Subscribe Machine This Them Is Bcd Own Room Video I Am Amazed And Limbs Pe This Frustrated Of Commerce 0000970 Next Comes First Morning 2012 Early Morning 2014 Was So Che A Feel This Now Its Eyes Of Hinduism Science Stream Taste One To Take Immediate Intervention After But Exactly Fasting Is One Which Disappoints Guests Can Be Field After More Than 1000 Intimate Scenes One Element Subscribe 280 90 80 So Let's Mode So In The Beginning Events Train From 200 to 500 to 1000 index so since every state portal duets with sacrifice and last index of the tricolor not very cool danish khan ki movie exam not if two possibilities given people and not rule out the possibility of sexually elected chief 125 se zinc must Lu 204 Hai So Let's Move Ahead With His Due To Which He Zloty Total 100 Possibilities Itna Radhe-Radhe Group C And D A Distance Radhe-Radhe Group C And D A Distance Radhe-Radhe Group C And D A Distance Tubelight 0341 Loot Video then subscribe to the 13012 12402 Hai And Posting Third Fourth Standard Deduction Not Matching Us Force Of Medicine Possibilities 250 and one two make such questions page 232 vinod sood vipan return 8.30 subscribe 2012 in return 8.30 subscribe 2012 in return 8.30 subscribe 2012 in response to calculate subscribe my channel and minds pe aa 121 hai and bluetooth two and 20121 sleep 2000 12 10 20 and 10 side footval Determine it's two suggested to choose as per 2013 basically a terrible poverty 2051 2012 John Mukesh I need one information and by doing tried to 130 - 140 plus suvarna 2012 suggest this as minimum Mangal 1020 plus one dish branch Lucknow return 10000 To make it will give me one does blasted 10000 in 120 calculate a soldier school dhundhu calculated for the best one and 0 is not related to calculate the little but it does not a possibility 0208 and 12158 102 and widening 000000000 rzu Minimum 20000 Election Ghee Goldfish Branch Is Show My Ansuvan 14 Answers For 0.2 20012 In Given Ansuvan 14 Answers For 0.2 20012 In Given Ansuvan 14 Answers For 0.2 20012 In Given Instructions In The World So Dan Dj Suvvar Is Trending Se 2012 Is To Chennai Distance Calculated For Executive Who Comes To 1000 And A Similarity Between Fielder Complete Saver And Answers Which Should Zero Forgive Bus In Initially Destroys Game Repeat 100 Grams Suit Experts Mobile Midfielders Computer Way 10000 Twitter Complexity Of Complexity And Complexity Of This Feeling Which Swayre And What Is Swayre Size And Process And When Is The Rise Of The Apps Website Show Biz Va inspire au ki Shahrukh PM water pooch to khayal bhi doubts aur in points jo pizza bread commission aaye definition answer listen let's move to the school surya sister input function witch is initial years witch might be are Vijay meeting 4 minutes ago prohibition minus one nine Point Mahal Per Function Veronica Singh Master Mind DP Are Starting Index May Indicate Susma ABP Are Starting And Finding Her Love Sports Doing The Side Of A Given To The Soul Within There Video Related Information So Far S E Support This Needs To Be Done With Chest Size Zero size midnight possible 991 quality have compiled and favorite that is dance for this train will celebrate dance on ion new a two chances post liquid diet post element and starting element and breadth beautiful mind spirit from all this skin tight sudesh and time anupam terrible fix match Udhar And Character Is Difficult For The Needle Subscribe And Boon And Calling Woman Function Way Color Portion Starting Index Of Maintaining Mister And Minus One End Storing Bansal Indian Returning Officer Not Matching Possibilities C1 Possibility Is Sending Subscribe A Question Is That This Regarding In Scripters and you should start power in the given instructions for class 10th and widening destroyed and moment in life is this suggestion is part plus 125 vs me to the minimum for peace in the temple run luta do you very -very happy and take -very happy and take -very happy and take necessary | Minimum Insertion Steps to Make a String Palindrome | count-artifacts-that-can-be-extracted | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zzazz " is already palindrome we do not need any insertions.
**Example 2:**
**Input:** s = "mbadm "
**Output:** 2
**Explanation:** String can be "mbdadbm " or "mdbabdm ".
**Example 3:**
**Input:** s = "leetcode "
**Output:** 5
**Explanation:** Inserting 5 characters the string becomes "leetcodocteel ".
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters. | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. | Array,Hash Table,Simulation | Medium | 221 |
1,008 | Hua Tha Hello Viewers Welcome Back to My Channel Thank You Doing Great Job Done Please Do Subscribe My Favorite Playlist Cover Various Categories of Problem Subscribe and Research Dynamic Programming Benefits on Please Aadhe Problem Subscribe Video Subscribe Free Mode on Traversal Preorder Traversal Basically Veer subscribe Channel Questions Binary Tree Every department of not lose no value and independent of not right they regret not at all the order subscribe 9 First and last but not least not a charity subscribe And subscribe The Road subscribe the Road & Water & Travels Let's Tree & Road & Water & Travels Let's Tree & Road & Water & Travels Let's Tree & Destroy Se Zombies Servi Slideshow If You Have No Drought Sleep Notes Value Node V Node Glutes Subscribe No Rights Shouldn't Say No Greater Noida Subscribe Properties Date Will Have To Keep in Mind While Constructing Vakriya Travels and Tours You Visit Dheyaniya Lagwale Rahli Mai Subscribe The Channel Please subscribe and subscribe the world will visit Left My Favorite select1 100MB Left Right Left Thursday is true 51000 Jobs Pharaoh Vinit Winter Left Is Youth Officer Right For One 998 after minutes one will give verification tab in the 5th id notes157 with node subscribe zaroor subscribe kar do hai what is the active what is the lecture prisoner of this visit r website is being developed rate list sunao visit 1212 return adhir with example subscribe The Input Subscribe My Channel Subscribe Sudhir With 100 Contrasted With Great Regret Not Subscribe To Hai That's Why Golf But This Right Sudhijan The Worst Thing They All Were Is Not Live Without Prior Permission From Veer The Robot Subscribe Property What Will Be The And Basically in support of all we know what is the phone prima facie 517 sure what is the lift and what is the white part Ashok Vidron it's to go to the best not to tell you The Truth Labs Note Subscribe Now Just 120 Days A Very Few Points Were Reported Due In This Point At Which Location 5802 Nodule Should Consider Swift After Five Will Decide To Avoid 98100 Heavenly Nodule Subscribe 808 Pure View 808 Hair Oil Factory Is Loot That And All The Notes On History Greater They Need To Show What is the right place rate fix share price subscribe to 102 ki bihar to find what is the split between the laptop battery and victory in the remind notes ok morning office of stock president sunao dravid and all subscribe now to receive new the right now aware of his Five Strict So If They Are Saying No And Face Right Sudhir And Difficult Notes55 Is Next Roots Of Wave Subscribe Note Subscribe 158 The Final Carotenoid And Vansh 7 Mein Exam Dushman Notes Left Loop Me Note Clear Way Report Subscribe And Share Are 117 What Are We Now Its Joe First Night Shift 157 The Best Property 37500 Gil Se Okinawa Subscribe Notes Basically You Are Going To Subscribe And They Will Not Subscribe To Divide Into And Convert The * Subscribe From School To * Subscribe From School To * Subscribe From School To Our Left Reverse This Should Go Back and create something subscribe our that 51702 torch light software website create one saw them one let's go back to godhead and in this life but that vehicle and 78 to connect with a remit android what is the price entry special festival what is the root what Now So Tank's Decision That After Trail What Will Be The Like Share And Corruption Free That After What Is The Racer Plane Referee Talent Weather In All Are Basically Television 12% Means 12% Means 12% Means Kuch Deer Is Not Love Story For 1010 Jewelers Intended To Commit Suicide Note Toilet Not Valid Notes Will Take From This Zee Subscribe Toe Side Correction Software Go Into A Great Soul Problem The Thing For Only Two Things And Avoid Falling Property Note Subscribe Is Loot Se What They Are Looking For Subscribe Will Help You Identify Which Way Can Go Sid Subscribe Liquid 1081 What Is This Point 10 Points 173 Ki And What Ever Wanted Is Rate Citric Acid Basically Subscribe Divided Into Two Parts Every Step With Boys Veervar Arjun That You Okay - 110 To The All Subscribe Veervar Arjun That You Okay - 110 To The All Subscribe Veervar Arjun That You Okay - 110 To The All Subscribe Button - 151 - 999 Subscribe Button - 151 - 999 Subscribe Button - 151 - 999 9999 Subscribe Shubhendu Side Saurav Garg 1285 Thursday How To Get Will Not Give It's Not About What Is The Language Of The Great Ho That Water Dhavya Starting From Will Give Special Greater Ahirwal Club And Not To Find Index Of Elements Lights 172 nx100 Wear Setting Find Electronics Oil in Axis Basically the Form No Dacoit Software Pass Defiance Zarut Vyaay Entry Radhe-Radhe Subscribe and Entry Radhe-Radhe Subscribe and Entry Radhe-Radhe Subscribe and Frustration and Subscribe Return subscribe and subscribe the Channel Please subscribe this Video Please Click on the link for Zindagi Ka Number Note Hai Next 100 G * This Day Thursday Must Subscribe Subscribe and Subscribe Right Subscribe - 110 from which all-weather electronic rate minus one India Free From and Subscribe My Channel Subscribe and Finally Bigg Boss Thursday The Problem subscribe The Channel and subscribe the thing considered A Solid Gold Plated Time Complexity and Space Complexity Adhamare Time Ki and Space Addition Subscribe for more 119 Notes with Everyone Binary Search Tree Is Dehra Notes in Free Mode from Amazon I Have Length Plutarch Powder for Sixth Minutes 95519 Specific Simple Things Are Not and You Have Not Tree To Give A Specific Author And Snow Come Back To Time So What Are Doing This Element In The Preservative And Give It Is Not Only Does Not Mean That Will Go With All It's Something Print Split Into Every Drop Of Water Levels In Best Possible Way Splitting Baikunthpur Activities Live Wall Street Absorbed Into Two Parts Video Subscribe Every Time E And Then Complexities Of Different Space-Times Of Fresh Water And Half Inch So If You Have Space-Times Of Fresh Water And Half Inch So If You Have Space-Times Of Fresh Water And Half Inch So If You Have Any Rate Questions Please Let Me Know In The Comment Section Below The Video I Will Be Getting Back Tubeless York Post Ko Delete Hum Repository In Two Languages Tyonther Description Bolo This Video History Become Subscribe To My Channel Please Gold And Subscribe And Also Share Your Friends Please Click on the Bell Icon on the You Will Be Notified About My Videos Thank You For Watching My Video It's very specific. It happened. | Construct Binary Search Tree from Preorder Traversal | binary-tree-cameras | Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**. | null | Dynamic Programming,Tree,Depth-First Search,Binary Tree | Hard | 1021 |
662 | hey what's up guys it's Nick white and I do tech and coding stuff on twitch and YouTube and I do and check at the description for everything else I do all of the LICO problems I got a ton of them up on my youtube channel so please go check those out if you want these explain to you trying to get a job at Google guys so this is the path to do it leak code this problem is called maximum width of a binary tree so given a binary tree write a function to get the maximum width of a given tree the width of a tree is the maximum length of among all levels so the binary tree has the same structure as a full binary tree but some nodes are no the width of one level is defined as the length between the end nodes the leftmost and rightmost nodes in all nodes and level we're known though it's between the end nodes are also counted in the length calculation so the there's a way to do this that's pretty cool I didn't think of it intuitively but the solution explained it to me and I liked it a lot we're gonna traverse the nodes and we're going to us okay so wait let me explain this a little bit better null nodes are counted as well so see the width the max width of this tree is 8 because you can imagine there's null nodes here between 6 and 7 so we would have 1 here now I meet up one here and then if these had children to eat up on here and you have one here and it counts like that so but down here it wouldn't count it's only between the leftmost bottom node in the rightmost bottom node so the leftmost bottom node here would be or just the left most node on the rightmost node the left most node here would be 5 and the rightmost node would be 3 so that's just 2 is the width because it's 1 2 so what we're gonna want to do and then here it's 2 because 3 2 it's not just the bottom level it's any level it's just the max would throughout it so what we're gonna do is we're going to assign position values to every node so don't worry about the values of any of the notes for this entire problem we're just going to assign position values and in a binary tree to have these ordered we're gonna have the left most node this is something you learn in data structures in college the left node will be the position value will be the valley so we would start the route would be one right the left would be two and then the right would be three so the left is always going to be the value of the root node times two and the right is going to be the value of the root node times two plus one so we're gonna have this we're gonna have a max we're gonna have a position value for each node and then what we're gonna do at is we're going to have a hash map that contains this hash map is only going to contain we're gonna keep track of the depth at each level so we're gonna keep track of the level and we're gonna keep track of the position we're gonna have a hash map that contains only the leftmost nodes of each level so we'll just do this and it'll make more sense as we go so max width is going to be equal just initial it initialize a max width variable and then we'll have a hash map that's going to contain the depth and position so we'll call it leftmost positions it's only gonna be for the leftmost nodes as we go down this tree so max width we will set to zero at the beginning because that's just a good default and then we'll also initialize our left most positions hash map to an empty hash map and then we'll have this helper method called get quits right so get width we're going to pass in our route 0 and then we'll return max with at the end so max width is going to be updated within this void get widths get width let's get with method and we're gonna take in three node root we're gonna take in depth and we're gonna take in into position so the initial position that we're using is zero and the initial depth is zero because that's the root node that's very initial thing so if root is equal to null we will return otherwise what we're going to want to do is we're going to add to our left most positions hash map and this will make sense in a minute guys just give me a second compute if absent so this is how we're going to add notes only for the leftmost nodes into our hash map is this compute if absent method so we're gonna add the depth the current depth into it and we're also going to add the position and the compute if absent only puts the value into the hash map at so we're putting it in at the current depth so at each depth as we go so at depth 0 we're gonna put the left most node here which would just be the root and then here if there's no value for that depth already so there wouldn't be whenever it's the left most node we're going to put in the leftmost position so once since we're doing we're cursing on the left side first and we will be recruiting on the left side first in a second let me just actually break these recursive calls we're always doing recursive calls here guys root got left so we recurse on the root left and right that's how you just traverse a tree regularly with depth plus 1 each time we're gonna be doing depth plus 1 and on the left nodes we're going to be doing position times 2 like I said earlier to get the bat new value of our position and we're cursing on the right side as well depth plus 1 each time we have a go to a child node in position times 2 plus 1 for the right node which will give us the actual perfect sort of positions yes so if there's since we're going we're cursing on the left side first left nodes are getting visited first and there's gonna be when we get to a new depth each recursive call there's going to be no value in the hashmap yet so this essentially could put a write node into it if it's alright node first but it won't because we're going on the Left nodes first so we go on our left node first there's no value whenever we recursively call on a new depth there is going to be no value there so the only time this compute absent so we're gonna put the leftmost low left most node into the hashmap but when we see a right node later you know to call this compute if absent on that depth but it would already have that left most node in there so nothing would happen to that hashmap so that's why it only puts the leftmost nodes this little arrow function is actually a lambda function in all it does is X is arbitrary and it's basically just putting depth and then position in you can ignore these basically it's just putting depth in them position it's basically just X as an arbitrary variable that gets set to position and then actually gets put into the hashmap so this is just putting the depth in position of all leftmost nodes in and then all we have to do is update our max width variable now which is going to be set to math dot max between max width and the position minus leftmost positions dot yet depth plus 1 now here's where I have to explain the whole problem and we'll run this and I'll show you that it works and it works perfectly so what this does is we have our hash map of leftmost depths and positions so for example you can imagine that this would be this tree if it had the correct positions labeled it would be 1 2 and then 3 would be over here so it would be 4 5 now you want you would have 4 and 5 here at the last level now 5 minus 4 is 1 but that's wrong you want to the length of 2 we want the width of 2 because there's two nodes so basically we have to add one two no matter what it would be the positions the subtracting the left we're grabbing the leftmost position and we're grabbing the rightmost position because this is going to go down every right node the leftmost will be grabbed so we this is gonna be the left most node for sure and then every other node in that current level we are going to test this exact statement on we're gonna test the max width against every right note so am i tested on you know not the rightmost node at first but when we get to the rightmost node the max width will be greater anyway so we're going to be grew up the max with each time hopefully this is making sense but it's kind of hard to explain this one's pretty hard to explain when we're so every node we Traverse in every level we're tested we're reading the max with if it's bigger so we test her max with against the max with and we do the current position of the current node we're traversing subtracted subtracting the leftmost position and we have to add one no matter what so we have that rightmost position and subtracting the leftmost position is going to give us exactly the width it's going to give us the exact width and -1 that we need so the exact width and -1 that we need so the exact width and -1 that we need so all we have to do is add one to that width and that is because of the way that the positions are set up where all the leftmost nodes are the value is position times 2 when we set them at the beginning in position times 2 plus 1 to get to the right node it's just organizing in an ordered way our tree so that when we do this math at the end the positions are set up perfectly so that the subtraction is going to give us the width perfectly hopefully that makes sense for you guys I know it's kind of tough to visualize I wish I could give you a diagram here there's not really a diagram that I can show you here but I think it's a really good and intuitive solution just imagine a tree if you could take a pencil and pen and draw the exact positions like it would be it would look like 1 2 3 4 5 now if it was one if the tree was 1 2 3 4 5 you could the max width is going to be 2 no matter what because 2 & 3 are 2 & 4 & 5 or 2 what because 2 & 3 are 2 & 4 & 5 or 2 what because 2 & 3 are 2 & 4 & 5 or 2 and if you subtract 3 minus 2 that's gonna be 1 but we need 2 is the max width so we just add 1 every time it's gonna work out perfectly you just have to add 1 you do the subtraction from the rightmost node and the leftmost out so 2 & 3 would be rightmost - leftmost 3 & 3 would be rightmost - leftmost 3 & 3 would be rightmost - leftmost 3 minus 2 plus 1 gives us 2 or it would be 4 & 5 minus 4 plus 1 gives us 2 so 4 & 5 minus 4 plus 1 gives us 2 so 4 & 5 minus 4 plus 1 gives us 2 so those are just some examples if you do a couple examples of this tree you'll just notice that the rightmost position - the leftmost rightmost position - the leftmost rightmost position - the leftmost position plus one will give us the max with every single time you just have to be sure this is something you learn in data structures in school that you when you're setting the positions for these nodes and doing these recursive calls the left mode the left nodes get the position x 2 as the new position and the position x 2 plus 1 is for the right node and then you just think about the depth I 1 each time you have this leftmost hash map which I explained earlier the compute if absent just puts it in there if it's not there yet at that current depth so the only nodes getting put in that leftmost position are the leftmost position nodes because we're cursing on the left side first and I'm really trying to explain this well so let me know if I did a good job at that it's pretty intuitive we're updating these up we set them up here so that we can update them down here and we just return the max whoops at the end because it's getting updated throughout the whole thing so let me know what you guys think about that explanation it was a really hard one to explain for me here without visualizations maybe I'll try and incorporate those a little more next time but I do all the problems so check those out on my channel and thank you guys for watching and good luck | Maximum Width of Binary Tree | maximum-width-of-binary-tree | Given the `root` of a binary tree, return _the **maximum width** of the given tree_.
The **maximum width** of a tree is the maximum **width** among all levels.
The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
It is **guaranteed** that the answer will in the range of a **32-bit** signed integer.
**Example 1:**
**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** 4
**Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9).
**Example 2:**
**Input:** root = \[1,3,2,5,null,null,9,6,null,7\]
**Output:** 7
**Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
**Example 3:**
**Input:** root = \[1,3,2,5\]
**Output:** 2
**Explanation:** The maximum width exists in the second level with length 2 (3,2).
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3000]`.
* `-100 <= Node.val <= 100` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
659 | To Jhal Ajay, Hey Guys, once again welcome all of you to your YouTube channel TLC. There is a very interesting question in today's video and the question is very important. It is from Interview Perspective Study. A small thing before starting the video. Do not subscribe the channel, press the bell icon notification, Big Boss, you will keep getting video updates, join the third telegram group, Northern Command Hota Pathak, if we talk about questions, then what does the question say? What does the question say? The white board. But let's see the giver saying the question is very good, what is it, life is in increasing order, I have ever heard a very good thing, one two three four army step 4 element is sweet in the recorder, now he says what should you do, hey something. Plate one or more than one Subsequent, in this Subsequent, we know that the most contests of any state are the same Power End because each element is only 24, here hit Welcome and Note Company and broken Power End Subsequent, one of the Subsequent SMTP in this If you leave that MP sequence, then the rest of the ribbons near it will become all these sequences. I will make them, there is no problem, but you will measure all the sequences you will make. When you make this sequence, all those sequences will need vermicelli subsequences in which there will be no What should be each element in this sequence? Which coating should be the increasing means? The difference between each element should be equal to that plus its length should be greater than the length of that sequence. So now all the subsequent sequences we generate using the sequence generator should be discarded. Do it, definitely decide which length it is, now let's see from the second line up to the length of the year, yes brother, what is the subject in it, I have to take only that many consecutives in which there is between each element. How much is the difference and there is no exact one? Okay, so this is the question. The question has been asked by a player to make all the sequences. Cut the one and two length ones into two, three, catch the ones more than three, put a time loop and check whether Those properties are being device with these readings. If it is happening then increase it in your account that yes one subsequent exile and if even one is made then start return. If you do not get even one like this from the function then fold the work. It is easy to see, now where does the story go wrong, where does it get worse when we look at the content, which before the tattoos were very good, now we will sit down to make the scrubs, so first of all we are out of the tour for this because its time is very this. Plus, even if you somehow optimize and generate it, put a loop in each one and check that the skirt will go away. Staff time is limited. So let's see what it is. Now how do we optimize it? Let's look at one thing. If only three are needed then no. So why go to one and two, when you have to buy from China, will you buy two things? So, the same concept will be used here. We have given something from which. Okay, now I have said one thing which is small because every element has a choice. Is it going to be the text of any one of the sequels or will it create its own sequel? I will say one thing again when we generate all the skins, we have the requirement for it, either it will come or it will not come, if it comes then it is this else its successor. Will make it and if it does n't come then mt2 will go nearby. Either it is for the game or if it does n't come then it can be asked to come. So come with me or go to the MP seller. You make it all, meaning that every Take that choice near the element, now what do I say, I came to the forest, I asked him, my forest brother, tell me, would you like to come alone or would you like to study any subject, now actor moment to moment now I did not have any sequel, so this is the first one of mine, otherwise I am not going to be myself, madam, you start and come alone, mother, if there is anyone else, then my is worship generator, right now, I have a sequel named one here. Make it in which first of all the net was closed. Okay, so much work is done, now let's come to you, but you also said, did we ask? Well, you did not say, search, you have extinguished the enemy, brother, tell me, would you like to go with the forest or separately on your own? Will make a sequel, now both of those tweets were being opened here because if Luttu went with his mind and whoever had his mind, the property among them was also left positive and you alone were not such a big deal for Katori but I took Giridih. Thought for the beads, friend, if I send you alone then my respect will not be lost somewhere, its length which I have to do or my length which is not wanted, that thing will not be more than a guest, maybe even now I should say why maybe because in someone's mind Will go but if the other one is the most difficult then why can't we talk then date wise main ingredient thought it should be stars, remind yourself so that if you get three lines, if you meet, then wait for a minute friend, do one thing which you do n't do when alone. You will get it, come with me, one said, come with me, what do you do with me, what have you done, if you have made yourself the best customer then how much will be the subsequent one, I need SIM of one and two, it was also said, it was said from increase, please tell me what? I have to do it, I can come alone, I can also go with me, Azad will be right, now you are here, I remembered to take the twist fare, now three said, come with me, I will come home with you, otherwise it is wrong because you have come in the month of Sawan, for you and me. There is no difference between the two, I want to be carefree brother, you start alone, three to three, start alone, seven months work is done, now see what is happening, now when we come to another and we come to the phone, now we have one more Giridih. Look thinking Giridih, but what is it because I have already generated a subsequent subject, because I have already generated a subject, the different one is of three but a different one is also going on, there is a greeting which has less length, start it. Click on it, because somewhere there is grease, it has to take the length of three, I am also starting it, its length has become three, so what benefit will I get by putting the jar in it, why will I not get it because already I have only one length. If the answer is, my phone will work, so I will think of Delhi, first I will put it in it, I feel its length is less, I said ok, do it friend, so we did shopping together, it is Sheffield, make it successful and move forward for free. Put Bigg Boss-3 Learn Computer 123 Bigg Boss-3 Learn Computer 123 Bigg Boss-3 Learn Computer 123 was more so now what we are left with is after taping this after taping we have 123 I love from here and hands free I am fine Here I write further on whomever the woman will take and I have left behind what was of One Two Three, that you read the story alone, the force point of us breaking Kailash, I went to Kailash Mata Di in Delhi, if I wanted to connect with someone, I decided to for Put it here, as soon as I put the for here, I went to the face. Now look, now another twist came that now I put the pipe, although in this example, I don't see anything else that the example is like that. But okay, where is the return five because now I have put 384 here, okay, I had put it here on Sunday, so then I have my work, I will come with you and I will get myself packed, this retail There was a pack of 3, there is also increasing, there is property, satisfy your answer through, it has turned inside, you said this thing, it is visible in the front, there are also three days, right, now we have a twist, I will tell you. Here some examples may also come in which now think that now I have put the pipe here, it is okay but some examples of Possibilities of the Year are found like 345, I have 384. When I got five, I went for the length because I had done shopping on it. Now you are a villain, small American, small, no problem, but in increasing also, length is required, increasing is also required shooting, how is the shooting required because in this one to three After that, it is okay if it is fast, then its three and its four are great urgent, then keep it behind, because in some examples also we may come across such questions in which what will happen to us, the number is bigger than four, smaller than four. If there is any element which is smaller than the first one, then either our answer will be verified or it will be verified. Here, it was more than Bhai Thakur, but in someone's example, if any element is smaller then what would that element do like here. I would say that if there was someone like Seven here, this listener and now if there was fiber here, then the condition would still be like this, if something like this was made, then Five would not be found here near Seven, then I would have taken this place, but this is my logic, that in this. If he goes and shifts then I have to maintain the shopping in two ways. One way is that in which the last element is like here we have the first setting Career Free, then its first Element, what was the first element of the subsequent element and the last element of this subsequent element was the same? So we shot at the length then but when it is not saved then do shopping on it. In the increasing order then put this first then put this one then put love then here. Kept it and now when five comes, five will ask that five could not come in it, the difference between the two will be checked after popping it is pausing it, its length is the company but if it was not there, then nothing. It happened this came in it saw 510 could shirt and started the story end Maryland also end return to so this is a little bit cat here that shopping is to be maintained in two ways one that if you have the last 1232 element glass 10:30 element Who else was that entertainer? 10:30 element Who else was that entertainer? 10:30 element Who else was that entertainer? If it is Shampoo, then see the length. Which one had less sequence. Move him forward and if it is not so, then keep him in normal increasing because in increasing, we may need him for adventure. No, let's talk now. We will see that we need frequent shopping, at every time period, so who can do the setting again and again automatically, but why is this ready priority the best and what to store in it and we will start by doing all the subsequent 1234, one to three elements means. This means - one plus one two three one - one plus one two three one - one plus one two three elements, everything should be done in advance, so now when the first element in 123 also has all the properties, then let's see how to do this using what I said for the code. Tikki will be made on priority, why will we make how to read yours, after making it we will keep the interior type first, to land many in which we will not keep our physique when you are generally positive, love you, now what to do in it, now do this in it, let's install a custom computer because it is fixed for the one who does not. Come on man, please comment, I will be in love that there is no light here to make things, I am not subscribing, there are no comments coming, so what will I do with the news? Someone must have just come to me, I have to check. Is there a last element and the last element of the middle one, if it is the same? At that time, you have to shop for land. As mentioned, if you hit from the last element, then you can see the land, if you move the one whose line you have left, then how will you get the land? Agrovan - only 1800 will how will you get the land? Agrovan - only 1800 will how will you get the land? Agrovan - only 1800 will be arranged. Jhalamand Element - Post Element Plus Jhalamand Element - Post Element Plus Jhalamand Element - Post Element Plus 120 Aisi Bhi At what time will the alarm come? Best one is E - A is - is E - A is - is E - A is - 200 plus one begins towed and returned that returned on its base. Next month year is also increasing. If decreasing then If we reverse it, then how to do it by simply increasing, then in Creating a Good One Dose - 2019, the smallest limit which will be the Dose - 2019, the smallest limit which will be the Dose - 2019, the smallest limit which will be the last element will be kept first. Before storing the rest of the rate further, if it is 1234, then 123 should be placed first. Keep three four later because four is greater, it is free, we have done so much work, why did protein become with this, end the story, now let's do the main work point i.e. main work point i.e. main work point i.e. go into each of those elements, first of all let's check if the protein is Kunwar. Size is against 10 or else or love you Priya daughter's topper increase element of element increase function is top which is the last of the element like here I said one must have come in and one must have come after becoming minister as if it came If you have size, then when you have size then you have to do simplicity by simply setting it and if the size is not zero then you saw that 13483 is coming then these three match its last eliminator then what will have to be done even then no intervention will have to be inserted new range these two You can say no, if any element of the thing ever eats protein, no person will say his own life, I will start my own because I can't connect with this and if it is not empty then check if last. Element and do now and elements have more then friend will have to start new anytime like told then if this is absolutely friend element now then what will we do in it if we become protein then will set meditation then PQWLED type till date justice will be done right My meaning will be - 6 till date justice will be done right My meaning will be - 6 till date justice will be done right My meaning will be - 6 because after 11:00 each one is because after 11:00 each one is because after 11:00 each one is made up of 24 digits otherwise later we will remove them from Muslims and update them in one comment, in this we will keep updating this thing again and again because this is what has to be done. If there is no update for the range, then we will update it monthly because if we add extra to it again and again, one to three, then we will have to increase the size of the dynamic range, so keep the cumin minister because it was done after some rounds and we are checking. Everything is not going wrong and in that case it is not like that and it is not like and either the size is not zero also meaning there is no address which we possibly what we have to do is possibly we have to store it with the old element. When Ankita and I go with the previous ones, when an element becomes new and completely new, then what will we do for it? The present one, which is the current range, was taken out by grinding the one in the current range. Removed the attachment because you must have come and what else have you added, I have added one comment, so who will I be, who will prevent and end the current old range, from the previous rent, the opposing element of the previous range, i.e. opposing element of the previous range, i.e. opposing element of the previous range, i.e. Wildlife Expert Doctor 2859 Done if you step will be clear otherwise video coach just go through please that we have done the information and done the murder now comes the one in which I had said that we have in increasing order like in this one we have a Who had come like this, that when there was an address named 123, there was only one more in your bread and the fiber had to come, so because it has hit its shot in increasing, then this thing will be visible to him first, so still it could not be separated, we potted it. I did the same by doing the top and checked whether its length is less than 3, if it is then follow it and keep coming back in the opposite direction until the fiber can't handle, if you find any, then put it in, put the pipe, then it is here. We will apply that as long as the size of this cap, this ribbon is zero and it is the page-18 element of PQ muscles, that is, what is the last is the page-18 element of PQ muscles, that is, what is the last is the page-18 element of PQ muscles, that is, what is the last element 3D, which is the last element, what should it be in the lineage of plus, but how many different can this plus 4 become? If it's gone then check it here, the condition proper difference is not of one, there is more than one reason, keep helping, keep doing and what have you printed, President Lemon and here I have made its length 80 inches more, if this, then from here you can like this Ghrit if you subscribe to both of them and now in the last people could not do anything. Language has been monitored. Which one is this? Click here that we are left with Allo picture Doraemon and check why its length is not less than the entry S. One - There - There - There is no less than 0513 lag increase in Britain and France and if nothing like this happens in France, there is no story, then at the end of the whole day, the proven points converge. Today's video is definitely long but you have to watch it because Concept is important, this is the concept that we do backtracking honey, if ever backtracking is left by our enemies, then I will tell them this, if you do not understand the question once, watch the video again, then the question is summed up with this, so guys please like this. Video Dhan please comment channel subscribe The Channel and see you in tomorrow's next video Tata Good Bye | Split Array into Consecutive Subsequences | split-array-into-consecutive-subsequences | You are given an integer array `nums` that is **sorted in non-decreasing order**.
Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true:
* Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** more than the previous integer).
* All subsequences have a length of `3` **or more**.
Return `true` _if you can split_ `nums` _according to the above conditions, or_ `false` _otherwise_.
A **subsequence** of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., `[1,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,3,2]` is not).
**Example 1:**
**Input:** nums = \[1,2,3,3,4,5\]
**Output:** true
**Explanation:** nums can be split into the following subsequences:
\[**1**,**2**,**3**,3,4,5\] --> 1, 2, 3
\[1,2,3,**3**,**4**,**5**\] --> 3, 4, 5
**Example 2:**
**Input:** nums = \[1,2,3,3,4,4,5,5\]
**Output:** true
**Explanation:** nums can be split into the following subsequences:
\[**1**,**2**,**3**,3,**4**,4,**5**,5\] --> 1, 2, 3, 4, 5
\[1,2,3,**3**,4,**4**,5,**5**\] --> 3, 4, 5
**Example 3:**
**Input:** nums = \[1,2,3,4,4,5\]
**Output:** false
**Explanation:** It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
* `nums` is sorted in **non-decreasing** order. | null | Array,Hash Table,Greedy,Heap (Priority Queue) | Medium | 347,1422 |
509 | hey everyone welcome back and today I'll be doing another lead code 509 Fibonacci number and easy one a very famous One the Fibonacci number commonly denoted as FN from a sequence called Fibonacci Sequence such that each number is the sum of the two preceding ones starting from zero and one that is like this and now we are given a you can say the point at which we have to return the output so the num at 4 we will have like 0 1 and 2 and 3 then if we have at 4 we are going to have the output 3 that's why we are going to return 3 at 3 we have two and at 2 we have one so that's it and there are two methods to do this recursive and iterative so first of all we will be using the recursive method in which if the number equals I or the number equals this is our exit case so if the number is like this we can just return and in the else case we can just simply say like self.fib we can just simply say like self.fib we can just simply say like self.fib call the function itself and at first subtract minus 1 and add it with self Dot babe calling the function again and subtracting 2 from it so this is it like this will work and the recursive solution is pretty slow and what we'll be doing is just making in the iterative one we'll be using a previous value which will be previous we'll call it previous one and previous one will have the value of 1 because it is like this is previous two and the one here will have previous uh this is previous one because this was more closer and previous two will be like zero so 0 and now okay done so for I in range of starting from 2 and till the number plus 1 because we do want to include the number itself the range itself you can say so after that we can just append add basically so previous to will be updated by previous one and previous one will be updated by output and after that we can just return our output and that's it as you can see the iterative portion solution was uh very you can say uh memory consuming dot memory consumed but the time complexity was high and in the iterative one it was like much less much lesser than the recursive one so that's it | Fibonacci Number | inorder-successor-in-bst-ii | The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30` | null | Tree,Binary Search Tree,Binary Tree | Medium | 285 |
7 | hey guys in here and we're doing a easy problem on Lee code the seventh problem reverse integer and it is indeed quite easy so it gives us an input of say one two three and we just need to return three two one but this is an integer so we can't just reverse the string but we can convert that integer into a string and then reverse the characters and then turn it back into a digit and we also have to retain the minus sign and will truncate any zeros and okay so let's get started so first we'll try one way of just converting it to a string reversing characters and then we'll actually do it by without converting it to a string okay so first the easy way the string way so we'll need to retain the sine of X so we'll say X sine numb and that will just give us a negative one if it's negative and a positive one if it's positive and we'll multiply this by the result that we're gonna return and so for the result we're gonna take the absolute value of x so this so that we don't have the minus sign at the beginning because if we reverse a negative number then we're just gonna have a minus sign at the beginning whenever we turn it back to a number and that's not gonna make sense it's gonna return an error and so then we'll need to convert this to a string then we'll convert that string to a bunch of characters and then we'll reverse the characters and then when we need to turn this back into a string so we can use the collect function with the turbo fish for the string inside so this creates this will collect all these characters into a string again and then we'll need to parse that into an integer so we'll need to use another turbo fish of I 32 and but if and so that's going to return a results which will have an error or if it's an overflow so if basically if they give us as integer like this it's fine when you get forwards but when you go backwards you have a nine there instead of a one and that's gonna overflow the 32-bit and that's gonna overflow the 32-bit and that's gonna overflow the 32-bit integer so if that happens this is going to return an error but if it's okay we'll just return the number inside and okay so we can just unwrap that so if we just left it like this is gonna panic if there's an overflow but if we add an or then we can give it a default value so if there's an overflow it tells us sieve it a default value of zero so this should work famous last words so let's go ahead and give this one a try so this is our non optimized solution so that's right now this should be yeah two point one and so if we do this without converting it to a string we should be able to get down to that two megabytes that we got right there okay so how do we do that so what we're gonna do is we're gonna have two variables Ryan have R which will be zero so that's our four result and then X will equal we'll say X as an I 30 I 64 though because when we're working with it we don't want to have an overflow as we're trying to convert to because we're R will just be a high 64 and then if there's an overflow will test for overflow at the end so we'll say I 32 at the end and then we'll try to get an i-32 from R then we'll try to get an i-32 from R then we'll try to get an i-32 from R which will be in I 64 and we'll say unwrap or zero like we did before so that will give it a default value of zero if there's an overflow but R is not gonna I 32 doesn't have this try from by default so we'll have to import that into our scope from the standard from the convert library from the standard library the convert module to try from trace a little sick that's why my voices will offer right now okay so then we'll say well X is greater than zero because we're gonna be or is greater than zero because we're gonna be dividing X by ten taking the remainder and adding that to our and then multiplying our by ten so basically the that's going to take the ending of X so the three we take the remainder of X divided by ten so that would be three and we add that to our so our is now three then we multiply our by ten so ours now 30 we divide X by 10 and so now X is 1/2 so we've got 30 and 12 so now X is 1/2 so we've got 30 and 12 so now X is 1/2 so we've got 30 and 12 and then we just take the remainder of that divide 12 divided by 30 so that's going to give us a 2 we add that to the 30 so that gives us 3 2 so 32 so now we've gotten the first two of our result and we just keep on doing that taking the end of X and adding it to the in the part and Addington so that's pretty clever I didn't come up with that I think a lot of people have used that so I don't I wouldn't know who to credit so we'll say our plus equals x divided by the remainder of X divided by 10 and then we'll multiply X by 10 and actually we need to multiply this first so we're gonna move the character still left first and then add the remainder and so then we'll just divide X by 10 and so I think this should work let's see okay so this doesn't work because whenever X is negative it's already going to be greater than zero so we'll have to get the absolute value of X rather than just X by itself and that works so we'll paste this into leap code and see if we can get this to work see if we can get two megabytes that's our goal probably should pay for that oh two point one if we ran it again it would probably be we'll just run it again cuz I'm pretty sure it's gonna be - okay so two sure it's gonna be - okay so two sure it's gonna be - okay so two megabytes so you slightly less memory is it really gonna matter probably not but hey this is an educational video ok so join me in the next video which is going to be number eight straight to integer | Reverse Integer | reverse-integer | Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1` | null | Math | Medium | 8,190,2238 |
20 | hey everyone welcome back to the channel i hope you guys are doing extremely well so today we will be talking about balanced brackets basically you will be given a string which contains brackets of six kinds one is this kind that is the opening bracket this is the corresponding closing of that this is another type and the closing type is this there's one more type that's this and the closing type is this so these are the uh six or three basically three types of brackets that are given to you and you have to tell if the string is a balanced bracket or not now what does that mean if you carefully observe this is an opening bracket for which i have a closing bracket so this opening has been closed this is an opening bracket so this is an opening bracket for this has a closing bracket so these two are closed this is an opening bracket for this there isn't closing bracket again for this there is this guy i can see every bracket is balanced hence i can say this string is a balance bracket now let's check this out i can see this opening has this closing but i cannot see for this closing and opening bracket hence i'll say this is not a balanced bracket what about this if i give you this string again this is not balanced because for this opening i know there is a closing but that's on the opposite side it's very important it should have been on the other side similarly if i ask you is this balanced or not again you cannot say that this is balanced this is also not balanced why because for this opening this closing comes in but apparently for this opening this closing should have been that's why this is also not a balance bracket sequence simple one before moving on to the next part of the video let me tell you about coding ninjas now coding ninjas is one of the largest coding education company and they have taught around 50k plus students now they offer you courses in programming in different languages like c plus java python they also have courses for machine learning android development data science and web dev the content quality is exceptional as it is made by experts from iit stanford amazon and facebook they do offer you one is to one doubt resolving support and the average doubt solving time that they take is literally the best in the market now since the courses are really well structured and so many have benefited from it i guess you should give it a try and if you feel so we use the link in the description to avail a discount which will be added above the one which is already present in the website so guys go and check it out so in order to check if this given string is a balance bracket or not we have to use stack data structure which is a last in first out data structure now if you don't know what is the stack you can definitely watch my previous videos so what you'll do is remember this whenever it's an opening bracket now the opening brackets can be of these kinds this one or this one whenever it's an opening bracket please push it into the stack so let's start iterating the first time i have an opening bracket just take this opening bracket push it into your stack next move to the next element this is again an opening bracket take it and push it into your stack next this is a closing bracket now remember whenever yes whenever you get a closing bracket it can be of this kind any of the closing brackets you get check if the stack is non-empty i see check if the stack is non-empty i see check if the stack is non-empty i see the stack is non-empty that means for the stack is non-empty that means for the stack is non-empty that means for this closing there might be an opening that should have like there should be an opening if the stack is empty that means it is not balanced so i see the stack is non-empty take the top most the stack is non-empty take the top most the stack is non-empty take the top most out and take the current guy and see if they're opposite and if they're opposite i can say for this closing i have a corresponding opening hence i can move ahead and i'll move her to the sky again it's an opening whenever it's an opening please make sure you put it next it's an opening again if it's an opening please make sure you put it in next step this is again an opening please make sure you put it in to your stack next step what is this is a closing bracket again if it's a closing bracket you check if there exists an opening in the stack that means stack is not empty or not stack is non empty take out the topmost guy and compare if they're opposite they are i can say for this guy i currently have one of its opening bracket hence i'll move to the next guy what is the next guy and closing so i need a corresponding opening let's look at the stack the top guy just take it out is a corresponding opening yes it is so i can say this guy also has a corresponding guy so i'll move next now when i move next i have again a closing so if i again have a closing can i say again i look at the stack so the moment i look onto the stack i get disks and these are again opposite so i can say this is also balanced hence i'll move ahead to the last guy the moment i move to the last guy i again take this guy out and i see if they are opposite and i see that they are opposite hence i can say the last guy is also balanced and i move out now when i move out the stack has to be empty yes this stack has to be empty which signifies that everyone got its corresponding opening and closing and since we got it we can say that this given string is a balanced string now let's check out with one more example where the string is not balanced let's take this small example to check if the string is balanced or not so at first this is an opening bracket whenever it's an opening put it into your stack next move to the next guy so again which bracket opening put it into your stack next move wedge bracket opening put it into your stack next move which bracket closing if it's a closing bracket please take out the last element of the stack and check if they are opposites i see they are opposites so i can definitely move to the next guy when i move to the next guy that's in closing so i'll take the top of the stack and these are not opposite and if they're not opposite you can definitely return saying that it's not balanced this doesn't have it's not balanced because this guy did not find its closing hence i can say it's not balanced now what is one more case if i talk about one more case uh let's take this case when i say i have this okay so over here what we will see is we go over here it's an opening i put it into your stack right next i go over here it's an opening i put it into your stack next i go here which is a closing so if this is a closing what i'll do is i'll take the topmost guy and these guys are opposite at their opposite i will definitely move this guy ahead to the last guy hence the complete iteration is over and i did find everyone balanced but the stack is not empty which means for this guy i did not find a no closing one hence this string is unbalanced so these are the three cases that you need to take care if there has been an opposite we can keep on continuing if they're not opposite it's unbalanced and if at the end the stack has to be empty there this there's one more case you need to also take care of imagine uh it starts like this okay so in this case if this is a closing one if this is a closing bracket the stack will not have anything so if you have someone as a closing bracket and the stack doesn't have any one which means it doesn't have any opening hence you can say it's an unbalanced one so these are the cases you need to take care while writing the code so now i'll be moving on to the code let's check out the code with all the edge cases covered so i know i have a string so first i have to declare a stack so let's declare a stack so this is how i'll declare a stack and now what you'll do is you will try moving in from i equal to 0 to i lesser than n which is the string size and you'll keep on moving now what will you write can i say if it's an opening bracket i don't have to be doing anything like if it's an opening bracket like if it is this bracket or if it is uh this bracket or if it is the other one then can i say i actually don't need to do anything i will take this stack and i'll say hey can you please push in this uh string of i so he does that but what if it's a closing bracket then the else will come in yes then the else will come in that's very important if inside this else i see the stack is empty if the stack is empty can i say for the closing bracket i did not have an opening bracket hence i can say return false which means it's an empty the stack is empty that means it doesn't have an opposite one but what if it does have then what you'll do is you will take this character c equal to s t dot top yes kindly take it and right after that you can definitely do an st dot pop so that guy gets out of the stack so your current character is st talk now you know one thing if your s of i is equal to this closing then your c has to be this opening this is one of the cases similarly i can have the other three cases for three brackets and if any one of the three if statement is satisfied that's completely okay but if any of these three doesn't satisfies and i come to this else then i can say return false if any of these three doesn't satisfy then i can say return false and this is where my for loop will end once this for loop execution is over what i'll do is if the stack stands empty yes if the stack stands empty after the entire for loop execution if it stands empty i can say it's a balanced bracket or else i will say it's not a balanced bracket this is how the code will look in order to check for balance bracket if i talk about the time complexity can i say i'm just i treating on a string which makes it a big o of n now can i say the space complexity that i am using is big o of n because i'm using a stacked data structure apart from that i don't see anything but please make sure you do a stack dot empty check before doing a stack drop talk because the stack has to have relevance in order to execute stack dot top otherwise it will give you run time error so guys this will be it for the balance bracket explanation and the code i hope you've understood that explanation just in case you did please make sure you like this video is | Valid Parentheses | valid-parentheses | Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`. | An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards. | String,Stack | Easy | 22,32,301,1045,2221 |
93 | hello and welcome to this video on the implementation of an algorithm on how to restore IP addresses from a given string we will start by discussing the problem statement and the input and output of a function the problem statement is to take a string as input which represents a number and restore all possible valid IP addresses that can be formed from this number the input to a function is a string and the output is a vector of strings containing all possible valid IP addresses now let's dive into the code and understand how it works we start by creating an empty Vector of strings called answer which will store all the valid IP addresses we find we then use four nested for Loops where each loop iterates from 1 to 3. the outermost Loop is for the first segment of the IP address the second Loop is for the second segment and so on inside the nested Loops we first check if the length of the IP address is equal to the length of the input string if it is not equal we continue to the next iteration if it is equal we then extract the four segments of the IP address using the substring function and store them in variables S1 s to S3 and S4 we then check if each segment is less than or equal to 255 which is the maximum value of a segment in an IP address if all segments are valid we then convert them to string and concatenate them with dots in between to form the final IP address we then check if the length of this final IP address is equal to the length of the input string plus 3 which is the number of dots in the IP address if it is equal we add this IP address to our answer vector finally we return the answer Vector which contains all the valid IP addresses that can be formed from the input string and that's it with this code we are able to efficiently find the number of valid IP addresses from a given string I hope this tutorial was helpful and if you have any questions feel free to ask in comments thank you for watching | Restore IP Addresses | restore-ip-addresses | A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.
* For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses.
Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order.
**Example 1:**
**Input:** s = "25525511135 "
**Output:** \[ "255.255.11.135 ", "255.255.111.35 "\]
**Example 2:**
**Input:** s = "0000 "
**Output:** \[ "0.0.0.0 "\]
**Example 3:**
**Input:** s = "101023 "
**Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\]
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of digits only. | null | String,Backtracking | Medium | 752 |
97 | hey everybody this is Larry this is day 25 of the league of daily challenge hit the like button hit the Subscribe button join me on Discord whoops what did I click on join me on Discord let me know what you think about today's poem uh yeah okay today's firm is interleaving string number 97 I give an S1 S2 S3 fine weather S3 is formed by an interleaving of S1 and S2 okay I mean uh to bounce are small enough this is a very canonical um uh dynamic programming problem um I feel like we've been doing a lot of dynamic programming problems lately or maybe it's just me getting confused about it uh yeah I mean the follow-up is easy if you are very the follow-up is easy if you are very the follow-up is easy if you are very practicing dynamic programming and the other parts are also straightforward if you've done it I don't really have much to add today maybe I'm just a little bit tired to be honest which I apologize uh just came back from the gym but basically the idea is try to think about uh ways you can think about boot forcing right and in this particular case well if you have S1 S2 and S3 then if the first character is the same then you test whether the first character of a S3 is from S1 or S2 and then you can't just keep on doing it you know in that way I think that's really it I don't know that there's anything um no that's the The Brute Force version of it and of course the way to think about it is that now you're trying to process this the rest of the string as a suffix and of course the suffix is always going to be the same for a given strain so you can represent that with using a number which is usually you know the index or something like this is what I do right so yeah so maybe I would say like uh it's possible or something uh so then you have Pi 1 I2 I3 technically this looks like n Cube because it has three inputs you know 100 we'll figure it out later on the memorization uh 100 times 200 but still n Cube or 100 Cube anyway um but we'll figure that out later right so basically if uh I three years ago to N3 they don't they hmm I assume S3 is length is equal to these two added I don't know if it's worth doing a check for it uh but maybe it is right so yeah if N1 plus N2 is not equal to length of S3 return force uh but yeah otherwise if I three is you go to N1 plus N2 then basically we've done everything so this is returned true uh because now you're basically matching an empty string if you look at the I3 suffix of this um of course this assumes that this is same as what happened uh and three which I guess we'll just write it why not but maybe that's just more straightforward uh yeah and then now we just have to check both cases right which is if S1 of i1 is equal to S3 of I3 and of course we have to make sure that i1 is less than N1 meaning that we still have strings left or characters left on the S1 string then we can um and if this is possible and is possible of 5 plus 1 I2 I3 plus one then we return true we also by you know in a similar way do the same thing for you know um for S2 meaning the next time uh we take the first character from I uh from S2 instead otherwise we return first and that's pretty much it I mean this is Rave before us uh where that's basically the concept right and of course I'm not going to submit it but if I do submit it this is probably going to time out um especially if it doesn't work like we'll do even just like a reasonable one right so this should time out if not then technology is fast hmm it's actually surprising actually hmm you take both every time I guess two did it I got lazy this is only two to the ten I guess I can double it um all right now two to the Chinese maybe it should be slow enough but I guess if not then we'll just I mean my point is still that you know uh it is two stones and now you have to do the memorization right yeah there you go uh yeah the thing to notice is that there is an invariant which is i1 plus I2 is equal to I3 right this is always going to be true and as a result um uh two of the variables determine the dirt it doesn't matter which one you choose to I wouldn't say a word but just like you know but that's always going to be the case so now uh yeah so you can just take any two even though I one can go from zero to N1 I2 can go from zero to N2 I3 can go from zero to N3 but like I said only two of them can be fixed right because the third one is uniquely determined by the other two so yeah so in this case it is actually just n square or N1 times N2 uh yeah so let's actually memorize on that then right now that we can as I said you don't even need to consider I during the caching oops because it is literally the same but uh otherwise yeah this part it's a little bit funky because of the early termination but yeah we'll just fight it out you could buy by this in a queen of way but uh I mean well the queen of it is probably just to use uh the decorator but um trying to be a little bit well yeah okay oh I was in extra space Oh I might just Play Store uh let's send text our parents I have them backwards so I one could go to N1 oh wow I knew I added a plus one on this part we forgot to add on this part for some reason that's weird but yeah so this looks much better let's give it some it and there you go apparently I've done it three times before so but yeah uh what's the complexity space and time here well the complexity for space and time is going to be N1 times N2 in both cases because I mean you can kind of the reason why I write it out this way and people ask me why I don't just you know especially even in the teaching but I don't just write out cash because there are scenarios in which you know um the range of the parameters is not necessarily the complexity right and here is much easier to see the upper Battle of the space and time complexity if you kind of write out the Matrix like this right the two-dimensional array this right the two-dimensional array this right the two-dimensional array like this uh yeah so it's gonna be N1 times N2 and the follow-up is can you do times N2 and the follow-up is can you do times N2 and the follow-up is can you do it in additional uh only um o of N2 and one whichever shorter uh memory and the other yes you can this is top down uh memoization you can actually rewrite this as Bottoms Up and when you do there you can use the space optimization trick I'm not going to go over it that much in this video I have a video for it if you want to kind of learn more about it don't remember the problem that I go over in that one but the idea is still pretty much the same so yeah um anyway let me know what you think stay good stay healthy took a mental health man this week is going by quick I'll see y'all later and take care bye | Interleaving String | interleaving-string | Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`.
An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that:
* `s = s1 + s2 + ... + sn`
* `t = t1 + t2 + ... + tm`
* `|n - m| <= 1`
* The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...`
**Note:** `a + b` is the concatenation of strings `a` and `b`.
**Example 1:**
**Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbcbcac "
**Output:** true
**Explanation:** One way to obtain s3 is:
Split s1 into s1 = "aa " + "bc " + "c ", and s2 into s2 = "dbbc " + "a ".
Interleaving the two splits, we get "aa " + "dbbc " + "bc " + "a " + "c " = "aadbbcbcac ".
Since s3 can be obtained by interleaving s1 and s2, we return true.
**Example 2:**
**Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbbaccc "
**Output:** false
**Explanation:** Notice how it is impossible to interleave s2 with any other string to obtain s3.
**Example 3:**
**Input:** s1 = " ", s2 = " ", s3 = " "
**Output:** true
**Constraints:**
* `0 <= s1.length, s2.length <= 100`
* `0 <= s3.length <= 200`
* `s1`, `s2`, and `s3` consist of lowercase English letters.
**Follow up:** Could you solve it using only `O(s2.length)` additional memory space? | null | String,Dynamic Programming | Medium | null |
906 | welcome to maisley code challenge today's problem is super palindromes let's say a positive integer is a super palindrome if it is a palindrome meaning it's the same forwards and backwards and it's also a square of a palindrome now given two positive integers left and right represented as strings return the number of super palindrome integers in the inclusive range from left to right for example if we're given four to a thousand there's going to be four super palindromes notice how the square root of each one of these is going to also be a palindrome so here two i guess that counts as a pandome three eleven is a palindrome and this uh i actually don't know what that is what one two one maybe no one two i don't know but whatever this is um the square root of this is a palindrome as well okay so what we want to take advantage of here is there's actually not that many super palindromes even in this huge range from 1 to the 10 to the 18th power there's really not going to be that many super palindromes that we can calculate so what we'll do is first calculate all the possible super palindromes all fossils two pound growths now to begin uh we might start with saying okay well let's make some sort of list and say four i in range of one through ten to the what 18th power but we don't actually need to do it to the 18th power we can do to the ninth because we will be um appending to this right here i to the square so we know it's going to be within the range right here we don't have to do it all the way to the ninth power but this isn't gonna work and the reason for that um is a little bit confusing but basically i think they just set the constraints so that even one two like running it one to the ten to the ninth power is too long time exceeded so even this right here is not going to work so what could we do then um well uh we know that it needs to be a square right we also know this number that we generate to begin with this i needs to be a palindrome right so what we might be able to do is say for the number um 12 right what we'll do is say okay there's two possible power nodes we can calculate here we can calculate one two one and we can also do one two one these are two pound rooms that we can make with this number same with like 13 say or any number for that matter like one three four we have one three four and then three one and then one three four 4 3 1 right and what we'll do is get these numbers that we generate and square them and that's going to be some of the candidates that we can make and put them into this list here so let's start off by doing that and if we do that actually we don't need to do it to ninth hour we can do it i think up to the fifth uh i believe okay so how will we do this well let's first generate our numbers and i'm going to call it odd and even the reason being it's going to be an odd number of digits or an even number of digits right so what we can do then is see here um i'm going to convert to an integer and we're going to say get the string of i plus string of i but um get rid of the first character sorry and we also need to reverse it right so we need to reverse that uh let's see you can do that by just saying it like this and then we got squared by two let's do the same thing here but with the string i will add it to string i again but reverse it again we will square it by two so let's see string i let's write this so let me first make sure this even works um what we'll do is we'll say like look if odd equals the other integers so string odd equals string odd reversed it's a pound row so we're going to add the odd to nums and the same thing here if string even is equal to string even reversed then we'll add that now let me make sure this works i may have missed something so let's see okay so that looks like it's working i can't be completely sure yet but we can see that it is possible that we'll have some um repeating numbers here so and it might not be sorted either because we're doing odd and even digits so what we'll do take care of that we will see we'll make it into a set first take it back into a list and then we'll sort it okay now all we need to do is uh for all the numbers here in nums we'll add it to an output let's say if this number is let's see against left this some bounds of the left side and it's imbalance of the right side and we're going to append it to our outfit and then let's return the length of this outfit so let's make sure this works okay that looks like it's working one thing to note is this actually won't work and the reason for that is every single test case that we run it runs this whole thing again and again so to kind of avoid that and save some time what we'll do is actually put it on top here in the class and this will kind of guarantee that this runs just once and afterward we don't need to worry about running it again and again um so this would become a self variable so that would mean i have to go soft on numbers here let's make sure that works one more time it still works let's buy some fat and there you go accepted so time complexity i actually don't know it's like log of n times n to the something power possibly but it's really confusing because i do all sorts of weird things so i'm actually not entirely sure what the time complexity is on top of that i had to kind of put this up in here to get this to work if i you know just did it normally and put it here for some reason it doesn't work and it's probably because it's running this algorithm and again even though it works like since we're running this every single time i guess it kind of fails to test cases which is unfortunate because my logic is sound it's just the way that's that it's set up won't allow it to complete a time so that's annoying all right well i hope that helps thanks for watching my channel remember do not trust me i know nothing | Super Palindromes | walking-robot-simulation | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null | Array,Simulation | Medium | 2178 |
134 | i'm just preparing to record this video and yeah i'm ready all right let's get started welcome to this video in this video we're going to solve this coding interview question gash station in this problem you are given to every cash and cost the cash array represent the amount of cash is station hedge and the cost array represent the cost that means the unit or the amount of gas required to visit from one station to the next station from this station to this station the cost is three from this station to this station the cost is four from this station to this station the cost is five from this station four to the station five the cost is one and from this station five to this station one the cost is two this two array forms a circle the gas stations are located in a circular route let's see how the route look likes now let's write out the index number the index of this element is 0 1 2 3 4. let's draw a circular route let's assume this is our circular route in this route we have a total five gas station one two three four five one two three four five now in each stations i'm going to mark it with the index number this is the station number zero the station number one two three four these are the index number this station zero contains one unit of gas this station contains two units of gas this station contains three units of gas this station contains four unit of gas and this station contains five units of gas this is the logical representation of this array now here we have this cost array from this station to this station in order to visit from this station to this station the cost is 3 unit of cash from this station one to this station the cost is four unit of gas from this station from the station to the station three in order to visit this station three from this station to the unit of cash record five from the station three to this station four the unit of cash record one so one initial cash required and from the station four to the station zero the amount of cash required is two now our job is to find out at least one station from where we can start the journey and we'll end up at that station that means if we choose a station as our starting station then we have to visit that station in clockwise fashion this is the problem we are given this two array and this is the logical representation of this true array now if we take this as our starting station here we see amount of gas we have one in order to visit this station the recurrent gas is three unit so here we have one in job cash but we need three unit of cash so we cannot visit from this station to this station the cash will run out in between this station so we cannot visit from this station to this station so we cannot start at this station let's try to start at this station if we start at this station the amount of gas we have here two and the required gas to visit the next station is four so we cannot start at this station as well now this station in this station the amount of gas we have three unit and the gas is record to visit the next station is 5 unit so we cannot start at this station now let's try to start at this station 3 here we see the amount of gas we have in this station for and the required guys to visit next station is one so we can start at this station let's start at this station then in these stations we will have four minus one three unit of gas and in this station we have five unit of gas so three plus 5 equals to 8 in this stations total we will have 8 unit of gas if we start from this station now from this station in order to visit this station we need to unit of gas but here we have 8 unit of gas so we can visit this station from this station so 8 minus 2 is 6 plus 1 is 7 so in this station we'll have seven units of cash in our car now can we visit this station from this station here seven unit of gas we have and record gas is three so we can visit this station seven minus three four plus two is six so here we'll have six unit of gas in our car now can i visit this station two from this station one the required gas is four and we have six units of gas six minus four is two plus three is five so in this station we will have total five unit of cash now can we visit this station from this station two the recovered gash is five and in this station we have total five amount of or five units of gas so we can visit this station if we visit this station we are left with zero init of gas and we visited the starting station so we find out a starting station from where if we start the journey in a circular route in clockwise fashion we can find out that station so you can see if we start at this station we can visit this station in clockwise fashion so if we start at this station we can visit this station in clockwise fashion in this circular route so we can start at this station now we have to return the index of the starting station so here we started the output for this input is the index of this station is three that means this is station so we can start at this station we can have more than one station where we can start the journey so that we can visit that station in a circular fashion in a route or in a circular path so for this given input the output is 3 this is the problem we're giving this true array we have to find out the starting station so that we can find out that station in clockwise fashion in a circular route now how we can solve this problem bit of tricky to understand but don't worry stick to this video till the end the first formula of this problem is that first we have to compute the total cash and we have to complete the total cost if we find out total cash is greater than or equals to total cost then we will have at least one station where you can start our journey such that we can visit that station in a circular route so this is the formula we will use to solve this problem this is the core intuition this is the orientation the total gas must be greater than total cost so we can calculate total cash and total cost by iterating this array instead summing all the element for cash and cost array we will find out the difference cash i minus cost i okay g4 gash and c4 cost we'll find out the difference here the difference is 3 minus 1 is minus 2 here the difference is minus 2 3. if we add all the difference we get zero if we get zero that means total cash equals to total cost if we find out a negative value here that means total cash is less than total cost here 1 plus 2 3 plus 3 6 plus 4 is 10 plus 5 is 15 total gas is 15 and here 3 plus 4 7 plus 1. 8 plus to 10 plus 5 15 we see total cash equals to total cost by summing the difference of cash and cost at these stations we can check these conditions by defining our difference and adding the difference we can check this condition either true or false so this is the intuition after finding out this condition is true then it's okay we have to find out the starting positions that means the starting station index if this condition is false we don't care we'll written -1 now let's see how to find the starting station first we're going to use here two variable position equals to minus 1 this is our initial value now we're gonna declare a variable current equals to the gas index i minus cost i will find out the difference after finding out the difference if we find out if current is less than zero then we'll set the position to i and we will set current to zero that means the current station for our current iterations will see the implementation don't worry if we find out the difference is less than 0 that means we cannot start at our current station we're setting position equals to i the current station index and here we're assuming that the next station can be our answer it means that we can start at the next station so next station can be the starting station of this index i okay now let's see how it works initially position equals to minus 1 and current equals to 1 minus 3 minus 2 so current equals to minus 2 is less than 0 so we'll set position equals to the current index 0 it means that the next station that means this station can be the starting station position equals to 0 means the next station that means this station 1 can be our starting station so the next station can be the starting station and current equals to zero we're setting current to zero now here we're gonna find out for the next iteration to minus four cost gash unit of gas minus cost minus 2 so we'll set this station index as position and we'll set current to 0. here it means that this station can be the starting station okay we'll see when will implement the code now for this station 3 minus 5 is minus 2 so minus 2 is less than current so we'll change the position to 2 it means that the next station that means this station can be our starting station and we'll set current to 0. now here we see that in this station we see that we have 4 minus one now what we're going to do we're going to now here what we're going to do we're going to find out the difference cash and cost that is three okay we will see this implementation this code implementation don't be confused about it we will have something like this plus equal to and let's assume this is our loop and on the top of loop we will have particles to zero something like this don't be confused i'm using this pseudocode or the algorithms just to make you understand this tricky question now here at this point we'll have current equals to 3 so let's write out here current equals to 0 plus the difference 4 minus 1 that is 3. now we see that this condition is true so will not change this position so this the next of this position that means the next to this position 2 this can be our starting station we don't know but it can be the starting station now let's move forward let's move to this station in this station we see that we have total three when we move our car to this station we're left with three unit of gas from this station because cost is one and in this station we had the four unit of gas so we will add this gas that means five plus 3 5 plus 3 equals to 8 but when you move to the next station we have to subtract this 2 from this gas so 5 minus 2 equals to 3 plus 3 equals to 6. now we see that here this is false so still this next station of this station can be the starting station okay now when you move to this station we are done and we'll have total equals to zero we'll calculate total right here we'll show you how to find out the total that means the difference the sum of the difference if the sum of the difference is a greater than or equals to 0 that means we'll have the answer now we're at the end of this array we reached at this station that means at this element now we have processed this element and we're left with this position two and this current six so if we start at this station we clearly see that we'll have three plus five eight and if we move to this station for these stations we will have six plus one seven unit of gas and we will see when we will go through the code but we don't have to go through all the way to this station in this circle or in this route in this circular route because we find out the sum of difference is zero so we don't have to worry about how many gas we have in the next station you might think this can be the starting station okay it's fine but when you're moving to this station from this station by considering this is our starting station we don't care how many gas we are using from this station to visit this station because we are not using any gas from this station we can have more than one station one valid station such that we can find out that station in a circular route so this is the intuition of this problem this is a little bit tricky to understand but don't worry try to go through their own examples then it will make sense now let's code of this problem let's create a function can travel this function takes two parameter gas z for cash and cost c for cost this two array now here we're going to declare a variable position equals to minus one initially total equals to zero this total will hold the sum of the difference of this cash i minus cost i then here current equals to zero now we're going to run a for loop for i from 0 to dash dot length minus 1 you can use here cost that length minus 1 because the length of this two array at the same now inside we're going to calculate the difference equals to g i minus c i minus cost i now we're going to calculate total so total plus equals to difference and we're going to add to current plus equals to different now we're going to check if current is less than zero then what we'll do we'll set position to i it means that the next station can be our starting station we are saying the next station came with the starting station because if we because when we return will written position plus 1 if the total equals to greater than or equals to 0 and let's set current to 0 to find out the starting station now at the end of this loop right here we're gonna check if total is a greater than or equals to zero then we will return the next station that means position plus one this is why we are saying will written the next station can be the starting station if not we will return -1 return -1 return -1 this condition similar to total cash greater than or equals to total cost okay this condition is similar to this condition we're checking this differently using one loop so we're solving this problem it's in single patch this is the algorithm to solve this problem so here when we find out the last station that means the last element in our array when you move to the last iteration then we will just check we will just compute the position here that we are computing just the position the goal here is to find out the position first we have to find out this condition total cash greater than or equals to total cash is greater than first you have to find out this correlation total gas is greater than or equal to total cost and you have to find out the starting station from here we can start our curve this is the intuition and if you're understanding this condition then you can solve this problem pretty easily if you find out a starting station for finding out starting station you might be confused at first look but if you try with couple of examples then it will make sense you'll be stuck at the point when you are done with the last iteration you are no longer moving all the way to the this station the starting station because we don't have to check the starting station if this condition is true and if we can visit the last station from any of the station from starting station if we find out current is greater than or equals to zero then we will have our answer if it satisfies this condition so if we find out current is greater than or equal to 0 and this condition total gas is greater than or equals to total cost if you find out this condition in the last iteration if you find this condition is true then we will have the starting station at position plus one okay this is the algorithms here if we see this condition is true then we don't have to check this condition will be always just true if this condition is true so we can discard it if we find out this condition then we will have at least one station from here we can start the journey in the circular route this is my solution to this problem hope you have understood this video explanations if you are new to the channel subscribe to the channel like share comment and i'll see you in the next video | Gas Station | gas-station | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104` | null | Array,Greedy | Medium | 1346 |
88 | hey everyone welcome back and let's write some more neat code today so today let's look at leak code 88 merge sorted array so we're given two input arrays nums one and nums two and we wanna take nums 2 and then merge it into nums 1 into 1 sorted array now lucky for us we are guaranteed that there is enough space in nums 1 for every element in nums 2 to be inserted and we want to make sure that they're in order now what if you just want to kind of be lazy let's say you got these input arrays nums 1 and nums 2. it seems kind of annoying having to merge them into nums too what if we want to be really lazy we can just create a fresh copy a fresh not copy but a fresh empty array with the same number of elements as nums one and then just take and then we can start at the beginning of each of these arrays numbers one and nums two take the smaller element insert it into the new array and then we can repeat that process the smallest element and then we can just keep doing that two three five six but this array is temporary right because they want the answer to be in nums one so what we could do is then just copy this into nums one the only problem with this solution is while the time complexity is big o of n we also need extra memory we need this temporary array but is it possible to solve this problem exactly how they want us to solve it with without actually needing this temporary array because if we don't need the temporary array we don't need the extra memory then the memory would also would be big o of one so let's see how we can solve this problem the most optimal way okay so when you draw it out like this the first thing you notice is that there's the empty space is at the end of nums one so if we're going to start merging these values why should we start at the beginning and start like filling this way when it might just be easier to start filling this way if we want to sort it because there's already empty space we know that there's enough space over here for these elements to fit in no matter what right like that's guaranteed so i want to start merging from here so i'm going to initialize a pointer here this is where we're going to start merging it's the last value in nums now what value do we want to put here since we want it to be in order we want the largest value to be over here how do we get the largest value well we can start at the last real value in nums one and the last real well the last number in nums two because there's no empty space in nums two and we can compare these two values we see that six is greater so we don't need this anymore and we can replace it with a six and we also don't need this anymore so we can move our pointer of nums two over here now looking at the five and we're also done with this pointer we can shift it over here now we compare three and five we know five is greater so that's exactly what we can do we can replace this zero with a five and again we know we have to shift our pointers now so the last pointer is going to be over here now this is going to be the next position we insert into and this is going to be the next value from nums 2 that we look at so now we're going to compare 2 with 3. finally we get a larger value in nums 1. so we can get rid of this place it with a 3. once again let's update our pointers so last pointer is going to be over here now we got rid of one pointer replaced it with another this is going to be the value we look at in nums one and this time they're both equal two and two so it doesn't really matter which one we replace i'll use the first one so get rid of this and get rid of this replace it with a two now we got our last two values 1 and 2 is greater so we have no more values in nums 2 to look at we can insert this 2 here and so we're pretty much done merging because there's no more elements left in uh numbs2 but we only did five values right lucky for us the one that's over here doesn't really need to be changed so we can leave it there and you know our result is correct regardless okay so now let's finally code it up so in this uh function we're given nums one we're given m which is the lat which is the index of the last value in nums one not the length of nums one because we know it has uh some empty space at the end we got nums two and we have n which is the index of the last value in nums 2. so the first thing we want to do is get the last index of nums 1 like basically the length so i'm going to store it in last different way you might need to do m plus n minus 1. so the next thing we want to do is start merging them in reverse order so now that we have all three of the pointers we need last m and n let's start merging we're gonna keep going while there are elements left in both arrays so while m greater than zero and n is greater than zero we want to find this the largest value so if nums one of m is greater than num's two of n then we can go to our last position replace it with nums 1 of m the else condition is if they were equal or if nums 2 was greater so in that case we just want to do the opposite numbs 1 last it's going to be nums 2 of n uh one thing we should definitely not forget about is updating our pointers so since we're going in reverse order we're going to decrement m and decrement n regardless of which element we insert we want to decrement last regardless so now we've merged them and into inserted order we did it without extra memory and the result is stored in nums one but there's one last edge case that we forgot about let me show you so it was convenient for us that the smallest value was already in the position we wanted it to be in but what if these two values were the opposite what if this value was a 2 and this value was a 1 what would we have done in that case well we see that the 2 is greater so we would get rid of this and then put a 2 here but notice now how the empty elements are in nums 2 over here right so in this case what are we going to do we're basically just going to take all the remaining elements in nums 2 and then fill nums 1 with them right so we'll just put this one over here in this case there's only one value but if there were more values we would just keep going we would keep taking each value and filling it because this is already in sorted order so we can just take that sorted portion and then fill nums one that's exactly what i'm gonna do so fill nums1 with the leftover elements in nums2 and we're only going to do that if there are leftover elements and the condition for that is if n is greater than zero so in the last position numbers one of last is gonna be nums two of n and then all we need to do is update our pointer so n and last are both going to be decremented by one and hopefully this is bug free okay so this is actually not too bad of a bug we remember that indexes start at zero so we forgot to use the minus one and i think most of these so let me not forget and now it should work awesome so i tried to make this code somewhat more like readable and beginner friendly there are definitely more tricky ways you can do this as always thank you so much for watching please like and subscribe to support the channel it helps out a lot and i hope to see you pretty soon | Merge Sorted Array | merge-sorted-array | You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time? | You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution. | Array,Two Pointers,Sorting | Easy | 21,1019,1028 |
459 | hi all welcome to learn code repeat so today we will be looking at day three of the september lead code challenge so the problem is repeated substring pattern let's look into the problem so the problem is uh repeated substring pattern given a non-empty string pattern given a non-empty string pattern given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together so they have said that it's only going to be lower case character and it should not accept 10 000. so the example that they have given right this is a whole string and you want to find out whether there exists a substring which can form the whole string if it is repeated multiple times so here in this case i have a b i can repeat a b twice so once here and once after that it will form the whole string so this output should be true then i have a b a here i can't repeat any of the substring multiple time to form the own whole string here it's a b a i cannot repeat any of the string multiple times to form the whole string so the output is false and in this case if i check the first three characters abc it can be repeated three more times to form the whole string right so the output is true so let's see what logic we can use to solve this problem so let's take a string a b c d now if i want to check that if there exists a substring which if repeated forms this whole string right is one way is that for any string right if there is a repeating characters right which forms the substring the whole string right so if i divide by 2 right that means the length is 8 divided by 2 is 4 that means the minimum repeating character can be 4 right so here in this case the minimum repeating character can be abcd which is 4 and if i double that 4 it becomes 8 that will be the minimum at least right and if the string is something like abc so here abc is the character which is getting repeated right so in this case if you divide the length by 2 that is the minimum number of repetition that we can have if my string is having repeated substrings right to solve this problem is i will take the first character and repeat that till the length of the string so here i'll take a and repeat that 8 times so a 1 2 3 4 5 6 7 8 and then i'll check whether this string is same as my string s in this case it will not be same so i will go for the next iteration so my next iteration is earlier i just took a now i will take a and b that will be my substring which i will consider it that can be repeating so now i have to repeat a b so that it forms the length eight right so before even appending a b i can simply do a check that if i repeat it will form eight characters right how can i do that i can just divide my length of the actual string with the length of the substring and see whether the division is possible whether the mod is zero so in this case the length is two and eight is divisible by two so mod will be zero so it is divisible and i will just and also it will tell you what is the number of repeats that you have to do so if i divide 8 by 2 i will get 4 so that means a b needs to be repeated 4 times so we have repeated three times and this is four times and that will form the eight character so now again i will check whether a b is same as my substring no so i again in my next iteration i will append the next string abc and try to repeat abc but again before repeating i will check the length whether the length is 3 whether 8 is divisible by three whether the modulo is equal to zero in this case it is not zero so i know that even if i repeat abc multiple times its not going to form exact eight length so that means that cannot be a valid repeating substring for the source string ok so i will then go for the next which is d and i will check whether a b c d is repeating so again i will check the length of this substring is 4 so whether 4 divides 8 yes so 4 2's are 8 so that means i have to repeat abcd twice so i will repeat twice and check whether abcd d same as a b c d if it is then i have to return true now this operation you do not have to do till the length of the string because we know that as i said earlier that for a given string the minimum number of repeats that it can have is two right which is the length by two so we have to only go till length by two so our for loop the iteration that we are doing should only be happen length by two okay so let us look into the code so first thing we did was the we have to check if my length mod i equal to zero so this was the first check right that we were doing to check whether the length itself is divisible by our substrings length right so i is our substrings length oh here i give i equal to okay and i equal to length by 2. so inside this i'll now have to see what is the number of characters that i have to repeat right so into repeating character is equal to it will be length by i correct so this many times i have to repeat my characters so i'll use string builder to do the appending operation and here i am doing a substring of s from 0 to i now i will try to repeat that character once my strv is ready i will just do a two string on it and do equals yes if that is the case then i'll return true so what will happen is if my stair be same as s then it will return true else it will go for the next iteration so the way we are doing here right it checks with a first and then it will go with abc right so similar to that here also we are doing a for loop and then we are appending each and every string to my substring okay so if you are done with this for loop and still we have not received anything that means the substring is not the soil written false let us try this and see whether it works ok it is accepted there is one more way i have already done that in python so i will just go over that code so this is just two lines of code so ifs is not present then written false so one of the characteristic of a repeating substring is that if i append the same string twice right so what i am saying is abc is my main string if i append it again to itself right so the resulting string is abc this is my source string again i am doing appending this is my resulting string right now if i remove the first and the last character from it right this is what it would be remaining right if i remove the first and last now if i search my source string in this there should be a string that is present in this so here in this case there are two substring that can be repeated to form this main string right if i am again appending the same thing again here right in this main substring so here it was two substring here also it will be two sub string so in total there will be four substring which can be repeated right so four sub string will be there right but if i remove the first and last character right so the property of that substring will go away and there will be only remaining out of four since i am removing one character from the first and one character from the end right so the first abc character right i am removing a so this particular abc substring will lose its property of repetition similarly the last abc sub string will lose its property of repetition right so the remaining two will be this these two right so from the four there will be two gone right and two will be remaining so if i search now my source string into the string i will be able to find that in the string so let us take one more example right let us say put my example is abcd and abcd so here also if i append abcd twice this will be the string and if i remove this will be the final string right and now if i search this abcd whether it exist in this string right you can see the square right or the rectangle so it will be present in the middle so this way we can know that there is a repeating characters in this source string which forms the source string now assuming that if there are no repeating characters right assume that instead of a it was let us say c right so my if i now append twice here right and then remove the first and last character in this case if i search this right i am not able to find it here because it is not a proper repeating substring which forms the main string so that is one of the characteristics of repeating substring and we can explore that in this answer right so here we are doing the same thing we are appending sns again and then i am removing the first and last character and then i am just trying to search my main source string in my ss if i am able to find it then i will return true so here fine returns minus 1 if it is not able to find it so this is another way of doing the same thing i hope you liked my video please subscribe | Repeated Substring Pattern | repeated-substring-pattern | Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters. | null | String,String Matching | Easy | 28,686 |
665 | hi everyone today we are going to solve the lead code question non-decreasing the lead code question non-decreasing the lead code question non-decreasing array so you are given array Norms with n integers your task is to check if it could become non-decreasing by modifying could become non-decreasing by modifying could become non-decreasing by modifying at most one element we Define the array is non-decreasing if we Define the array is non-decreasing if we Define the array is non-decreasing if current value is less than or equal next value hold for every I such that the islands is like a uh greater than or equals zero to n minus 2. so let's see the example so you are given four to three and the output is two because if we modify uh this first four um to one so we can create a like a non-decreasing so we can create a like a non-decreasing so we can create a like a non-decreasing array one two three so that's why output is two and let's see the example two so you are given four to one and the output is false because uh um we have to modify uh twice to create a non-decreasing array like between 4 and non-decreasing array like between 4 and non-decreasing array like between 4 and 2 and between two and one okay so let me explain with these three example and look at the first example so basically uh we get it through all numbers like one by one and every time we check the um adjacent number and we start from index one because we want to check the like a current index -1 -1 -1 so in this case uh looks good and uh between two and two um they are same looks good uh and uh between two and four looks good and then now we find the like a vibration so but uh we can modify the number once so this is a look this is good and then um take the next numbers and then two and five looks good so in this case it's simple just return true right and then look at the second example actually this is an interesting point and again start from index one and the three and the four looks good and uh move next and then two and four now it's a violation and but this is the first time so looks good and then move next and three and two and uh this is a non uh decreasing relationship so looks good so that and in this case uh it looks like true but look at the uh when look at the four when we are like a last index so three is smaller than less than four so between two and three looks good but uh look um between like a four and three is as smaller than less than four in this case it's a vibration so that's why um in second case we should return false basically so we don't have to modify any numbers because uh this is a brilliant question like a return true or false but there is some case where we have to modify the number um to return the correct answer so in this case we find the violation between four and two so when we find the piration we have to um check if current number is less than um current index minus 2 number which is three in this case and uh y minus 2 so let's look at the sad example so we start from index 1 and 3 4 and the look looks good so far until four and we find the variation when we reach the two so we know that we make sure that until fall um these numbers are non-decreasing um these numbers are non-decreasing um these numbers are non-decreasing order that means index 3 is definitely greater than index two so when we find the violation here um check the non-ado Json number precisely current non-ado Json number precisely current non-ado Json number precisely current index -2 and if current number is less index -2 and if current number is less index -2 and if current number is less than um current index -2 which is three current index -2 which is three current index -2 which is three so we should up to date this current number to with a current index minus one so that definitely our current number is greater than like a previous um like a number like this like one two three because I also uh in this in these three um three is definitely uh biggest number so we can make sure this number is a greater than or equal between from index 0 to 1 to 3 index three so that's why um updater this number so now Operator 2 with um this number so four and then check the next number and the five and four so non-decreasing relationship four so non-decreasing relationship four so non-decreasing relationship looks good so that's why um in this case a return true so look at the second case again so if we don't modify any number so as I told you this these two relationship is like a non-decreasing order so that looks like non-decreasing order so that looks like non-decreasing order so that looks like a true case but uh a like a true case but uh so between four and three it's a like a decreasing order so which is a vibration so to prevent the vibration um maybe this uh index 2 so look at the non other Json number so current index -2 and compare two numbers current index -2 and compare two numbers current index -2 and compare two numbers so three uh two is less than three in that case um update current number with current index -1 which is 4. index -1 which is 4. index -1 which is 4. so four in this case and then so now the range between index table to index 2 looks good like a three four looks good and then move the next so we find three but uh the relationship 4 and 3 is like a decreasing relationship in that case we find the violation twice that means we should be done false in this case yeah so that is a basic idea to solve this question so with that being said let's get into the code so let's write a code actually it's not difficult so first of all um we should have like a frog change flag so and start looping for I in range so we start from index one so one two lengths of input array after that if current number is less than or the adjacent number so I minus 1 in that case we need to modify the number definitely so first of all but if um we already changed before in that case this time we modify twice so that means we should return false and then if not the case change frag to do and as I explained earlier if index number is greater than or equal to and yes so this is a um this check is like a auto advance or not and then um current index current number is less than um I minus 2 so we check the other Json number here and so this time we check the known as adjacent number which is a current index -2 -2 -2 in that case um update current number with the number at index minus one as I explained earlier and then after that return true in this case looks good and the time complexity of this solution should be a order of login linear time and uh we don't have extra data structure just a variable so I think a space complexity is uh o1 let me summarize step by step algorithm this is a step-by-step algorithm of this is a step-by-step algorithm of this is a step-by-step algorithm of non-decreasing array step one initialize non-decreasing array step one initialize non-decreasing array step one initialize changed flag with false step two start looping if your current number is less than previous number now current index -1 then if we already change the number -1 then if we already change the number -1 then if we already change the number once then return false steps to change the Frog to True step 3 a current index is greater than or equal to and the current number is less than a number at in the current index minus 2. then update the current number with previous number so current number in the current index minus 1. then after that um just return true yeah actually that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment if you have any question so I'll see you in the next question | Non-decreasing Array | non-decreasing-array | Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**.
We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that (`0 <= i <= n - 2`).
**Example 1:**
**Input:** nums = \[4,2,3\]
**Output:** true
**Explanation:** You could modify the first 4 to 1 to get a non-decreasing array.
**Example 2:**
**Input:** nums = \[4,2,1\]
**Output:** false
**Explanation:** You cannot get a non-decreasing array by modifying at most one element.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `-105 <= nums[i] <= 105` | null | Array | Medium | 2205 |
200 | question 200 of leap code number of islands given an m by n 2d binary grid which represents a map of ones land and xero's water return the number of islands so an island is surrounded by water and is formed by connecting adjacent land horizontally or vertically you may assume all four edges of the grid are all surrounded by water so we have two examples here the first grid has an output of one so there is one island in here and the island is formed by these connecting ones and remember the outside of this will all be surrounded by water so it'd be surrounded by zeros and in the second example we have a grid with an output of three and that's formed from these four ones connecting together adjacently to create one island this one on its own which counts as an island and these two connecting adjacently to form the third island so let's jump into the explanation so we have two examples here let's start off with grid one so in this grid we know that we want to be returning a number or a count right so we can have a count variable which we can initially set to zero and what we need to do is we need to loop through this grid and we need to find a position that is equal to the string of one okay so say we started here at the first position we have a one so we have an island but we need to check its adjacent values to see whether the island or where this piece of land is connected to other pieces of land to form a larger island so the way that we could do this is to use dfs recursive solution that checks all possible solutions and with dfs we have base cases so in order to check all potential values we need to go in four different directions right so we need to go up right down left but we first need to decide when to hop out of this dfs recursive call and the first case that we can think of is if the neighboring element or the neighboring value is equal to a zero because that signifies water right so if grid at i j so let's assume i is the row and j is the column if grid at i j is equal to zero as a string then we can return out of this recursive function now the second base case we need to think of is if it's inbound and what i mean by inbound is making sure that the value we're on is within this orange box so it doesn't go out of bound so if i is less than zero we're going to be outside here so i is less than zero that's out of bound if i is greater than this grid here if it's greater than grid dot length minus one and that's also out of bound so if i is greater than grid dot length minus one that's also out of bound because the grid length here is five the index of that is 4 so if it's greater than 4 so the index before would be here if it's greater than 4 then it's out of bound on this side and then we do the same for columns right so we do the same for j so if j is less than 0 it's out of bounds up here and if j is greater than grid at i dot length minus one then that's also out of bounds not the outer bounds down here so we need to specify i so that we go down so those are the base cases resolved now we can carry out the recursion right so we can move right down left and up from this initial position now let's take care of these two positions so this one is going out of bounds because i is less than zero so that's not going to work going up j is less than zero so that's not going to work so that's outbound so we know that we can go to this value and this value so say we carried out our recursion on this value so we go up that's out of bounds we go right that works absolutely fine so we can go there we go down that goes to there that's absolutely fine but we also go backwards so we go back to this previous one now we can't allow that to happen because that's going to create an infinite loop so what do we do in this case well we could store all positions that we've looked at within a set so we could store i and j within here but the only issue with that is that it takes extra space so what we could do instead is we could manipulate this grid in place so before we move from the first position we set this to zero now when we move to this position if we go backwards it's going to hit one of our base cases where grid at i j is equal to zero and then it's going to hop out of that so it's only going to check the positions that are equal to one and then we can carry this out we can go to all the different positions check everywhere and once we hit zeros we're going to realize we've reached all the positions where there are neighboring ones and we're going to hop out but we need to specify that we've hit a number of islands so we need to specify here to return one and then outside of this dfs we can increment count because count is going to be incremented by this one okay so counter is going to go to one and then it's going to return the answer because it's going to check all the other possible solutions because all of these ones are going to be reset to zero and then it's going to check all the other positions and they're all set to zero and once we reach the end pop out return the count and it's pretty much the same for the second example okay so we start off at the first value we go right down we can't go left because it's out of bounds we can't go up because that's out of bounds and then this is set to zero this one can't go up because it's out of bounds can't go left because we've reset that to zero can't go right because that's at zero but it does find a neighboring one down here so we can do the dfs on this and this one is going to check values as well so here we're going to go left right down there are no extra values so this one gets set to zero this one is going to check right that's already set at zero down that's set to zero that's out of bounds so now we can increment our account by one so count is now equal to one well we carry on traversing the grid we find the next position where there is one here is the position so we carry out the dfs function from here and we recurse in all four directions they're all pointing to zero so we can hop out of this an increment count then we move along until we reach another one and do the exact same here so we check all directions that's bound zero point into one check this one but before we do that we set that to zero goes this way can't go right cannot go down cannot go left anymore because we set the previous one to zero so we increment count again so that's the basic understanding of this question and how we formulate an answer now let's talk about time and space complexity so with time complexity it's o m by n where m is the number of rows and n is the number of columns and then space complexity is the exact same in the worst case scenario we are storing up to m by n within our stack for the dfs recursive solution so let's start off by initializing count to zero we need to find all the positions in the grid that are equal to one so let's loop through the grid i is equal to zero i is less than grid.length so this is going right grid.length so this is going right grid.length so this is going right j is equal to zero j is less than grid i dot length so that's going down so it loops through the entire grid now we need to check if grid up position i j is equal to string of one if it is we are going to carry out some recursive function to check all other possible positions so dfs we're going to pass in the grid because we need to update the grid in place we're going to pass in i which is going to be the rows and j which is going to be the columns so let's create that function so function dfs so we need to pass in grid row and column so in this first thing we do is set the base cases so if row is less than zero or row is greater than grid dot length minus one so if too far to the left too far to the right is outbound column is less than zero or column is greater than grid.length greater than grid.length greater than grid.length sorry grid at row dot length because we're going down minus one so if too far up or too far down that's out of bounds and finally grid at row column is equal to zero so if it's water we don't want to check that because it's not a neighboring island if any of these are true then we just return out of this recursive call next we need to set grid at row column to equal zero so we need to stop any further dfs calls from going back to previous positions the way we do that is we set the current value of grid to zero and then finally we need to recurse in all four directions up down left and right so we need to call dfs four times passing in grid row plus one will go down row minus one will go up cold plus one will go to the right call minus one will go to the left and finally once we found all neighboring islands we need to return one so that this function actually returns something and up here this is going to return one so we need to increment count by that value so we can say count is equal to count plus dfs and then finally we can return count see if this worked okay it's been accepted let's submit it okay and there you have it | Number of Islands | number-of-islands | Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_.
An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
**Example 1:**
**Input:** grid = \[
\[ "1 ", "1 ", "1 ", "1 ", "0 "\],
\[ "1 ", "1 ", "0 ", "1 ", "0 "\],
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "0 ", "0 ", "0 ", "0 ", "0 "\]
\]
**Output:** 1
**Example 2:**
**Input:** grid = \[
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "0 ", "0 ", "1 ", "0 ", "0 "\],
\[ "0 ", "0 ", "0 ", "1 ", "1 "\]
\]
**Output:** 3
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 300`
* `grid[i][j]` is `'0'` or `'1'`. | null | Array,Depth-First Search,Breadth-First Search,Union Find,Matrix | Medium | 130,286,305,323,694,695,2035,2103 |
894 | hey everyone today we are going to solve the little question or possible for binary tweets so you are given and return a list of all possible for binary three ways and nodes each node of each tree in the answer must have node bar equals zero so each element of the answer is a root node of one possible three you may return the final list of trees in any order a full binary tree is a binary tree where each node has exactly zero over two children okay so let me explain with this example so n equals seven so two sort of discussion I think there are three important things we have to think about so first thing is that this n number must be odd number not even number so I think it's easy to understand with this full binary tree so this three has seven nodes right one two three four five six seven so what if n equals six so we have to take a one node from these three so in the full binary tree is a binary tree where each node has exact zero over two children so how can we take a one note from uh these three to create a whole binary tree it's impossible right so if we take this node has only one child if we take this node or same thing this node has one side right so it's impossible right so that's why this n number must be odd number so that is our first important things and the second important thing is that um so how we can calculate a number of nodes on the left side and the right side so basically uh we create a binary tree with a like a one node three node and five node and seven node and so total number of node is seven right and so what if so let's say left number of left side number of node on the left side is one so how many nodes on the right side so I think uh we can use this picture so if this left side is one so right side has like a one two three four five right so we can create a formula like n N is a total number of node minus left number in this case one minus one so that means seven minus 1 minus one so in this case five so one two three four five so it looks good so this minus one is a root node and uh we subtract a number of nodes on the left side and that this is a total number so we can create this simple formula to calculate the number of node on the right side so that is a second important point so sudden important thing is that as I told you we will create the full binary tree with like starting from like a node one so when we have a node Z when we have node five seven nine so even if we have a like a n equals seven so we calculate the start from like when we have node one when we have node three when we have node five so that's why this algorithm has a lot of like a repeated calculation so it's a very time concerning right so that's why we use a hash map and then give a result so that's why so when we have another one so we can create a like a circle tree and uh if we have three um we can create like a triangle through binary tree and if we have five so we can create this Square for binary three something like that so that we can save the time right yeah so that is a such important point yeah so that is a basic idea to sort of discussion so with that being said let's get into the code okay so let's raise the code first of all if and divide two equals zero in the case we immediately done like an empty list so this is a first important point and the initial is let's say memo and a hashmap and then or I can return let's say generate Hulu binary tree and passing the input number and then so let's create a generate full of energy taking a m so first of all n equal one so we can return um three no and uh all the values are deterior right according to our description and then if any memo so we can immediately return a memo and that and so we don't have to calculate the game if not the case we need to calculate the full binary tree so trees equal so empty list and therefore left in so for left in branch and start from 1 to n and uh as I told you a number of nodes must be all the number so uh we increment by two so start from one so next number should be three and five seven something like that and then first of all create a rift sub trees and uh generate for the binary and the number of Rift node and writes sub trees and so this is a second important Point like a n minus left minus one and then so I think uh we can successfully create a left sub trees and the right sub tweet and then uh for uh let's say left in left please and for all right in right sub trees and then create a root node B code so three node so values should be zero and the left side is left and the right and then append this load node to trees so append and root so in the after that keep these three to memo so memo and uh n equal threes so that next time uh we don't have to calculate again and then return trees yeah that's it so REM isolated looks good very instant algorithm with 96 percent so time complexity of this solution should be order of two to the power of n d by 2. so in the generated through binary tree function for each value n the function is called twice with left and the right so for each because we call it branches into two more recursive calls so if we represent the number of recessive calls at each level as a binary tree it would be a binary tree with a height of n divided 2 so at each level the number of nodes doubles compared to the previous level so the number of recursive we call can be like a roughly two to the power of n d by 2 so that's why time complexity should be order of 2 to the power of n divide 2. and the space complexity is order of n multiply 2 to the power of n divided 2. so um we use a memo to keep the result of previous calculation so this algorithm may need to store up to 2 to the power of n divide two nodes of node objects so and then we need to uh keep like n times so that's why space complexity should be order of n multiplied due to the power of n divided 2 so this is a rough space complexity 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 | All Possible Full Binary Trees | random-pick-with-blacklist | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tree where each node has exactly `0` or `2` children.
**Example 1:**
**Input:** n = 7
**Output:** \[\[0,0,0,null,null,0,0,null,null,0,0\],\[0,0,0,null,null,0,0,0,0\],\[0,0,0,0,0,0,0\],\[0,0,0,0,0,null,null,null,null,0,0\],\[0,0,0,0,0,null,null,0,0\]\]
**Example 2:**
**Input:** n = 3
**Output:** \[\[0,0,0\]\]
**Constraints:**
* `1 <= n <= 20` | null | Hash Table,Math,Binary Search,Sorting,Randomized | Hard | 398,912,2107 |
1,857 | Hello everybody welcome back to my channel uh today let's start a hard question so that is the largest color value in a directed graph so description is too long so I will just use this example one to illustrate so here that there are five notes Here one from zero to four and for each node it has a color for example the No the number four the color of node number four is red and this one is blue and this one is two so the question requires us to count like along a path so for example for this path what is the highest or the maximum frequency of the color so it is so for this part it has a rate of three and the blue nose of one so we have to return the frequency of highest frequency so that is three how do we solve this problem efficiently so first the graph right and at the same time if we want to like to visit the node just one time we have two like keep the median results of each note so we don't have to calculate each again for example if now we have another node and we will next to the node three so if we start from the note here and we visit this node and then after visiting the Note 2 we want to start from this Note 5 and then this is the three again in this way I don't want to like to recalculate the result of this path so I need to find a way to somehow store some the medium results on this note so When I visit the node again I can just some value from the cache give these two in mind so what do you think we should use to solve this problem so it's like a topological search and plus the memorization right um let's start from null zero so when the null zero or go from zero to two to five to six and we reach the end of this path so from the six we can start to calculate the frequency of the color so for six we have a raid and that is one for this six only and now let's backtrack to the five so for the Phi we have green one and also we need to get back to six the result of the six so we have a rate one and then we are like to backtrack to two and for the Note 2 actually it has two pets so one from this way the other from the five so in order to check or to check the frequency of the colors starting from the node two we have to finish both node four and node five so let's go start from the Note 4 and then we find out okay four points to Note 6 but somehow in the test showing the memory already have that the in this six there is a the result is we have a red one red nose start from knock six so we can get it in this store here so from this node we have a um red one and we have a blue that is also not one and then back to two so for back to two we have a four we have two pad so we like to take the maximum frequency of each color we have a red one and red one okay so for this now we have our red one and we have a blue one and there is no blue but we want to take the maximum so we keep a track okay there is a blue one and then here is a green one I also have two plus Excel so the green is actually is two and for the node zero it will just add this one and pass itself so the zero is a red node so we will increase the one to two so after finish this note we know that um the maximum value will be two it may be like in red color or green color okay so after you finish node zero we want to go to find um next one is from node one so from node one and there are two packs one is good go to three and the other goes to two so this is three so since three is not being visited so we have to calculate its frequency so it has a blue one then back to one but one six one here's another path outgoing Edge so we need to visit the two and for the two we found out okay so here is the result of two right and then we back to one inside the other maximum frequency so is the red one okay so here we have a red one and a blue one in the green two and then I need to add back itself so it is through two actually okay so start from the note one you can the highest frequency is still two and then um after that we are going to visit two but we find out the two is actually been visited before so we don't have to count it's and then we find that all of the nodes in the drive has been visited so the num the result is two you might wonder why we want to keep track of the maximum frequency of all the colors instead of the highest frequency of each one color Okay so for example if now I have a node a red node the importance to the green node the importance to a right now so start from this no will have a right to you in green one but when we backtrack to each previous new video are red and red so yeah we can just use the red and plus this one but there may be some possibilities that these two notes are green right so in this way we need to keep track of this screen so we can know how many greens knows there in the pot so that is why we want to keep track of the uh the highest frequency of each color instead of the highest frequency of only one color the problem now is we know that we knew we use topological search and so what's format we can store these values okay so let's think about so for each node for each note it will have these colors that it means from the node I will have to like to um have a color set is memorized all the colors frequency starting from this node so it seems like it's a two-dimensional so it seems like it's a two-dimensional so it seems like it's a two-dimensional array with the row of these notes so for example here we have no zero no one no two no three and then fold the column it is the color so for example we have a blue color we have a green color we have a gray color so for each cell Pixel It means that start from node zero the maximum frequency of green note is this number the value of this cell phone we want to keep it negative set so we don't have to recalculate a node again if the node already is in the visit is that if it already visits in the visited session then we can just guess the value from this 2D array so now let's start from zero and zeroed all the way go down to six so for six we have a red one so we put it here and then went back try to Phi and then in the five so first we need to add the next node so that is node six so I want to put one here and then we need to add Excel so the null file is green so the green will put green here then go back to two but before we want to calculate the two we have to release this path from two to four to six okay so since six Okay so uh actually I forget to update the set so now we have the sixes already visited so we have finished the 2D alright so we finish it and we already finished the five and right so for four first for the four we next we want to visit notes six and then we found that six is already in the visited set so we can just get the value from the 2D array so I will put one here and then we need to add Excel so for the four you have a blue one note that is in itself okay so in Finish Note 4 we want to we would like to put four here and go back to two so for the two it has two Pi one is four and the other one is equal to five for each color we want to guess the maximum of this one of these two so since one and one equals so you can put one here and then here is a one here's a zero so we put one here this one zero here is one so we put one here and then we add the color of himself so for the two it's green one so we updated from one to two and we finish two so put the two here then we go back to zero so for the zero it just two so you can just take the row from then two so here we have one two but the zero itself is red so we need to add this one to from one to two and then finish zero so we want to put zero here next one is one so for one it has two pairs one go to visit Three another go to visit two so let's start from three so three since three is not Infinity so we have to calculate each so for itself it has a Row one okay and then put three in the visited sets and so back to one it has two paths so it has to consider it needs to consider path three and path two so we'll take the maximum of the of these two rows so for this column is one and zero so we put one here so this one in one the maximize one this is two and zero I put two here the note itself it is blue so I'll change it to two Okay so in the end I can um go through the metrics again and find out the biggest number here is two so that is the answer so now let's start coding so in this question I will use these two concepts the first is I will use the typological sort to Traverse the graph and the second is I use a I will use a 2d array and the 2D array is to Cache the frequency of the colors starting from the current node into the end of the path now let's create our graph so in the graph I will use a default dictionary the index dictionary is a list so for the A and B in without append the B to at least so it means that for the node a it will have a older Neighbors in the graph a list so it will be easy for us to Traverse all the neighbors of node a and then after that we will also back to initialize this to the array so for the 2D array I would call it as a cash so the role of the row number of the array is the size of the nodes and the size of the nose is the length of the colors string so foreign for each row we will have a column in the column is from the description of the question he says that um given the colors where the colors are is a lowercase English later so material at most 26 colors there of each node so um reductive initialize the current column is a 0 40. 60s 6 26 columns I would like to have a visited set it means I already can visit the set before so whenever I encounter the sets that is already exists in the visiting set then I know I don't have to call the average search function again I can just guess the value I want from the cache so you can save us lots of time so now this let's start for the definition function so for the deficit function I will pass um one variable is the node and another is the path I want to pass the path because in the description it says like if there is any Cycles in the graph you want us to return the negative one so I will have a path variable to come to detects if there are any node that is previously visited if that is true then there is a cycle in the graph so we will return -1 -1 -1 but for the different search function I will return the Boolean so if and return the Boolean if I return True Image um there is no cycle but if there is a false it means there is a cycle so now let's start from the best case so the best case is um in the path yeah I just return it false and then if it is not in the path the first thing is to add a node to the path and then we want to basis the neighbors of this current node and call the different search function on the neighbors foreign that we also like to check if I already visit the neighbor before if that is true I don't have to code the different search function on that neighbor so okay that's in the visited sets then I will call the research from the after I have the frequency of colors of my neighbors or then I can calculate so how many colors are there if the start from the current node so here I want to start from iterate of each column so I will have the column 26 colors right and for this 26 color I just want to get the most if there is the same color in different neighbors thing I want to guess the highest frequency of the harder and but first date frequency in the current node on this neighbor after I put my following neighbors uh the frequency and then I need to add myself the current node in the current color so in the current color it lies in the colors string so we will have the colors Gene but it the stringy will give us a character but we want to transform is to some index so we will use the order function to transform the from character to number okay so here if the colors of the current node is also a small a then the orda minus RDA will return a zero but if the color of the current node is B in the order of B minus out of a will return one so in this case we can use the order function to transform the from character to the index of the array okay so now we have finished the current node so we want to remove the node from the path such that um I can mark the current node as visited and then I can return shoes actually here I forget to um I for every neighbor I also have two chair Cliff theories any cycle so there are any cycle that will return to finish the different search function I can now call the different search function starting from each node to 4D in the first um I want to check if the end is already visited I only called the visit I only got different search function I'm visited no so I want to check the uh for the different search function so it's different search function and starting from each node I will give you a new set this is path variable so if it returns a negative it returns a false it means there is a cycle so I can just reach a negative one however if it is not it is true action then I would like to keep a variable actually this cookie frequency high is the maximum frequency and initialize it as zero so um the question asks us to return the maximum frequency of the color so uh fill this one for each note we will have a row of colors and then we can Count Their frequency by using the maximum function and then after we get the maximum frequency of that roll or that node then we can compare it with the current maximum frequency and then update the maximum frequency in the end you can return this frequency okay now let's check okay here's some zero for here I miss in range 26 for in a Range there's a colors okay hmm ah okay um you can just foreign let's check okay it passed okay thank you for your watching | 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 |
91 | The person starts disassembling and the instructor is nearby subscribe unit 2.2 subscribe nearby subscribe unit 2.2 subscribe nearby subscribe unit 2.2 subscribe button under subscribe Video subscribe ki 3222 sex 992 to decoded to benefits 2012latest video0 ab zid bcd na dhone subscribe Video subscribe and subscribe the Ajay Ko A Solman SlideAisho Loot Hai So Let's Look at all the system of the report and its almost from 1st April and beautiful post from S Dhoni The important one should not want to see the character subscribe and subscribe the Channel 123 Liquid 123 Lage Urs subscribe Video Ko K Laddu Ka The Spot Example Software Will Try Device Will Group Of The Bluetooth Settings Subscribe 123 subscribe video Subscribe From The Amazing Which Will Give One 12512 21 2013 Ki Aaj Shivani Bana Rahe Me Lagal Ba Netuvava Pipra Darshanarthiyo Twelfth Monitored Loot Subscribe Button President Mirwaiz subscribe and subscribe the Channel subscribe like this less group glass two characters in the last two characters free mode on her boobs pe commission more subscribe provide you with the release of english for class 5th and knowledge conclude of total number of western india turf badu counterweight white - your time in A student Do That - your time in A student Do That My Den Ooo 10 Easy Sir Pulsar It Means Lysergic Acid Steve Whitmore Subscribe to 2051 Have a Slack Right Left Right Direction of Course Even If They Think What Does Nothing Is Lost in Thought Length That I Plus A Plus Extract for the Tense Character Hai Loot Chote The Character Of But Does Totka Rath I - 1381 To Form For The Number Her During The Current I - 1381 To Form For The Number Her During The Current I - 1381 To Form For The Number Her During The Current Program Subscribe On The Basis Of Bhi At Any Place The Previous Character Unlimited Vansh Character 12th Art Current Place The Current Character Understand What Are The Number Of The Best Interest Number Get Name Par Number Do Absolutely 210 Spa Tension 128 A Private And Positivity Model Arise Record He Gives Very Good Impression That You Have Left Of Writing Modeler Code For Dowry Single Line That Aap Ji Ka Generated A To Z Number In This To Characters and let's write this number with new number is Loot 0606 and numbers class 10th I am doing a second group of teachers we are just in grade one equal to two PPF Waheguru DP of I miss you too swalla duty of ministers position also any two Do The Current Affair About Bill-2012 Improvement Bill-2012 Improvement Bill-2012 Improvement That Records For Details Inside Corner Case In Quality Twinkle Do Possibilities For Pun Fluid Se Hunting Uske Sher E Want To Is The Number Is Not Equal To A 80 That Today's Number Shri Krishna Vatika 222 Loot laptop hard work just 2 first's deputy chief of mission aa that also members of Adarsh Nagar have the condition members of Adarsh Nagar have the condition members of Adarsh Nagar have the condition that dat test exactly to f10 and sentences about equal to one and tanks' equal to one and tanks' equal to one and tanks' thirst exactly vomit two state's civil writ on revised answer what will Be The Most Cases Your Husband So Interesting Something Like Tells Husband And Something After That Somewhere Near Decoding 3031 Also Possible Feel On A Similar For Anything From 9856 Subscribe And Video Subscribe And Subscribe The Channel To Subscribe And Subscribe The Big 222 That Starring Vikas 1020 Can only be decompose nuvve note independence subscribe must competition more subscribe to that diwali loot main office don't length 8 - 1st semester and see how to us a strong difference hai thanks man this review a long answer egg white bun hair institute of hero And 2001 Show What Should We Do 2014 Cases After One Of Which Should Be Doing Today's Episode 148 Veeru Ki Kul Luta Subscribe Now That Aisi Rolex Submit Image Scroll System That Accepted OLX Talk Time Complexity Every Time Complexity Video Length Of During That A Number of characters present in the border of unnatural and number of characters printer input strength and weakness complexities contacted equal to airplane mode of length of observing that will be confident this singh dpro for the same size shows that too btc 1st id singh and thank you for Watching my video and photo, try to make logic and use this, thank you. | Decode Ways | decode-ways | A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s). | null | String,Dynamic Programming | Medium | 639,2091 |
1,962 | all right we are doing this problem called remove stones to minimize the total that's our read you are given a zero index integer a pi Square Pi Supply represents the number of stores in the ith pile and an integer K you should apply the following operation exactly three times remove any file and remove okay so basically choose any file and remove half of the stones from it notice that you can apply the operation of the same file more than once return the minimum possible total number of stones remaining after applying all the key operations okay so our what we have to do is we have to choose any pile and reduce its size in half and we can do that same uh you can we can do that on the same pile again uh and our job is to after what we are left with we have to return make it minimum so that would mean that I would want to I want to choose the maximum pile right like first I want to remove so for example let's say uh my file is like 150 I don't know 25 and 40 something like that now from which file would I want to reduce the half if I want to reduce the number of stones obviously the largest highlight so I'll reduce this largest file into half and then again I have to choose whichever is now the largest okay so this is the largest so I'll reduce this into half and if you have to choose now again then this is a larger solutions to have so we be greedy at any point in time whichever is the largest pile we will reduce its size in half as simple as that right so how do we accomplish it so we want to always maintain a maximum right we want to reach the maximum uh and uh how can we do that so we can use a priority if you a Max priority queue right that could uh maintain the so that we can query or uh remove the maximum easily right that's fair so let's add a priority queue of and let's save the indexes into this file side in that priority okay so priority queue also new priority queue and we are going to save the indexes so the way to do that would be if I am given a comma B uh I want to return the Mac I wanna have the maximum here so I'm gonna do files of B minus files of a this is going to give me the max priority right so if a is largest then this will be becomes the most negative yeah so this is how I save the priority queue now I just go for each uh when I equals to zero I is less than price length I plus I am going to uh additional practices so priority view dot add uh I and now what I'm going to do is I'm given key operation so for I equals to 0 I less than k i plus you've taken element out of the parity queue uh you also want to do something like and try to queue Dot is not empty right there is only if you divide if you keep reducing into half and everything becomes zero uh then also you don't uh do this so in this case what you want to do is uh or you should apply the operation exactly K times so you have to apply so if there are zero left and 0 by 0 would be 0 by 2 would be zero so okay I can still apply the operation K times if you want me to uh so I do this and then what am I going to do I'm going to do like a remove the item from the priority queue and now files of Max and gets equals to 0.5 Max and gets equals to 0.5 Max and gets equals to 0.5 I reduced this guy to half and now I'm going to add this guy back into the priority theme right so priority queue dot add I want to add it back but now when I add it back the value should reduce right so this is that and then you want to do return okay now we wanna just add them up so now we have to return what the minimum Stones left yeah so now we just do strong sequence to zero and you return the final limitation let's have a run and the answer we got is wrong let's have a look so 549 expected is 12 and we got 10. so 5 4 9 Let's uh see what would happen with five four and nine so you have five four and nine the largest is nine I'll divide it into how many times I can do this k equals to 2 so first I divide 9 by 2 so I'll get uh four right and then I divide uh this five into two uh all right I'm gonna remove that money ah okay I'm gonna remove that money so piles of this uh minus equals to this okay I'll run again right both Works submit and it gets accepted all right | Remove Stones to Minimize the Total | single-threaded-cpu | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the operation on the **same** pile more than once.
Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_.
`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down).
**Example 1:**
**Input:** piles = \[5,4,9\], k = 2
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[5,4,5\].
- Apply the operation on pile 0. The resulting piles are \[3,4,5\].
The total number of stones in \[3,4,5\] is 12.
**Example 2:**
**Input:** piles = \[4,3,6,7\], k = 3
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[4,3,3,7\].
- Apply the operation on pile 3. The resulting piles are \[4,3,3,4\].
- Apply the operation on pile 0. The resulting piles are \[2,3,3,4\].
The total number of stones in \[2,3,3,4\] is 12.
**Constraints:**
* `1 <= piles.length <= 105`
* `1 <= piles[i] <= 104`
* `1 <= k <= 105` | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks | Array,Sorting,Heap (Priority Queue) | Medium | 2176 |
1,200 | it's an easy problem it's said uh we'll be given an array of integers and the output is going to be the pair of minimum uh difference so here actually the difference is one so uh the output is going to be the all the pairs of which have difference one and here is another example in this case it have a difference the minimum difference is too and we have only one pair of that okay to do so the easy way is to short very fast which i have done here and getting the minimum difference by adding the infinite or the maximum difference here and then finding it after that we'll just add those failure into the result by checking if the minimum difference is the difference within the array of the pair and then uh i'm just appending that array with the result and it returned it thank you | Minimum Absolute Difference | remove-interval | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference of any two elements in `arr`
**Example 1:**
**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
**Example 2:**
**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]
**Example 3:**
**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]
**Constraints:**
* `2 <= arr.length <= 105`
* `-106 <= arr[i] <= 106` | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. | Array | Medium | null |
315 | so hey there everyone welcome back I hope you all are doing extremely well so in the latest video we have seen this easy problem how my numbers are smaller than the current number so in this video we are going to solve this problem count of smaller numbers after Self write for example we are given an integer array numps and we have to return a new count sorry the count sorry has the property work count I is the number of smaller elements to the right of Ramsay so in this question what we have seen is so for each element we are running for loop from 0 to till the size of array and we are checking all the smaller elements than the current element but in this problem what we have to do is for example we have five to the right of five right so our count will be two right similarly for two to the right of two only one is a smaller element than two then our count will be one right similarly for six only one is smaller then count will be one then for the last element our count will be zero because uh there is no right element exist at the right of the last element given right so let's see how we'll solve this so we are already saying this first test case so let's see it's Brute Force first brute force will be and it will work in Big O fan square right and space will be big of one so let's see how it will work so what we will do is we will use two Loops right we will use two Loops the outer loop pick all the elements for example we are given with five two six one right so our outer loop will pick all elements from left to right so first outer loop like if I pick here over the inner loop will iterate through all the elements on right side of the picket element right so in the loop will run from two to one and it will check all the smaller elements than five right again our outer loop will come here like I becomes 1 then J will become 2 let's say J come here then it will check six and one uh is there any element which is less than two then it will count it right so the inner loop will iterate through all the elements on the right so the picked element and we'll take one count array right and we'll keep counting the array elements for our current element on the right side elements smaller than our current element right so is for example for I is equal to 0 to n let's say is this is our count array then what we'll do is count array of I first will be 0 right will initialize all the counts in the count area as a zero initially all will be 0 right then what we'll do is 4 I is equal to now will run two nested loops I is less than and I plus what we'll do is 4 J is equal to I plus 1 right because we have to check only two right side of the current element right how many elements are smaller than our element right we run second loop our inner loop from J is equal to I plus 1 and now if the elements we are checking if any element is less than our array of I right what we'll do is we'll do count array of I plus right so this will be our Brute Force approach but it will give tle because it will work in Big O fan square but space complexity will be big of one right so you can try this approach it will give tle so let's move on to the optimized approach how we can optimize it to server optimized approach will be will work in big off and Logan right but we will use space complexity of big off and so let's see how we'll do it so in these up to optimized approach we'll use the merge sort function right we'll use merge sort so let's see how we'll take into consider the mouse sort and we will sort that in our descending order given let's say given arrays 6 to 5 1 731 let's say this is the given array so we'll sort them using more sort and it will be in descending order why in descending order because we have to check all the array elements to the right of the grand element let's say we are checking four six then we have to check all in the right side of it right so we will sort them in descending order we can easily check all the elements because which are smaller than the current element because uh the decreasing order so simply we will count all the elements which are smaller than the elements right so using merge sort function what we will do is first we will divide it in into two halves let's say over half becomes here now two partition comes so first partition is six two five one and second is seven three one right so again by calculating mid will further divide it so now our first part becomes uh six two and second becomes Phi 1 similarly in this case it becomes seven three and it is one right so after again dividing it we will get each element 6 2 and 5 1 right so all unique elements we will get at the last seven three one right so we have sorted uh both the partitions in the decreasing order you can see right so we'll sort all these in decreasing order we will we still have to sort it so let's say we again take our count array so initially it will be all the count arrays will be zero right all the counter elements how many are elements are given four three seven right so let's take zero right so this is our count array now so now how we'll calculate our count of all the uh Elements which are smaller than the current element to its right side so now 4 6 and 2 right 4 6 and 2. now 6 is greater than 2 right 6 is greater than 2 and 6 is at our 0th index what we will do is we'll do count of 0 plus is equal to one right so now our count array becomes 1 0 again 0 because we still have to check for rest of the elements and remember we will increment always at its Index right for example we will increment 4 6 because at the 2 is at its right side right and 2 is less than 6 right we will increment 1 to its CR to its the index of six here it is 6 right it's the index is four six two five one seven three one right these are indexes of elements right this is our zeroth Index this is one two three four five six right so now we have checked four six right so now moving on to now if we check for five and one we checked four five and one now five is greater than one right and if I uh one is at its right side right so now 5 is greater than one what we will do is we will do count of 2 plus is equal to 1. because index of 5 is 2 right we will do now our updated count array will be updated account array will be so now after updating it will be 1 0 right so now similarly we will check for seven and three right we'll again 4 will check for seven and three now seven is greater than 3 right what we will do is at position for that index fourth we will do count plus is equal to 1. right because index of 7 is 4 right we'll update it will increment at its position by one right so now our updated count array will be one zero one so 0 1 0 right so now our uh now our new array was six two five one seven three one then we will again check now as six is greater than 6 is greater than both five and one right you can check five and one are at its right and 6 is greater than both five and one we are already checked four two right again it is greater than five and one what we will do is we'll do count two times right because we have two elements which are less than six right six is greater than five and one now again what we will do is count of 0 plus is equal to 2 right now our updated count array will be three zero one zero right now comes to two will check for two now four two is only greater than 1 right again 2 is greater than 1 right so what we will do is we'll do count of 2 is at our index one right so then what we'll do is count of one plus is equal to 1 right now our updated count array will be three one zero right now moving on to we are left with this part seven three and one so checking for seven now seven and three both is greater than one right seven and three both are greater than one will increment both is greater than 1 will increment a count by one at both of the positions of seven and three right so now our updated count array will be three one uh zero as it is now index of 7 is 4 index of 3 is 5. 012345 will increment at our fourth and fifth Index right so this will be our updated account array right so now by applying merge sword function at our both the partitions right so our update where I this is our previous array now updated will be it will be uh six five two one in decreasing order we will show them in decreasing order right seven three one right now for six and five now four six and five it is greater than three and one 6 and 5 are greater than 3 and 5. sorry three and one because we were left with three and one right let's say four six we are done with five and one right four six we are done with two also but six is still greater than three and one also right so we'll increment its value by 2 at its uh indexes right so our operated account array will be now server 6 was at our zeroth index will up will increment it by two and it will become 5 this is the index of the element six zeroth index and the index 4 5 is 2 0 1 2 this is the index 4 element 5 so 1 at as it is we'll increment it by 2 and it will become 3 right 5 1 3 0 and raster as it is this will be our updated count array right so now checking for two so 2 is again greater than one previously but we didn't compare this one right so 2 is again greater than one will increment one at the position of two so two was present at index one right two was present at index one zero one two three four five six and this is the position for array element 2 right so over again updated count array will be 5 2 rest as it is three zero two one zero right so this will be our final count array and this will be our final answer so you just have to remember that we are incrementing always at it index at its Index right so we are taking count array as in our Brute Force approach and what we are doing is for every element we are checking all the array Elements which are smaller than the current element at its right side right and we are sorting them in decreasing order using merge sort function right and for each element at Indy tax index May write so we are incrementing always attitude at its Index right so this will be our final count array so its time complexity will be big off and Logan we are sorting right and space complexity will be also big of an its temporary space we are using count array of size big of size n right to return our final answer so let's see its code so this will be our final code right so we are taking we are first making merge function and then we are making Vector of pair right and we will add elements with its indexes right and I will point to left and J mid plus 1 and let's take K variable and initialize it with zero now run I and J I will be till mid and J till right now if array of I DOT first will be less than equal to Arrow of J DOT first we will not do anything we will simply put it in our count array right else what we will do is we'll count all the elements right to the right side of which of it which are smaller than it right foreign merge function what we are doing is we are doing little mud a little bit modification while merging to arrays we will check if the right is greater than the left then it's okay right so if uh right element is our right element is greater than left we will not do anything it's okay as what we will do is uh but if left is greater than right we'll add total elements in right in count array right where the index can be found by our Vector of pairs taken right so this is all about our wide merge function rest what we will do is so here what we are doing is we are putting all possible remaining left part to the sorted array right and in this case we are putting all possible right part right so now this is our merge sword function we are sorting the given area in decreasing over the right if left is greater than equal to right will return we are calculating mid and then we are applying merge sort function to the left part and again to the right part right and we are merging finally upper both partitions of the array right so this is our final Vector function where we have to return the count array so simply we are taking off type we are taking Vector of type pair right foreign right so we are uh incrementing always at its Index right so our Vector will uh contain pair of type integer and integer one will take numzo Phi and another I it will save its index also right so we'll increment always at its Index right finally we are taking count array we are taking count we are passing merge sort function at last we are returning our count array right so let's try to run it and its time complexity will be big off and Logan because of merge sort function and space complexity will be simply big off and because we are taking counter it to turn our final answer so yes it's submitting the test cases so you can check the working code in the comment box if you still have any doubt you can ask in the comment box so let's try to submit it so yeah that's it for this video so thank you so much for being here if you like the video do share and subscribe to the channel thank you | Count of Smaller Numbers After Self | count-of-smaller-numbers-after-self | Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104` | null | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | 327,406,493,1482,2280 |
344 | hello everyone this is rajat welcome to the boss coder YouTube channel so today we are going to solve this problem reverse scen so let's see the problem statement so in the problem you are given a stren however in the form of an aing for example let's say the string is hello then you are given like this so this is the string that is given to you finally what you have to do is you have to reverse the string so the output will look like this o l e h however you have to do this in place what do I what do we mean by in place means that you don't have you cannot use an additional space you have to reverse this array you have to reverse this string within this array itself right so that is the meaning of in place okay so let's start so what is the approach one get is coming in your mind very simple approach that is coming that might be coming in your mind is we are given this array let's reverse these two characters let's make this o and let's make this H then let's reverse this so let's make this L and let's make this e and then either you can reverse the single number that is there or you can you don't reverse it that is completely fine so what are you essentially doing here is just taking two index that we are starting here from zero index and from the last index n minus one given the length of this array Lex say is n you are reversing these two characters on the first and the last and then incrementing left by one and decrementing right by one right so this is very simple let's start writing the code for it so this will look something like this void reverse string you are given a character of string right so you will take initialize left as Z and you will initialize right as s dot length minus one while now until when you will keep on spping characters your L will start increasing from there and your R will start decreasing from there so till your R is greater than L you will keep doing it however as soon as your R becomes less than L you will break out and then you will just reverse the left and right character simple you will just store the character uh character ABC in s of L then you will change S of L by S of R and then you will update s of R by character very simple you will do it and then you will update the left and right pointers so update left and right point l++ and point l++ and point l++ and rusus so let's write the code for this very quickly in the and see whether this code works out or not okay so let's start writing the code for it of course we will Define the left pointer by Z and we will Define the right pointer as the last element last character in this string array then we will keep looping through till my right will be greater than left and then I will reverse the left and right characters so I will first save the left character then I will update the left character and then I will update the P after this I will increase my L and I will decrease my I will update my left and I will update my right and then ex done let's run the code this is accepted let's submit it so this is submit submitting so what is the time and space complexity for this approach the time complexity is of course order of n given n is the size of the stream or the size of the array and the space complexity is of course order of one because we have done this in place and have not used any additional array or any additional space to solve this problem this was the problem statement if you want to solve more such problems of leak code you can check out this playlist and definitely like And subscribe to our YouTube channel WE Post valuable content very frequently on our YouTube channel | Reverse String | reverse-string | Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
**Example 1:**
**Input:** s = \["h","e","l","l","o"\]
**Output:** \["o","l","l","e","h"\]
**Example 2:**
**Input:** s = \["H","a","n","n","a","h"\]
**Output:** \["h","a","n","n","a","H"\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters). | The entire logic for reversing a string is based on using the opposite directional two-pointer approach! | Two Pointers,String,Recursion | Easy | 345,541 |
1,614 | so this is the lead code question 1614 maximum less than depth of parents parentheses we're gonna check uh the maximum of depth of uh strength now to start off we need to create a integer where we initialize the maximum number of that to zero uh Max depth we're going to label as zero right now we're going to increment that based on nowhere with the number for Loop then we're gonna have to create another variable and current that same thing initialize it as zero then we create a for Loop which will go through each character's um create a variable called C character that I'll put see that to Char array which will which we will pick up each of the characters and we're gonna check if C is equal to our character open record if it is then we're gonna increment the current depth then we're going to get the maximum depth and we're gonna leave it out as Matt initialize it as matte where it's going to update the maximum depth dot X from Max that took current that and then we're gonna check on our else if statement where C is checks if it's the closing uh parentheses and then we're just gonna increment or not increment the current listing current okay and then we're going to return coming out of the for Loop and we're gonna check okay maximum number of debt in parentheses foreign security questions foreign foreign uh how did foreign see uh current at Amazon and chocolate uh Thomas foreign scope kinda beta Minnesota he is foreign | Maximum Nesting Depth of the Parentheses | maximum-nesting-depth-of-the-parentheses | A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following:
* It is an empty string `" "`, or a single character not equal to `"( "` or `") "`,
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or
* It can be written as `(A)`, where `A` is a **VPS**.
We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows:
* `depth( " ") = 0`
* `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`.
* `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s.
* `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**.
For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s.
Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`.
**Example 1:**
**Input:** s = "(1+(2\*3)+((8)/4))+1 "
**Output:** 3
**Explanation:** Digit 8 is inside of 3 nested parentheses in the string.
**Example 2:**
**Input:** s = "(1)+((2))+(((3))) "
**Output:** 3
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
* It is guaranteed that parentheses expression `s` is a **VPS**. | null | null | Easy | null |
1,850 | hi uh today we'll solve the problem 1850 minimum adjacent swaps to reach the kth uh smallest number so what i will be explaining is one uh the problem statement we'll go through few examples and then we'll discuss about the solution and then we'll go ahead to the implementation okay let's move to the problem quickly so you are given a string num representing a large integer and a and then teacher k so we have a number n is represented in string and an integer k we call some integer wonderful if it is a permutation of the digit in num and is greater in value than that number so what that does mean is if i have one two three four the this there should be one permutation to it like this and all that but if we call it a permutation wonderful if it's greater than my number so let's suppose i have 3 2 1 4 and the permutation for it is 1 2 3 4 i will not call it is permutation but i will not call it wonderful similarly 4 1 2 3 will be uh permutation as well wonderful as well now we have to find a similar yeah and there can be many wonderful integers as we saw however we okay only care about the smaller one so what does that mean is if i have 3 2 1 4 what will be this first smaller one smaller permutation wonderful stream it will be 3 4 1 2 how we decided it will come back but this is greater than this okay i this is greater than my number but i cannot find any permutation which is uh which lies between these so this is become my first similarly second similarly third so that what it says so it says for an example we have this string the first smallest will be this second smallest will be this and so on now what we have to compute is return the minimum number of adjacent uh digit swaps that need to be applied to num to reach to the kth value so what will be given is will be given a num will be given a k we have to find the kth smallest permutation which is wonderful string and then if i want to convert this num into this string how many adjacent swaps we need so adjacent swap is let's suppose this is three two one four this is one adjacent swap uh if i want the one four and i change it to four three one two then this will be how many adjacent this moves here so three adjacent swap so this is the problem statement so if we see the problem can be broken into two steps step one and step two step one is take the number convert that into the kth permutation which is also wonderful once we do that the second step would be count the number of adjacent swaps required to convert num to set kth permutation of this so let's move to the first one first so let's suppose i have a number one three two four now what will use what how will make sure that i will make sure that this get converted into the kth one so let's see what we have to do for the first one then we'll see from the first one we can use it to convert to the second one because it will be similar like this is my zeroth permutation this is my first permutation next time well i will consider this is at my zeroth permutation and then uh applying the same rule uh to this permutation like the same algo i will get the second permutation so let's see how to convert this there is a standard algorithm what we do is this let's suppose this is my number what we do is we see and we see from back side until like suppose this is j we traverse until we have array j greater than array j minus 1 so and let's suppose this is uh this is the j now and this is the i is equals to j minus one so we know now uh so let's take an example let's suppose i have a string one two three four sorry not this one four three two one so i cannot have any permutation which is wonderful to this right because i cannot find any new number to this so let's suppose this is the string and this is the string one four three two one so i cannot actually get anything from this one i cannot actually make any change to this and get the new permutation with one as starting point and uh get the next permutation which is wonderful because i cannot just reduce it to any permutation which will be less than this so that's why what we try is we iterate from back until we have j is equal to j greater than j minus 1 and this is the point where we reach now what we do we cannot do anything about this one we cannot minimize it or we cannot reduce it so what we try to reduce this string and we keep this string as same so let's suppose i have 5 9 1 4 2 3 1 so will this is my jth element i cannot change this i can if even if i change anything to this that will become smaller this is my led element i will use it to make it smaller but i don't want to change this because if i make any change to this one either it will become smaller or bigger and i don't want to make it smaller that will not help me i want don't want to make it bigger also because i have a way to make it bigger from later positions like if this position r so what we do in this case is because this is descending what we do we reverse it now we have this initial part let's call it x this ith element and reversed y part why we reversed it because we know this is in descending order and we want to keep it minimum so we if we reverse it this will be in ascending order and this will give us the smallest one but now the now is the main point in this y if i replace i with any of the element any of y element which is greater than i and also smallest in y so any element in y which is greater than ith element and smallest in y if i swap those elements let's suppose this element i will get the minimum one let's see this algorithm with an example so let's say we have 1 3 4 2 5 6. we want to find the next element to this so what we'll do it will be like 1 3 4 2 5 6 traverse from back check if j is greater than j minus 1 yes it is replace it so this is my string now in the next iteration it will be like it's uh 6 is greater than 5 6 is greater than 2 now what we have to do is reverse this string sorry again and replace 2 or swap 2 with the minimum of this string minimum of the string is 5 so it will be 1 3 4 5 2 6. so this is how it works let's take just for example one more example one five yeah we took that example like one five three two in this case and let's take six as well so in this case we this is greater than this but five is greater than this so he'll reverse this string swap one with this is my i this is my j swap one with the minimum of the string so minimum is here six two one three five and we'll get the next iteration so this is the first part second part is count how many adjacent swaps will need so this is a simpler part so let's suppose i have a string one three two four one two four three how many swaps adjacent so absolutely required we will require only one just swap this one with this one now let's suppose i have one two five four three i have one five two four three how many steps it will require it will also require one trap so let's make it little bit complex i just add five three to four okay so what i have to do is i have to first of all see two letters one is in place two is not in place so we'll search for two it's two positions from here what we'll do is we keep on swapping it so let's suppose five i want to find two so this is a 2 then 2 will come here first 2 3 then 2 will be swapped with this and it will come to 5 3 and then we'll move to the next element so five and five three and four again one sub will required and so on so for two we added two steps for four we added one step so total will be three swaps three adjacent traps okay so this is how we'll solve this problem in two steps so let's move to the coding now implementation part so this is we have so let's start the coding so let's convert this number into cat because we need swapping and all that stuff for this okay this is okay permutation let's take this permutation from a method it's passing the k so it will return me the k permutation now just to debug it what we can do is we can print this to see what actually we got and then just return hsn so apps hey and kth permutation okay so this is the first step this is the second step so here we are converting this array into kth permutation here we are just returning the number of so me make a copy of it i'll get this so this is what we're doing uh we are iterating our string from backbone until what until we get until we have descending order until we find any element which is uh greater than our which is less which is greater than its previous value so it will be like let's say if character numeric value so until we find a value which is greater than uh its previous value will just iterate it and once we find it we'll just reverse it with i until the end keep the algorithm in mind that we discussed we find out a element which is more than its previous element now we are reversing that element until that point okay now what we have to do so seconds first second step in the first one once we reversed it now we have to replace our element with the smallest element in our uh nr so this was the first step reversing it second step was reverse this ith element with the smallest of these elements so how to do it smallest of these elements which is greater than i so any element is y which is greater than i and smallest in y so let's see remember the string we have now this string we have now is in ascending order because this was in descending order we reversed it now it's in ascending order this is what we are doing is iterating world so again let's use it so if my character j is greater than my i minus one element should be visible then the swap okay what we did is also click here like what we did is in this code so we reversed it now what we are doing is this is ascending so as soon as i'm iterating over it as soon as i get some element which is greater than i'll just swap it we can use a binary search for that guys also like because this is a in ascending order find an element which is greater than this element and just swap it and now move let's move to the second part okay now go to the second part which is counting the adjacent ones let's test this first let's implement reverse and swap at least we'll get be sure like this step one is working fine ij a simple swap another one is okay so this is just keep on changing them we can use as well okay see if this works we have system now and let's check for any compile time error yes there is uh what's that i think it will start exhibition have we missed some closing bracket yes cannot find the symbol get bomb okay that's fine guys skate communication okay is what happened and we have to just implement this so so it will help us to find that but just for now we can just want to test this so finally yes so you can see like for the fourth one we are getting for the similar one we have here let's try for three yes for it should be yes it's same so that is working for us we'll see more when we submit it but now move to that decent one so this is how this is the second step we moved on where we'll see count of edges in swaps and this is very simple method so let me just write and explain so let's uh we have to convert one string into another but we have to see how many adjacent traps so that's important point adjacent traps that we don't have this until we have this if it's equal then we can just ignore and move but until the both the elements in both are not equal we just add plus one what we are doing with this is the same thing we are searching uh let's again take that example two five four three one what was it one uh five three to four so this is one five will not enter into while loop this is two and five now we'll search where this 2 actually exist in this string and we'll just keep on swapping it until we match that so that's how we can find the edges and flaps j will point now to while i didn't change simply just keep on swapping as many swaps we do we just keep on and then let's see for three it's fine yeah so let's try submitting it yeah so it's working just to make it little faster yeah so uh thanks guys uh just feel free to comment for any other problem you want me to solve i can explain with the whiteboard and with the code yeah thank you so much | Minimum Adjacent Swaps to Reach the Kth Smallest Number | minimum-length-of-string-after-deleting-similar-ends | You are given a string `num`, representing a large integer, and an integer `k`.
We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones.
* For example, when `num = "5489355142 "`:
* The 1st smallest wonderful integer is `"5489355214 "`.
* The 2nd smallest wonderful integer is `"5489355241 "`.
* The 3rd smallest wonderful integer is `"5489355412 "`.
* The 4th smallest wonderful integer is `"5489355421 "`.
Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_.
The tests are generated in such a way that `kth` smallest wonderful integer exists.
**Example 1:**
**Input:** num = "5489355142 ", k = 4
**Output:** 2
**Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number:
- Swap index 7 with index 8: "5489355142 " -> "5489355412 "
- Swap index 8 with index 9: "5489355412 " -> "5489355421 "
**Example 2:**
**Input:** num = "11112 ", k = 4
**Output:** 4
**Explanation:** The 4th smallest wonderful number is "21111 ". To get this number:
- Swap index 3 with index 4: "11112 " -> "11121 "
- Swap index 2 with index 3: "11121 " -> "11211 "
- Swap index 1 with index 2: "11211 " -> "12111 "
- Swap index 0 with index 1: "12111 " -> "21111 "
**Example 3:**
**Input:** num = "00123 ", k = 1
**Output:** 1
**Explanation:** The 1st smallest wonderful number is "00132 ". To get this number:
- Swap index 3 with index 4: "00123 " -> "00132 "
**Constraints:**
* `2 <= num.length <= 1000`
* `1 <= k <= 1000`
* `num` only consists of digits. | If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1 | Two Pointers,String | Medium | null |
232 | welcome back everyone we're gonna be solving leeco 232 Implement a queue using stacks and I actually had this question as in um as an Amazon interview question I want to interviewed with them last year so definitely it's definitely a good one to know um so all right so they want us to implement a first in first out cue using only two stacks and the implemented queue should support all the functions of a normal queue push Peak pop and empty uh implement the MyQ class void push pushes element x to the back of the queue pop removes element from the front of the queue and returns it Peak Returns the element at the front of the queue empty returns true if the queue is empty false otherwise and what else do they give us down here we must use only standard operations of a stack which means only push to the top peak pop from top size and is empty operations are valid and they also say depending on our language to stack may not be supported natively Okay so they want us to implement a q with two stacks so we can just say in the initialization we can say self Dot stack in is going to be an array or a stack and then self Dot stack out will be the same so when we push an element we want to push it to this stack in so we will say self Dot stack in dot append the x value now when we pop from our stack right when we pop from the queue say um we're adding in one two three as an example for stack end right one two and three when we pop we want to pop this one in constant time right that's how a queue works it was the first one in so it has to be the very first one out so how do we do that using two stacks well we have to iterate through this stack and then append everything to here from the back right so while this stack is not empty we will take these values put them in this one so in that case it would be three two and one and then this would be empty and then we can take this value and pop it off and then we will have to take these remaining elements and then put them back in to our stack in so let's do that so we'll say a while self dot stack in is non-empty we will uh say self dot stack out dot append self dot stack in dot pop and then we will get the last item from self.stack in or out sorry self.stack in or out sorry self.stack in or out sorry self.stack out is going to be our value self.stack out is going to be our value self.stack out is going to be our value of this pop to get rid of this and then after we pop we have to return those values from this array into the first array so then we can say while self dot stack out is non-empty we are going to say non-empty we are going to say non-empty we are going to say self.stack in dot append self.stack in dot append self.stack in dot append self dot stack out dot pop and then we can finally return this uh self or this value that we already obtained up here so that's the pop function the peak function should return the element at the front of the queue and to do that we can just grab the very first item at self.stack in so we can first item at self.stack in so we can first item at self.stack in so we can say return self dot stack in at position zero right that's a constant time and then empty we can just say return length of self dot stack in equal to zero so let's run this list I spell append wrong okay so we'll run this and pass the test case we'll submit and it does run perfect so runtime what is it this is going to be constant time pushing is going to be constant time this is going to be this whole function pop is going to run in O of n o of n plus M time where n is the length of our stack in and then m is the length of our stack out Peak is going to be constant and empty will also be constant as well | Implement Queue using Stacks | implement-queue-using-stacks | Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer. | null | Stack,Design,Queue | Easy | 225 |
353 | hello everyone welcome to clean coder youtube channel if you are new to this channel i will highly recommend you to subscribe to my channel as i make content related to software engineering system design and data structures and algorithms today we are going to solve this lead code problem number 353 the name of the problem is design snake game so let's check out the problem statement quickly so this problem states design a snake game that is played on a device with screen size with into fight play the game online if you are not familiar with the game okay so the snake is initially positioned at top left corner zero okay and the length of the snake is one unit and we are given a list of foods position okay in row column order basically coordinates so when a snake eats the food its length and the games score both increases by one each food appears one by one on the screen okay for example the second food will not appear until the first food was eaten by the snake so the next part is like when a food does appear on the screen it is guaranteed that it will not appear on a block occupied by the snake okay basically uh the food won't appear at the coordinate where the body of the snake is already present so this problem i think will become more clear when we'll go through this example so let's come to this example so what it tells is that we have a board or screen with width 3 and height 2 and food is located at one two and zero one coordinates okay so initially only one two four would be available and once this is eaten out then zero one food will become available okay so a snake this new snake this kind of constructor would be provided to us and initially the snake appears at position zero and food is at one two as depicted by this matrix okay so the first command he gives is he calls the move function with r as the argument so this should return zero okay because uh the food is not present on the right side and size of the snake is same or like score is not increasing so here uh initially we can assume the size of the snake as one and score is zero so there is a relation between size and score like score is always equals to size minus 1 okay so in this example he has talked about the score but you can also uh solve this problem for the length of the snake okay so now he gives r command and our snake moves towards right side now snake is present here okay now he gives down command and our snake points here okay still there is no port so length is same and score is same now he gives our command okay so as food is present on one comma to this one okay so this food he eats and his length increases by one okay so this is the snake now and our length is two and score is one okay now what happens at this moment is the next food starts appearing okay so the coordinate of next food was zero one so zero one here the food starts appearing okay so food appears here okay now he gives the command as up okay so our snake will become like this okay so length is still same our score is still same it will return length minus one or score which is one now he gives left command okay now the food is present here and he gives left command so size is bound to increase by one so the size would now become as uh previous plus one okay size would become as three this is my snake okay now he gives the command as up okay so what will happen when he'll give this up command so on giving this up command the snake will hit the boundary of this matrix right so in that case what we are supposed to do is we are supposed to return negative one or like finish the game because like snake lights with the border and in the classic snake game this ends the game okay so there is one more thing where you need to be careful which is a snake should not bite itself let's say our snake is like this and if we take a move like this right so game should also become over when snake bites itself okay so these two things you need to be careful while solving this problem so i hope like the problem statement is a bit clear now so like this is the uh kind of class we want to make and like these kind of constructor we want and like this food would be provided okay so uh you can assume like the output of these to be uh like this as given in the example okay 0 1 2 negative 1 so the snake initially starts from here right and food is here okay so he like the user gives a right command okay so what will happen snake will move to next block so snake will move here okay so now let's move to the next command okay so the user gives down command okay so what will happen now is the score or the size of the snake is going to remain same and the snake is going to come down by one step okay snake is here now again the user gives a write command correct now what will happen so at this point this food will be eaten by the snake okay so size of the snake is going to become the previous plus one okay the snake size is two now at this moment the second food item will appear which is this okay and this food is eaten okay so now this is the state after third call now what he do is like he gives fourth command or up command okay so what will happen is now snake will move like this okay so it will move like this so size is still same and we are returning one or size minus one okay now our fifth command he gives which is l okay so with l what will happen is he'll eat this food okay so this food is going to get vanished and size of snake is going to increase by one so this is the state of the snake now and now he presses the up command so when he presses the up command like this is my snake it will hit this wall okay so it will hit this wall so game will become over and we are supposed to return 1 in that case okay so this is the problem statement briefly and how we want to implement it is on our own like we can use any implementation we find comfortable or like uh more easier to visualize so next i'll show you how i solve this problem let's have a code walkthrough okay so this is the main class and we have a snake game class okay so in order to visualize any point in space i have made a pair inner class this has two variables for instance variables x and y it has a constructor and i have overridden equals and hash code method uh because i want to use it for hashing like this will be used in a high set so i need to provide my own implementation of equals and hash code so that i have provided next let's try to trace the flow from the main method so the snake game is a constructor let's go and check out that so will be supplied width will be supplied height and will have a 2d array of foods so what i am doing here is i am assigning these parameters to instance variable and i have taken snake and foods as a linked headset why link hash set because uh first of all linked headset uh retains order like it stores elements first of all the elements are unique and then they are stored in the order of their insertion so this is the main advantage of linked headset so why we want uh elements to be stored in order of insertion uh just because uh it would be easy to move the snake forward uh like when you want to move the snake in any direction let's say this is my grid right okay so let's say here the snake is present and i gave the up command so you want to move the snake from this direction to this direction so what you want to do actually is you want to erase it from here and you want to put it here right so in linked headset what you are doing is you are removing the oldest element of the linked headset and adding the new element okay this will just move the snake forward and the best part with linked headset is that it provides us contains method and using contains you can easily find whether you have landed over any food or whether you have like bitten yourself so these type of checks you cut you can like very easily put with uh this linked hashtag so that's about it uh let's move forward now okay so uh this is a basic for loop i have used to put the foods in the linked headset okay nothing fancy here then i am adding the snake to this linked headset snake i'm assuming that a snake of size 1 is present at coordinates 0 and i am marking my instance variable x and y as 0 which is the current location of the snake okay so now let's try to check the move method okay so how is move method written let's check that out okay so user can only give four commands right up down left or right correct so uh if he gives any other command then it's an invalid input and i am directly returning 81 in that case okay so that is it and like the four command let's say user gives up so what i am doing is i am like on up i am reducing the value of x on down i am increasing the value of x on left i am decreasing the value of y and on r i am increasing the value of y first of all this thing and then uh what is happening in validate let's check so in validate what i am doing is i am just checking that whether uh on that point snake already exists it is a case like a snake has not bitten itself something like this has not happened and second thing which i am checking is the bounds okay the bounds are correct so everything is in the grid so likewise if the snake is bitten by itself then i'm returning true and if the bounds are crossed then in that case i'm returning true so validator is returning true on the like problematic cases this thing uh you just need to take care okay so what will happen now is uh i pressed up and it will validate everything is fine and snake has not beaten itself and then it will reduce that instance variable value x minus and then i am going to actually change the snake size depending upon whether food has been eaten or not okay so let's say uh let's check this change snake size method okay so what is this doing so this is nothing but this is uh getting foods as a stream and finding the first food remember that food appears one by one and we should eat the food which is present at the first position initially only like rest of the foods are not visible so what i am doing is uh in this if i am checking whether there is a food present at this place so if food is present at this place i am adding that to the size of the snake and i am removing the port from that linked hash set okay so this will increase the size of the snake by one and this will remove the food from the foods asset so in the else part what happens is food is not present at that place so what happens is i need to uh do something like this okay so let's say snake was like this okay and i pressed and up so what will happen is i want to remove this and i want to place this right so this is what i am doing so snake dot add xy is doing this and this part is removing the last field so basically size of the snake is going to remain same size of snake going to remain same okay i think this uh change snake size method is also clear to us so let's now scroll down a bit so all the logic of up down left right is similar and like the respective parameters are getting changed in terms of their coordinates so let me bring you to this part so this is just a kind of debugger statement so if you want to check where the snakes are lying you can mark this as true and on the console the position of snake would get printed but in the actual problem while submitting you can mark this to false and in the end what i am returning is the size of the snake minus one which is the score asked for the problem statement okay so let me run this i think you should be able to see the output over the console 0 1 2 and negative yeah the output seems to be correct so that's it guys i hope you liked my tutorial please give it a thumbs up if this added any value to you and once again thanks for watching this video hey guys do check out this instagram channel the encoder community for all the jokes and memes related to software engineering thanks a lot | Design Snake Game | design-snake-game | Design a [Snake game](https://en.wikipedia.org/wiki/Snake_(video_game)) that is played on a device with screen size `height x width`. [Play the game online](http://patorjk.com/games/snake/) if you are not familiar with the game.
The snake is initially positioned at the top left corner `(0, 0)` with a length of `1` unit.
You are given an array `food` where `food[i] = (ri, ci)` is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game's score both increase by `1`.
Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.
When a piece of food appears on the screen, it is **guaranteed** that it will not appear on a block occupied by the snake.
The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies **after** moving (i.e. a snake of length 4 cannot run into itself).
Implement the `SnakeGame` class:
* `SnakeGame(int width, int height, int[][] food)` Initializes the object with a screen of size `height x width` and the positions of the `food`.
* `int move(String direction)` Returns the score of the game after applying one `direction` move by the snake. If the game is over, return `-1`.
**Example 1:**
**Input**
\[ "SnakeGame ", "move ", "move ", "move ", "move ", "move ", "move "\]
\[\[3, 2, \[\[1, 2\], \[0, 1\]\]\], \[ "R "\], \[ "D "\], \[ "R "\], \[ "U "\], \[ "L "\], \[ "U "\]\]
**Output**
\[null, 0, 0, 1, 1, 2, -1\]
**Explanation**
SnakeGame snakeGame = new SnakeGame(3, 2, \[\[1, 2\], \[0, 1\]\]);
snakeGame.move( "R "); // return 0
snakeGame.move( "D "); // return 0
snakeGame.move( "R "); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1).
snakeGame.move( "U "); // return 1
snakeGame.move( "L "); // return 2, snake eats the second food. No more food appears.
snakeGame.move( "U "); // return -1, game over because snake collides with border
**Constraints:**
* `1 <= width, height <= 104`
* `1 <= food.length <= 50`
* `food[i].length == 2`
* `0 <= ri < height`
* `0 <= ci < width`
* `direction.length == 1`
* `direction` is `'U'`, `'D'`, `'L'`, or `'R'`.
* At most `104` calls will be made to `move`. | null | Array,Design,Queue,Matrix | Medium | null |
404 | Hello hello everybody welcome to my channel and solve the problems of vivo starting this problem i have created a facebook group for my channel you can join the group like water will travel aproducer iss saal bhi problem find the some of all left lips in a group In The Mystery Solve Entry Between Is Like Three Starting From Bharuch 90708 Looser Black Lips Wild Se Zara Lips Were Totally Free Live Web School Will Solve This Problem Will Start At Normal Labs Like Subscribe Our Channel Like This Is Not Simply Check This Route His Left Child yes fruit his life style especially for left side benefits loop is that left eliminate this will return value of root which will quit from subscribe b.sc math solve will b.sc math solve will b.sc math solve will start from nose glue the video then subscribe to the amazing check subscribe 7 the Benefactor And There Is No Anti Bijli What Is Not Laugh With Just Simply Return More Subscribe Implementation Check Return Gift Root Help Channel Notification Al Ki And G Road Dot Loot Is Channel Ki Hand Root Dot Right With Which Is The Condition Checking The Road Office Liquid Return Root love you to a plus half the value from the rise of tree souls will be sum of form louis from the subscribe to i ignore dksbs simply return road dot left subscribe must dot right side par lena hai similar to simplex no special record implementation also amused E Were Getting 0 Oil Safe Visum Plus 125 Working S Root Dot Left And 554 This Condition Is Wrong Actions Where Not So Nobody Will Get The Answer 80 Flats In This Key And 618 Record Tips For The Time Complexity Of Solution Is Open Withdrawal Tree And Space Complications Who Subscribe Vikas Step 4 How Will Solve This Problem In Birwal Problem Will Solve Again The Places Were Treated On That Infrared Fifty Shades Root Note 3 Our Why Name Will Tree Toe And Anil More You Don't Size K 2004 Joe Hair Clinic Silai Dasham Variable From The Zero Between World Track All The Sum Of Lucerne Know Will First Poll The Not From The Why Luta De Will Check Root Ki Dot Laptop Not Equal To Null Ki And If It Root Dot Loop Same Condition In Same Condition Receiver Changes Extra Condition Equal To Null AND ROOT DAUGHTER VIDEO CHANNEL SUBSCRIBE DAUGHTER -IN-LAW -IN-LAW -IN-LAW WHO IS NO OTHERWISE IT IS NOT LEAD AND WILL SIMPLY EDWARD SNOWDEN TO OUR GIVE ME THIS PROVED THAT LEFT THIS IS LIKE IT CONDITION OF SIMPLE BUT AVOID DOING THIS ROOT DETROIT LAKE I WILL CELEBRATE IN Two days after everything you will return of the day which I test series word form dot right e per insensitive it number extremely show here that this tweet note external purpose will work let's now directly hello how will accept for the time complexity of dissolution and also Point and subscribe that soft this is the amazing solid liquid and click the subscribe button and subscribe my channel otherwise check root subscribe to that end root dot left right that equal sunal inside k city diesel application will return root bottle plus subscribe this video roop dot right is other wise villagers call for very brain through developed plus a plus da the root dot right subject member but middle heavy next side don't like comment definitely right leg if one liner channel display that thank you see you tomorrow | Sum of Left Leaves | sum-of-left-leaves | Given the `root` of a binary tree, return _the sum of all left leaves._
A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 24
**Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively.
**Example 2:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-1000 <= Node.val <= 1000` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | null |
1,822 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem sine of the product of an array it's May 1st so you know they are going to give us an easy question but be careful because this easy problem is actually a little bit trickier than it might seem at first I actually did get the wrong answer well at least the way they intended us to solve this problem but the idea is simple we're given an array of integers like these we could have some negative integers we could have some positive integers we could even have zeros though in this case we do not have zeros we only have a bunch of positive and negative values the story here is that there is a function defined but I'm just going to completely ignore that and explain to you how I kind of read this problem which you can kind of you know skim over here because it's pretty short but basically we're going to take the entire array multiply each value together that's what they Define the product as being that's something you're probably familiar with so when you multiply all of these together we're gonna get some value by the end of it now it could be a really big value or a really small value it doesn't really matter what we care about is just that is this value a positive value or a negative value or maybe it's equal to zero those are the three cases if it's positive we return one if it's negative we return negative one and if it's zero we return zero so pretty easy here how are you going to solve this problem probably just by multiplying each number together multiply this and at the end of it we will have a negative integer I believe so actually no it is positive so we are going to return a one you multiply all these together you're gonna get a 144 I guess from this description so we return a positive one great now before I tell you the mistake what if in a real interview your interviewer asks you what's the problem with an approach like this or maybe what's the potential problem with this approach because it doesn't really take any extra memory we're just iterating through the array so memory complexity is constant time complexity is Big O of n because we are scanning through the array but we can't really do much better than that to get the product of an array so what could possibly be wrong with this solution well you might recall that sometimes in problems values can get really big and we sometimes have to mod the result by some prime number and leak code problem something like seven or something like that the reason we end up doing that is because big numbers can overflow in languages like Java and C plus Max integers I think are usually 32 bits maybe 64 bits I think depending on which type you might be using but the point is that the max integer that can hold is something like 2 billion I don't think python has this limitation but I think it's definitely worth discussing because this is a relevant point in real software development yeah I think it's kind of stupid to have to memorize complex algorithms like Union find and dixtra's album them but this is something that's worth knowing that integers can overflow a lot of bugs can be caused by this so how can we solve this problem without multiplying each value together because I kind of didn't talk about it but when you have values multiplied three times four of course that's going to be 12 but we could have some really big numbers here and you multiply you know 100 by itself a few times and you're going to end up with really big numbers like a billion or 10 billion and that's going to end up overflowing okay so how do we fix that well the answer here is that we don't actually have to multiply each number together because remember we don't have to return the product we just have to return the sign of the product how do we know what the sign of a product is going to be what's the sign of this going to be well it's always going to be positive because all of the numbers are positive now if we add a 0 to this it doesn't really matter what the rest of these are whether they're positive or negative a0 multiplied by anything is always going to be zero so this will return zero now when we introduce a negative number like negative four and let's assume that we got rid of the zero this product is going to be six multiplying it by negative four is going to make it negative 24. multiplying it by another negative number is going to make it positive 72. multiplying it by another negative number is going to make it negative 144. so with each negative number we kind of are alternating sine this negative 1 is going to make this a positive number now so that's pretty much the trick here if you're a math person and you want to see like the formula this is kind of what it would look like something like this well this is like the original that I was showing you just multiply all of these together but this is the same formula in a different way to like write it you can basically see I've taken all of these negatives and converted them into positives except for the negative one which I just kind of left the same over here and we now have four negative ones over here these two are exactly the same but this one kind of makes it obvious that the negatives will cancel each other out whenever we have two negative values the negatives will cancel out so we will end up with a positive value anytime you see two negative signs in a product you can kind of just think that they are not there so we're going to get rid of those two we're going to get rid of these two negative signs as well so when you just have one to the power of four that's just going to be one we don't care about this and so we just have the real product remaining the positive product so as you can kind of tell this is what's going to tell us our solution because we don't care about the actual value who cares about this we care about the sign how many negative values were there if there are four negative values the result is going to be positive if there are three negative values the result is going to be negative if we have an even number of negative values the result is going to be a positive number just like we had with this result it was 144. if we have an odd number of negative values the result is going to be a negative number so basically we're just going to be counting how many negative numbers we actually have so now let's code this up okay so since all we really are doing is counting the number of negative integers that we have let's create a variable for that and then let's just iterate through each number in the input array if the number is zero so if not n or n is just equal to zero I like saying equal to zero because it makes it kind of obvious what we're dealing with python and so in this case we can just immediately return zero that's the pretty simple case the other case here is if the value is less than zero we want to add one to the count we're basically trying to increment our negative count here but if n is less than zero that's when we want to add one otherwise we want to add zero I'm just using the ternary operator the syntax in Python looks like this it's a bit different in other languages this is pretty simple here we're just adding one to this if the number is negative otherwise we're just adding 0 which does and do anything we could have written this a different way which would just take you like a couple extra lines of code if you wanted to like actually write out the full if statement but I will not do that but this is a pretty small thing you can write it however you would like after this is done though we are going to return our result what is our result though because it's not the number of negative values in the array we are actually going to return negative one if the number of negative values is even we know that if we mod this by two and then it is one and I think I misspoke what I meant to say is when the number of negative values is odd then we want to return negative one otherwise we want to return positive one I keep confusing myself here but this is the entire code and the biggest thing you want to notice here is that we are not actually multiplying each number in the input array so this will not lead to overflow yes we have a negative counter we might count the number of values in the array but that will not exceed 2 billion so it will not overflow and in Python you don't really have to worry about overflow but I think it's still worth talking about anyway so now let's run this to make sure that it works and as you can see yes it does according to leak code I guess it's not super efficient but in terms of time complexity it is so I wouldn't really pay too much attention to this if you found this helpful please like And subscribe if you're preparing 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 hopefully I'll see you pretty soon | Sign of the Product of an Array | longest-palindromic-subsequence-ii | There is a function `signFunc(x)` that returns:
* `1` if `x` is positive.
* `-1` if `x` is negative.
* `0` if `x` is equal to `0`.
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
Return `signFunc(product)`.
**Example 1:**
**Input:** nums = \[-1,-2,-3,-4,3,2,1\]
**Output:** 1
**Explanation:** The product of all values in the array is 144, and signFunc(144) = 1
**Example 2:**
**Input:** nums = \[1,5,0,2,-3\]
**Output:** 0
**Explanation:** The product of all values in the array is 0, and signFunc(0) = 0
**Example 3:**
**Input:** nums = \[-1,1,-1,1,-1\]
**Output:** -1
**Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1
**Constraints:**
* `1 <= nums.length <= 1000`
* `-100 <= nums[i] <= 100` | As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome. | String,Dynamic Programming | Medium | 516 |
70 | Hello everyone welcome to my channel ok so we have who asked this question Amazon Microsoft Adobe Flipkart Siemens or it is maintained graphics also first say Oyo ok so by looking at the input and output of the question let us understand what the question is trying to say. It is given in the question that you must have given N. What is my number of stars? Okay, and how much jump can you make, either you can jump by one step or you can jump by two steps at a time. Okay, and you have to tell me how many wedges are there in total, so that you can climb all these stars till the top, how many wedges are there, how many ways are there, by which you can climb all these stars, whether there are two stars here or not, take whatever example is right. It is important to keep in mind that you have two options, either you can move one step or you can move two steps at a time, it is okay, you have to tell the number of steps by which you can reach the top, in how many ways can you move to the top. Okay now look let's see this first example 122 birds have happened and you are standing here how many ways do you have, look at that you can either jump only one step every time what was that one step plus okay second one What is it brother, we can do it once, we have taken two jumps directly, okay, let's see some other method, we will also see the free one, after that we will move ahead, okay, let's make 3 statuses here, you are standing here, okay. How many ways do you have? Think, you can either do one by one. Hit one jump, then hit one. Okay, took one step. Now you have reached the top. You have found a way by which you can reach the top. It is clear till here, okay, what can you do after that, take one jump from here, then take two jumps directly, take one jump, then take two jumps, then you have found another way to reach the top, okay, what else? The way you can do it is like this, you take two jumps directly from here and then there is one jump, another way has been found, okay and there is another way, three way, so let's see how we will approach it, first of all we will come to our This is the brute method, the first one should be mine, brute force will always think of optimizing it after that, okay, but there are two ways, right, you have two ways to climb the test, this means how many statuses are there in total, 3, how many are the number of statuses, okay, I will take zero. But it is there and you have to reach, so what did we say, we have two options, what will happen if we take two options, brother, where will I reach in the van from zero, we have 3 steps to reach, okay, and if we took a friend, you took the step in one go. So from zero you will reach your place and we will reach here and from this we have two options either take one step ok if we take one step here then we will reach three okay so pay attention here we have reached our target so we have to We have found a way, brother, we have found a way, we have made the return van, here we have found a way, okay, there is a need to move ahead from here, no, we have reached the top, so we stopped here. Okay, let's move on to this one, here again we have two options, then four comes three, this is not valid, we have to go till three, okay, so this is not valid for us, okay And this is valid, look here, we have reached 3, okay, we have found one more, we will return from here, brother, we have found another way, we will return right, we have found another way. That's it, okay, now let's go here, let's explore this too, you took one step, from here we will return, I am returning, okay and I found how many ways, okay, so this thing is clear, then you one You are paying attention to how many possibilities we have tried here. Let's count the total. One, two, three, four, six, seven, eight. N is my number of shares, like I take it. Here you have two possibilities, A, and each possibility is After this, there are two possibilities, like here one is here, okay, there are two possibilities on the number of share, okay, that is why time complexity will be your power, okay, so code these fruits here. Let's take it once, okay, you can also draw this recognition diagram like this, it is okay, that is, to simplify the court, I am telling you how you can write the letters, you had N = 3, it is can write the letters, you had N = 3, it is can write the letters, you had N = 3, it is equal to three, it is okay. So you can do the reverse, I mean, what I was saying was that I am at zero and have to reach three, so first the van came, then you came, you can do it like this also, now let's take the man, I am at three already, okay, so my There are two possibles, I am one step down, okay, so what will happen, it will become two 3 - 1 2 A went, I am doing the opposite thing, only one answer, only one will come, if there is a friend, I will come down, then van A will go, this is me on the van A I will go ok, then there are two possibilities here too, one step, either you go down one step, if you take one step, it will become one, if you come down a step, it will become zero, right after that, look here, there are two possibilities here too. But there is a zero here, look at the van step or you step here, there is a zero here, correct below one, two, three, bus code, okay -1, okay -1, okay -1, then brother, there is no possibility in the case, it means if you give less, zero. Done -1, sorry return to zero, means there is no -1, sorry return to zero, means there is no -1, sorry return to zero, means there is no possibility, no way, you know climb the stars and if the number of shares is less than zero, then it means it is a hypothetical case. Now what did I say if N = Reached 0, like what did I say if N = Reached 0, like what did I say if N = Reached 0, like look here and here, reached zero, means we have found a way, have we gone, then return the van, when we came here, you said, brother, I have found a way. If you come here then you have told me, brother, I have found a way. Here you have told me, I have found a way. Okay, from here you will get zero returns. Okay, if you get zero here, then we will add both to the total base. If we take it out then it has sent 1 + van, it has sent a If we take it out then it has sent 1 + van, it has sent a If we take it out then it has sent 1 + van, it has sent a van from here too, so this is van plus van, it has sent it is ok, if zero has come from here, it has sent 1 + 0, here, then zero has come from here, it has sent 1 + 0, here, then zero has come from here, it has sent 1 + 0, here, then total three has you plus van a. You will go plus three, okay, so we have to find the total base, I will keep adding, I am simplifying, if n is less than zero, the number status is less than zero, then brother, it will be zero, there is no date, there is no method, if n = 0, that date, there is no method, if n = 0, that date, there is no method, if n = 0, that means we If all the statuses are correct then stop the return. Okay till now it is clear. After that what I said that we have two possibilities so we will solve it again. Okay, I just have to send as many vans as I am getting. I have applied step plus and This is how it will be done, okay, everyone knows memorization and why is there a need to do memorization? Look here, look carefully here, okay, let's pay attention in this diagram, one thing is repeating some thing, friend, look, this is a van, isn't it? For WAN, we solved it twice, once here and once here, so repeat. If we had shared the answer of WAN state of this WAN, then we would not need to solve it here again, so we can remember C. Have Repeating Status is also there, when there is Repeating Status, it is the same thing, I can do Mohit, I will fix it, what is the maximum value of N, it is 45, Rakhi is 46, its more will be stored in it, we will do the memories, okay, so let's reduce it by one. Recognition which was a brute force method and memorization, once you code them, then I hope there is no need to read the question again. Okay, let's go directly to our solution. What did I say that we will write a function named solve in which we You will pass N and return what you want. Okay, so I wrote a function called solve and passed it to me. And what I said was that if you give less N then it is going to be zero, so brother, this cannot be a strange number. So make the return zero and if N = 0 means you have reached then = 0 means you have reached then = 0 means you have reached then stop the return. We have to go one way, no one step method is ok then what to do and from here there are many ways to both. Totally sent, we have to send the total, okay, let's run it and see what I have taken in the test cases, I have taken 4 and 45, okay, so the time limit for 45 will be one seat, the maximum limit is only 45, okay. So let's remove 45 and check the rest. Now 4 3 2 19. Okay, 45 was not passing. So let's write 45 here and subtract one. Let's call it 'I'. Okay, call it 'I'. Okay, call it 'I'. Okay, what did I say? Maximum value of N. If it is 45, then take a vector of size 46, right? Main set t - 1 size of t Main set t - 1 size of t Main set t - 1 size of t initialized, okay now let's reduce one that if we have seen the state of this N first toughen it is not equal tu mines van then Meaning, if we have solved it then simply tiff and return it and if not then store it in T of N. Commemoration is simple, everyone would know it, so we have just memoed it, let's see it, pass it for 45. It's done, simply submit it and let's see, okay and submit this question, now let's do one less thing, now pay attention to one thing, this is our third approach, one was brute force recognition, then we memorized it, I will serve the second one. I am saying, now let's see how we can make the third approach, okay, now look, we are going to see another new approach, generally you must have heard this approach, many people call it bottom up, okay bottom. Look bottom, what do you mean, we are moving from small solution to big solution from the bottom and this is our top down tree, it was top down, right, we are coming down from 33, first we did van mines, then you mines. If you hit the smaller one with the bigger value, then it is going from top to down. What is it that there are smaller values, we will get our answer from smaller sub values, so now we are calling it bottom, okay, so due to main, our input was N = 3. okay, so due to main, our input was N = 3. okay, so due to main, our input was N = 3. Okay, man, now remember, just a little while ago, when we coded, we took a vandivector to do memory, we took a vandivector to do memos, right, so now we N, I just take a mandi vector, okay. Now I will tell you what to do next, look carefully, n = 3, so I have look carefully, n = 3, so I have look carefully, n = 3, so I have taken an array named n+1, okay, I have taken an array named n+1, okay, I have taken an array named n+1, okay, I have taken an array named 0123 n+1, now see taken an array named 0123 n+1, now see taken an array named 0123 n+1, now see how I am defining it, listen and see. Have to pay attention that what does it mean? Let's start filling it. First, what does it mean? I am telling you the number of steps, you climb, okay? Someone asks you, 'Brother, tell me the way to climb four shares. Okay, friend, I need to climb two shares.' If you tell me the method, then do I need to climb two shares.' If you tell me the method, then do I need to climb two shares.' If you tell me the method, then do n't do anything with it. Hey off, you send it. Okay, the logic of filling is also very simple. Look, you can jump only once, so there is a method. Okay, man, let's take Tuesday, so what do you say first? First of all, answer mentally that if you are a friend, then in how many ways do you remember, once like this Chadha, or one way, this happened, or both the shares went up in one go, at least two. Ways, what do you mean, you have found out the number, your you mean, what do you mean, you have found out the number, your answer will be n = 2, answer will be n = 2, answer will be n = 2, okay, now look at one thing, here we have gone to three, okay, so now you can think like this too, right? Well, these are three, we have two possibilities: either go we have two possibilities: either go we have two possibilities: either go up one step, or friend Stephen will go, come down, so what will go here, you will go, and what will go here, the van will go, right here, the van will go, then the van will go. I will have to go out, I have taken out the lead of my van, I have taken out the lead for you, so what do you mean, I will simply return the answer of you, if I get the answer of three, then what can you write as the answer of three, sorry, look at this diagram, it is more clear than this diagram. Okay, if we add both then what will happen Ray of Tu, what are you, hey friend, what is F1, answer is A, three, so here we will simply write three, okay, one more thing, pay attention to what we have to return in the last question. What has been asked in this question that you have asked me, the question has been asked, what will you do and N = 3, then we will return the area of N = 3, then we will return the area of N = 3, then we will return the area of N. Look, A has been given in the answer. Look, for small stars, we have calculated and for big stars, we have calculated The answer was found. How did we find the number three by dividing the smaller one by that? Similarly, if four comes next then how will we find the number four. 4 - 2 4 - 1 3 The how will we find the number four. 4 - 2 4 - 1 3 The how will we find the number four. 4 - 2 4 - 1 3 The answer from these two will be two plus three. Punch, look, that means the answer to N = 4 was 5. Remember, the look, that means the answer to N = 4 was 5. Remember, the look, that means the answer to N = 4 was 5. Remember, the answer to N = 4 was five, so answer to N = 4 was five, so answer to N = 4 was five, so how simple it becomes. You can get the answer very quickly from this. Okay, so let's code it. Okay, let's start. What did I say that I will take one hey off zero will be zero, right? You also know that hey, whatever is there, it will be one, right? And you also know that hey, if you are, hey, now you are. He is mine, you will be this, you already knew this and here you have given this team, now here you can also add these, so N = [ N = [ N = If it is If it is If it is 2, then Van will be the answer, okay and let's see, now we have got caught with 3. We will have to come out, how will we come out, what are the possible ways, we can take one step, T of I - 1, we have gone we can take one step, T of I - 1, we have gone we can take one step, T of I - 1, we have gone down, we can take one step or two steps, I - 2, neither is it tf5, I will be I - 2, neither is it tf5, I will be I - 2, neither is it tf5, I will be populated, what should I return in the last Is t of and to be returned? Is t of n to be returned? How simple is this code? Let's run it and see what mistake we have made. Sorry, no, its name is great, this is also accepted. Okay, now one last approach. Okay, you pay attention to this, it is very good, it means it can be done like this too, pay attention to one thing, see that when you want to go out, the Aiya is watching you, just in case you want to go out. I - 1 and watching you, just in case you want to go out. I - 1 and watching you, just in case you want to go out. I - 1 and I - 2 are required, that is, just one first I - 2 are required, that is, just one first I - 2 are required, that is, just one first and just two first, okay, it is a simple thing, no, you can reduce one, you take three variables, okay, it will represent, okay, so I will take T of I write 'C', it's okay I will take T of I write 'C', it's okay I will take T of I write 'C', it's okay and I write 'T' of I-2 as 'A', till now it is and I write 'T' of I-2 as 'A', till now it is and I write 'T' of I-2 as 'A', till now it is clear and in the last answer in our CG, the answer was 'A', clear and in the last answer in our CG, the answer was 'A', clear and in the last answer in our CG, the answer was 'A', this too must have been clear, ' this too must have been clear, ' Till now, it is clear', now look, it is less than the variable. Okay, now pay attention to one thing, let's reduce one. Okay, see what will be the answer. A = 0, okay, Okay, see what will be the answer. A = 0, okay, Okay, see what will be the answer. A = 0, okay, B is equal to C = 2. B is equal to C = 2. B is equal to C = 2. Now pay attention to one thing, start from I = 3, Now pay attention to one thing, start from I = 3, Now pay attention to one thing, start from I = 3, give three less. Equal tu three C, what will happen to me? Look, C will remain in B plus A i.e. zero plus van C will become my van plus A i.e. zero plus van C will become my van plus A i.e. zero plus van C will become my van and we will go out of this look and we will send the answer C. The value of C is van which is wrong. So what mistake did we do, you make C three, okay then what will be the value of C, B plus A, then B is my you and A is my van, so it becomes 3, after that the answer will be so A is van. You made B, you made C three, then what happens from Ranchi, C = B + A is just the sum of the previous two, so C = B + A is just the sum of the previous two, so C = B + A is just the sum of the previous two, so 1 + 2 = 3, 1 + 2 = 3, 1 + 2 = 3, okay then remember what will happen after that. Whatever is B will become equal to C and whatever is A will become equal to B. So what I said is that B is stored in B. Whatever is B will become equal to C and whatever is A will be equal to B. If it happens then what was the temp of B, was it equal to B, it is clear, it has become simple, this is enough, let's run it and see, it's all about how much you explore, the more you will learn. Okay, any doubt is there, next video. Thank you | Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45` | To reach nth step, what could have been your previous steps? (Think about the step sizes) | Math,Dynamic Programming,Memoization | Easy | 747,1013,1236 |
129 | it's another binary tree problem and if you love solving binary tree problems and if you love recursion then you will love this problem so it says that you have to find the sum of root to leaf numbers not rootly paths so every leaf denotes a path from root to leaf you don't have to add the sum of the digits but you have to add the number represented by this so for example this denotes 495 this denotes 40 and this denotes 491 so take these numbers as digits of a single number and return the sum of all of those so here we will return 495 plus 491 plus 40. so whatever is this sum you will return that value so let's see how we will solve it so let's say a case where we have just one node let's say five so it has just one root one leaf everything is one this so the result is five just one if we have 5 2 then how many numbers are there just 1 again 52 so here we will return 52 now let's say we have another branch 1 then we have 2 leaves two leaves means two numbers two paths from root to leaf so five two is one and second is five one so total will be one zero three so how we are solving it uh for us it looks very trivial but how you just write the code for this so uh before reaching any node we will pass a value to the node below it so root will have a value it will pass the same value to its left child and its right child if they exist and what these children will do whatever value was given to it will multiply it with 10 and add the remaining values returned for example uh this route will pass on 4 to both of them so it passes 4 here also it passes 4. so what it will do it knows that whatever was the number represented before me in the hierarchy uh the digits that follow here onwards will just be appended after this so this value was passed from root and let's say there are three more digits starting from this d1 d2 d3 so uh this was let's say 125 and these are three four six so total number will be 1 2 5 3 4 6. so this number was passed to us so what we will do we will multiply 10 to it so it will become 1 2 5 0 plus whatever we want 3 so it will become one two five three and then we will pass this value to below and it will again multiply with ten and add four again we will pass one layer further and again it will multiply by 10 and add 6 so it will become this one this is how we write numbers in decimal so 12 means 10 plus 2 153 means this is multiplied by 100 this is multiplied by 50 and this is multiplied by 3 and we are trying to replicate it so what we will do we will have a global result variable so we will keep a result variable and it will be initialized to 0 and whenever we reach a leaf node we will kind of keeping track of what are the digits still reaching here and we will add to result so first time we start traversal from here it's left and right are valid so we don't do anything so we pass 4 to below so it adds it multiplies it by 10 so it makes it 40 whatever digit was passed to it and pass 40 to its left and right add the current value also so it will become 49 and pass 49 to left and right so the task of every node is to whatever value it is given multiplied by 10 and append the current value and uh just one more information all the numbers are from 0 to 9 so that these are single digits number and then that is very crucial so it will pass 49 to both 5 and 1. now it sees that it's a leaf node both left and right are null so what it will do it will again multiply by ten add five so it will become four ninety five and since its leaf node it will update the result so result now becomes four ninety five again this call will terminate and the next call will be made for this write node and again 49 was passed from here same value will be passed to both left and right if they are present so again it multiplies that by 10 and adds the current value that is 491 and then it sees that it's left and right both are nil that means it's a leaf so we have reached the end of the path so whatever is the value add to the result so this value is also added to the result next this call will also terminate here and this will terminate here and it will pass again the four was passed to this branch so same value will be passed here so what this will do this will blindly multiply by 10 and add the current value which is 0 so it's 40 and then it will see that it's left and right or null that means we have reached a leaf node so we have to add the current value to the result and this is what we had expected 495 plus 491 plus 40. so let us write the code for this first we will write it in c plus less than java and python so the base case is that if root is empty root is not null root is null then return zero if root is not null then let's keep a global result which is zero and we will pass this result as reference to recursive calls which we will define in a moment and here will be the logic and then we will return the final result now we will define a recursive function let's call it find sum this val is the value that is being passed to lower levels for example this 4 passed 4 to its below level and this node multiplies whatever value is passed to it and adds the current value so it becomes 49 and again propagate it below if there are nodes otherwise return otherwise add it to result this is what we are doing just one task so let's write that here and we can keep this result as member variable also or we can pass it by reference so that every call is updating adding to the result which was initialized to zero so here what we will do whatever value is passed to me well multiply by 10 and add the current digit which is the valve value in this node not work valve and after adding this we check if it's leaf add this value to result if not propagate this value below only we will add values at the leaf which is a valid path so if not root not left and not root dot right that means it's a leaf then we add to the result and also return don't need to proceed further if it's not leaf node then it will have either left or right or both so if left is there then find some root left and we will propagate this value current which we calculated here and also the result so result is passed by reference you can see it here so every call will every leaf will add its current value from root till the current node to the same result and the same thing for write if right is present propagate the same value and then we need to call this function here and to root zero is propagated let's say we have just one node let's say we have just ten so you can think of that we are calling that same recursive function find some on root and we are passing a value of 0 to it so this is even above the root some hypothetical level 0 it does not have any nodes so we will pass a value of 0 to this root initially so this root will multiply 0 by 10 and add the current value so 0 multiplies by 10 is 0 plus 10 which is 10 it will not be 10 these are single digits so let's make it eight so this will be eight and if it's leaf it will return eight which will be correct so that is why we are passing 0 to the root that is the first call and then result by reference and let's see if it passes the test case it works so let's submit and the solution is accepted and it takes 12 millisecond let's try it again this time 8 millisecond and this time 4 millisecond you can see decreasing without even making any change i am pretty sure it can reach even 0 millisecond it's 4 but you can try a few times it can reach here also so now let's do the same thing in java so let's copy this function and then we will define it as member in result zero and we don't need to pass results since we have made it member variable and let's see and this works so let's submit here it's zero millisecond in java so it's better than 100 percent and now let's write the same thing in python 3. so here also we have made result as a member of this so this same result will be accessed across different calls of this recursive function so so let's submit and the python solution is also accepted | Sum Root to Leaf Numbers | sum-root-to-leaf-numbers | You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`. | null | Tree,Depth-First Search,Binary Tree | Medium | 112,124,1030 |
48 | foreign happy New Year today I'm going to cover a lead code problem number 48 rotate image so we're given an N by n 2D Matrix such as this and we have to rotate it by 90 degrees clockwise so as you can see this Matrix rotated 90 degrees turns into this um I just want to go over my problem solving process the first iteration that I did on this problem I came up with this solution so this element is to be copied into here this element has to be copied into here this element to here and then you move into this cell here and it gets copied into this cell and then this cell gets cut into this cell and this cell gets copied into this cell and then you just move along there until you get to this cell and then you go to the next kind of inner rectangle here which are these elements and you do the process over again so this cell gets copied to this cell and this cell gets up to this cell and then you move there Etc but I realized with this approach that we're overwriting the say five here so one will overwrite five and basically lose your values so since it's supposed to be um rotated in place we have to do a swap so I modified this approach and in my second iteration on the problem instead of we're overriding we make swaps so just go over here we take the one we swap it with the five and then we swap this cell with this cell and that rotates these four outer elements into their appropriate positions if you just think about it the one goes to here and then the one will be here the five will be here and then for the second swap the five will move to here which is its rightful place 25 will be up here and then for the third swap the 21 will go up to here and the 25 will go down to here which is it's uh which are both their respective places and then for the next iteration we move to the right one cell and then we do the same thing so we swap the two with the ten and then we swap this one with this one and move to the right until we reach this cell and we do our swaps and then we move into the next inner rectangle here right here and we say we swap this with this and then we keep going there so that's kind of the structure that I came up with and I just did that on a piece of paper and then I just basically said let's program it so I'll just kind of walk through my code a little bit here um so our rotation width is the width that we're currently the width of the rectang of the square that we're currently swapping in uh Max position is the maximum value that can be for a cell and then we have our starting X and starting y so we're going to Loop um through this while the rotation width is greater than one so if you think about this the rotation width at the start here will be five and then it will be three and then it will be one so obviously for this inner one there's no swapping required so as long as it's three or if you think about if it's an even number of cells then your final Square to a swap in will be f with two so that will also satisfy the condition so we get our starting swap position and then we're going to Loop and this is the loop for whichever Square we're swapping in so at the start we'll be swapping in this outer Square here so we go from We Do It um from I equals 0 to I less than rotation width minus one so four this one the rotation width will be five minus one is four so we're going to be from 0 to 3 here uses one less so 0 1 2 3 is 4 swaps and as you can see here that's how many swaps we'll have to do we'll go we'll swap this one Swap this one and then at that point all our swaps will have been completed and then we'll move to the Inner Circle and do the next ones so this is the for Loop now for our three swaps it's from zero to two as you can see so zero one two we're going to do this for loop three times and I just cased it out so if it's the first swap the second swap or the third swap so for the first swap it's going to be um it's going to be you're going to be swapping the top row here with the column here for the second swap it will be the top row with the bottom row and then for the third swap it will be the top row with the leftmost column in the Square so the index math that I do here is just demonstrating that so at first I do my temp and I get the current cell that we're in so it'll be the starting one so the temp will be assigned one and then I'll get my X and Y values that will be uh the other cell to swap with and then I will assign the starting cell with that X and Y cell value and then assign the other cell with the temp so it's a the index the getting the index is correct is a little challenging but once you get the index is correct it's a pretty simple and as you can see my algorithm is quite fast and quite good on memory thank you for watching have a good day | Rotate Image | rotate-image | You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000` | null | Array,Math,Matrix | Medium | 2015 |
815 | cool 8:15 bus routes we have a list man cool 8:15 bus routes we have a list man cool 8:15 bus routes we have a list man nice when I heard that now I feel like maybe this is gonna be another graph firm and I really don't want to do three graph forms no world or and he's not like you know should have a low down but I guess I will see members in his stuff first well it's each routes sub I is a bus well Dan it - I fuss repeats forever bus well Dan it - I fuss repeats forever bus well Dan it - I fuss repeats forever for example if while sub 0 is equal to 1 570 mr. first plus travels in the sequence 1 5 7 yeah the other forever we start at bus stop s initially not on the bus and we're going to go to pass stop T traveling by bus only what is the least number of buses few is number of places we must take to reach our destination we took negative 1 there's now possible routes one two seven three six seven you want to start one and you want and a T output is to the best strategy stick to it okay and this is maybe a fun palm okay I mean it still crafty bird maybe not seems like 10 to the six do this let's see I mean my first intuition is that so there could be up to 500 things yeah my first intuition is some kind of boy first search me see if I understand this actually yes okay so take the first Street to pass top 7 and then take the second place to bus stops X huh okay so actually this is only the fewest number of buses and not per time okay I think to really okay so actually initially I thought you would actually I mean I know that I went to Palm banned' mean I know that I went to Palm banned' mean I know that I went to Palm banned' reading I guess but I actually initially thought that we would have to do minimum number of stops or something like that actually but this is maybe slightly easier okay so yes 500 wow it's wait so which is highlighted here so you have 500 votes which means and it seems like at most the answers 500 so let's say if you cannot do in five hundred iterations then or whatever your answer is then you cannot do it like so that kind of helps us bound things to maybe some kind of life and I think the really naive thing to do is to kind of like construct a huge adjacency matrix maybe even sparse one maybe that's okay no but that would the under so initially my dog would be to construct some kind of adjacency graph just to graph under sequence itself I don't know what these numbers represent sir oh that's so in the stop itself so for example in this case you could eventually do if n were smaller you could do some transitive closure calculation or something like that and then kind of and then that's really easy right and then you just carried to the shortest path with that but seems like that's not the case yet but this is still a shortest path problem and I think given yeah okay hmm I mean it's a very shortest path problem so I'm just trying to think okay so you have each Wow and the question is how many routes so the first question I would ask myself is kind of for each well which are the well does it intersect or stop at the same stop or something like that and that depends on kind of the length of these two because well they're the same length I just do a for loop for each of them I think there's and I'm trying to think if there's a clever way to do this based on the you know the greatest common denominator or greatest common factor know least comment down me know but basically a GC D for example after way is three and three then you just do three loops and because n is five hundred approximately the biggest number that you can do is five hundred square R which is twenty five thousand I think twenty five thousand but yeah so that should be maybe okay yeah okay so this is a little bit hacky I mean there's definitely a math easy solutions for this but because basically if two number I kind of skipped ahead a little bit of my jump don't process but up basically well if two numbers are not relatively prime to each other then essentially like okay let me forget what the form is it's been awhile bit but basically let's say you have to well to whether typically prime numbers to each other let's say 499 and 500 right they have no common factors because for that it's for $9.99 five $9.99 five $9.99 five I actually don't well but for now and I does not share the fact there were 500 so in that case you would do something you do loops up to 499 times 500 times and then that's kind of your upper bound on your complexity because just number figured I don't know I mean it's not a lot of number theory is some basic numbers me I just don't know how much to explain because I and definitely please ask questions if I'm going a little too fast or going or making assumptions that you don't think I yeah so yeah it's gonna be some sort of VFS but first you have to construct a graph to do the PFS and to out intersect if so yeah so two out in a sec if for example you have one to seven I definitely jumped ahead way too much time let me explain this a little bit better so d so this is about one I just do 112 to so these two routes intersect because after the three on your when T is you go to do a say or to the pan out you if you start doing wonderful let's say at the third time increment they both stop at seven and that's how you can make it stop great actually maybe I'm okay maybe I misread this is really sorry mmm-hmm let me play around something mmm-hmm let me play around something mmm-hmm let me play around something because maybe I just miss about just to be honest for example or maybe I'm sorry you're right and I think it forces me to think about it okay I think this I think I just made this way more complicated than it needed to be honest because I would I so I think initially that I thought that they had to be at the same stop at the same time to make that transfer but looking at the problem again that actually may not be the case so that's the case then I mean so yeah so you're right so like yeah so they don't need to be at the same stop at the same time it doesn't seem like so this actually makes it a lot easier so yeah so you would do something so going back a little bit so yeah you would definitely do some copy something our shortest path maybe is B AB and in this case it makes sense cuz it we do bus transfer stand yeah exactly so my initial kind of going back a little bit was that to Vout in the stack each other if they kind of have the same state if they had the same station at the same time which that's what I thought was kind of the problem and to be frank even if that's the problem eventually if they have the same number they're loop so but yeah so first you would construct all the graphs you would construct a graph where r1 intersection r2 which means that they share at least one bus stop as a photographer and then we just kind of do something of BFS yeah so I think that's mostly right so I think we just need to do kind of how do we want to do it so yeah so we were I just construct a set for each of these routes yeah and then that would allow us to kind of integrate friends and check for things really quickly okay cool let me just do that pre-processing now okay maybe someone like that yeah maybe your said there's a great Queen a bit maybe something like that okay maybe I need more practice with Python I mean I've been doing Python for a while but I've been doing more go lately so I'm still just playing around but definitely let me know if I could do things more Python I go is here to learn and you know okay so dad hopefully that's it okay so now we construct a graph which yeah I think n squares not that bad for 500 so is Rhys query even if you want to go that way so forth yeah Oh hmm wait well actually now this would uh sorry well may I jump ahead a little bit too much because if we do the naive in this section then actually I think I did this the wrong way because when I was heading toilet doing was like for each tab on the station check to see if it's in another station right but actually I think we could pre-processed actually I think we could pre-processed actually I think we could pre-processed it just a little bit smarter instead of doing this we should pre-process two doing this we should pre-process two doing this we should pre-process two stops and let me show you what I mean can stop you yeah have to brilliant should be okay yeah okay fine now to get the biggest number first okay fine well I guess we could just use said that I mean that's it but a map mmm what I was gonna index got some homework on cleaning this outfit now today that's the one I am going to keep this one out okay so for each Oh I've been neutralised sister Samsa okay so now we can construct the adjacency list maybe even matrix yeah if I wonder list okay fine and weep okay this is stops mm whoops I don't know what I'm doing copy and paste my head except I type it out so now for you to stop that shares the same for each number in it we yeah there's an edge between all pairwise stop number Estella in a stop okay it's probably a more pythonic way to do it as I forget how to do the pairwise one I mean it's probably in what you McCoy in accounting one but uh you're just adding these edges and I was I need to we need to how is it well okay Tim I always forget which one is which wait oh yeah yes I yeah you I mean you're definitely right I meant to I was going to do it this way but then I went for it okay friends I'd be like oh yeah I would have been in kind of striking around here for a little bit but okay so this should create the adjacency this just for kind of seeing what I did when a quick twin and then one want it real quick also yeah you're right no just no yeah this is still okay Oh anyway hmm why am I thinking of yeah I do not remember 500 bucks is fine no this is my okay that's really clean I will try to change that they do okay oh man yeah of course sign spring Tom when you mixed too many languages in your head that's what happens but of course it's addiction yeah man I do not remember pipeline it stands late what oops wait that's not right am i commenting it's out whoo my stops me now we know I'm just being stupid kind of mix two variables in my head a little bit now this so okay so the stop number and stop set whoa just looks okay and I have them backwards I always have them backwards items Thanks yeah it's pin up don't blame it on the late night yeah Sofia it's 11 o clock at a very long hike today okay cool excuses aside no thanks for then and that's why I'm practicing okay so this creased adjacency list that is actually not quite why is it no I mean it's correct but actually this pie should be a set so of course okay so that so now the graph is constructed but uh yeah thanks for the heads up okay so now the graph is constructed and as and this actually becomes a very standard PFS I mean the confusing part that I had initially was also that I'm not 100% sure why this is a hard fit but not 100% sure why this is a hard fit but not 100% sure why this is a hard fit but yeah now that you have the graph that you want to construct it I mean and I say this but of course I've been taking a lot long times so maybe that it is well it'll be ok but ok yeah so now we could do some kind PFS and now have an s entities yeah I mean we could actually do perversity averse I think it doesn't really matter well actually it does matter but yeah I think as long as we do a shortest path thing it should be ok and now we have V Plus D algorithm and it's kind of yeah if you tuned in earlier you because it's kind of weird because I'm literally like doing the same thing from before from like the last problem so I mean I'm gonna try not to copy and paste then it is you send you a copy and paste in my head so okay let's do a topo instead and we might be to complain about this later if I don't need to but yeah okay oh yeah it's how do I plant it okay fine let's not do this waiter and this is only 500 so up to 500 so was the number of outs okay yes well then we queue it and set it this thing - okay this thing - okay this thing - okay I think that's roughly right now I'm going to try to do some testing and obviously I have mistakes mm-hmm oh and obviously I have mistakes mm-hmm oh and obviously I have mistakes mm-hmm oh is this one based oh I didn't this is not related it's just the station so okay hmm so that just add a wrinkle a little bit but we have what a man that also tells you that I should read the poem okay only next time of course but uh hmm because now effectively what we need is actually yeah actually it's not that bad because we already have to code win but be good so well we have written is assuming that given of Wow or s how do we get to vowel of T which is the interpret as ensuing which is not correct of course what we actually want is how to get them stopped as to s T but that because of the pre-processing we that because of the pre-processing we that because of the pre-processing we did earlier we can actually do this pretty simple ly thankfully so actually so will we actually what I mean now instead of a single source shortest path on your BFS now we run a multi source multi-source now we run a multi source multi-source now we run a multi source multi-source shortest path or a multi source shortest path on your p FS and essentially what that requires is kind of what I'm doing now and typing it out which is really instead of pushing just the starting element on the Q we put other elements on the Q as well on the stop so and because we already know we really processed it here we can actually get to a pretty simply so we have four Oh first stop in stop set stop wait this is a radio stop set okay so that should be okay oops and now instead of Ken the distance of just T we kind of do the in inverse yeah the inverse of Converse yeah what the opposite grab we set up what you're doing before which is I can wear all the t's - yeah the shortest distance or t's - yeah the shortest distance or t's - yeah the shortest distance or shortest distance is equal to say well as we said before the max you can have per distance is 500 so we're just to say a thousand doesn't matter but for stop and stop stops t QE man I'm just copying pacing too hard this is only the case of course okay and in theory both these functions maybe grab whatever abstract it - oh yeah I think that's just because it - oh yeah I think that's just because it - oh yeah I think that's just because I started this at zero but so it should be okay but um yeah and okay I mean I actually I gotta be submitted before I make a fool myself yeah maybe also maybe I should test a little bit more but you can add just some mumbo jumbo really sleep still okay oh man oh okay that's just a typo in the input oh it scared me there for a second okay oh well so there is a bug oh wait how do i we turn negative one okay so that is through a bug because we sure and set the distance with that negative one so when we do the min you know that's not clutch right so this will correctly give us a doubt Cohen quote correctly give us a ton so yeah so that's also one thing when you debug in general make sure that you know you could fool yourself sometimes by getting things correct while in a really weird and like unexpected way which I actually accidentally demonstrated and in this case as I was gonna say because they're sending a while used was negative one that should be on the shortest distant but which would have been okay if we didn't have to do this conversion but now because I have to do this conversion we have to do if we turn a good one and I think if I were to rewrite it then I would actually set this to like some constant up table which I've known to do it but today I mean maybe I'm no off today but because we used it like four times so that's where all the accidents happen but well that's actually want to be funny for some again but uh oh yeah okay oh no expected Cyril oh okay I was worried about some edge case and I guess there's an edge case where well your starts and start with the same so I don't know what these mean it's always a little tricky sometimes for me to kind of like know how I feel about it because someone hen like I do by the you know Leto of the problem usually is true like yeah these edge cases but my thing like it depends on qu your interviewers and why they testing for like I gave me I did not consider the case where to start and the stop is the same stop so start and the stop start and the terminal it's the same stuff but yeah so we did get it correctly - an edge case we did get it correctly - an edge case we did get it correctly - an edge case which I'm okay with yeah so a couple of things first it's an interviewee definitely first thing I would do is improving a code arise minimizes in a way definitely this has to go this should be like you know even if you have a cheesy like max equals a thousand and then just you know move it here I mean cuz that's just a terrible code smell and I would follow gi's profusely and just do it as soon as I can't get him working maybe even halfway through this it's very bad the second is what maybe kind of MA let's use 57 lines of code is actually a little bit longer you know on even as I try to keep it kind of in one function kind of depend on the bottom obviously I would price kind of modulized this a little bit or a lot even especially yeah just to kind of you know make things easier to understand I think otherwise it's okay I think maybe I could have explained this better the pre-processing so basically this is the pre-processing so basically this is the pre-processing so basically this is just kind of allow us to do the intersection of order route at the same time and compact slaves you can see is that this is we plus Yi and that really Percy it's then them is the this one's in the total number of elements in the number and routes so you have a thousand well I guess it's could only go up to 500 but 500 out of five on J elements each then it does that right so it's yeah so which is so is linear in the term in is lenient in the size of the input size but which is you know so and everything else here it's roughly true I mean this is the only thing that is a little sketch maybe and what's the running time of dad well this is at verse n square if you have a in about square let's say n is the number of welds because yeah so because you have to create a list and if it's a full graph then yeah brie square because and that's if you have to construct a graph that's the way you have to do it I like if there's an edge to every other edge then it's always going to be and then it's just gonna be Ries quare which I guess thankfully they didn't do anything crazy which is because it may actually even do don't mmm let's this could be in theory 550 C 500 so I don't know that's actually no surprising I guess they don't have a stress test on this one but babinicz cube is a little fast little slow but uh but everything else is just oh like four terraces as you point out it's a multi source shortest paths and but each century is still a people person well first search or BFS so it once in linear time we Percy especially since we created two adjacency lists can we do faster than that so yeah so I think that yeah so that's how I would kind of explain the complexity I mean maybe I had made them open and I would go into more of Danny we were as an interviewer I mean I think essentially is still a powerful search problem I think that's I like the level of difficulty a breadth-first search is kind of breadth-first search is kind of breadth-first search is kind of fundamental you know it's a little crafty and this boy i think it's a little bit on the trickier to understand side especially on this stuff about like sequence one five seven I don't know I mean so I think the wording could be a little bit misunderstood and stuff like that which I have so maybe that's my little bias over there I think in terms of like after you get that difficulty is probably a little bit under roughly uh I think it's a good representation of a difficulty I think it you know it asks you to do some pre-processing which you didn't have to pre-processing which you didn't have to pre-processing which you didn't have to analyze a little bit and before doing the kind of easier to write and that easy to write quick standard ish you're practiced to BFS and so I can I think I would consider putting this in an interview I might have to calibrate a little bit and make some parts like maybe we word it if I get feedback that is a little kind of confusing door but VF s should be in that everyone's always knows I think there should be okay | Bus Routes | champagne-tower | You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.
You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.
Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible.
**Example 1:**
**Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6
**Output:** 2
**Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
**Example 2:**
**Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12
**Output:** -1
**Constraints:**
* `1 <= routes.length <= 500`.
* `1 <= routes[i].length <= 105`
* All the values of `routes[i]` are **unique**.
* `sum(routes[i].length) <= 105`
* `0 <= routes[i][j] < 106`
* `0 <= source, target < 106` | null | Dynamic Programming | Medium | 1385 |
1,404 | are you ill no just feeling a bit off in this question we're given a binary representation of an integer and we wish to return the number of steps to reduce to 1 under the following rules if the current number is even you have to divide it by two if the current number is odd you have to add one to it we know that binary numbers are composed of zeros and ones the decimal number six in a binary number of representation is one zero which is 2 to the power of 2 plus 2 to the power 1. to solve this question we need to understand that the last digit of any even binary number is zero and the last digit of any odd binary number is 1. to divide an even binary number by 2 we only need to chop the last digit off for example 1 0 divided by 2 is 1. since dividing by 2 means -1 from each since dividing by 2 means -1 from each since dividing by 2 means -1 from each power of 2 in 2 to the power of 2 plus 2 to the power one which is 2 to the power of 1 plus 2 to the power of 0. that is 1 in the binary number for any all binary number adding 1 turns it into an even number with the last digit 0. and a 1 is carried over to the second last digit layer 101 plus 1 is equal to one zero if there isn't a second last digit the one is carried over and will result in a new bit like one plus one is equal to one zero so how do we approach this problem suppose we're given the binary number 1101 and which to reduce to one we do not change the original binary number and instead use a variable carry to record a carryover digit we start from the last digit of the binary number since it is odd we first add 1 to the number and a 1 is carried over to the second last digit another number is even we're divided by 2 by chopping it into one zero with a carryover digital one this takes two steps now the number is still odd we add 1 to it and divide it by 2. so that we have one line with another capital of Digit one this takes two steps one way with our carry digit one is even so dividing two means chopping one more digit which results in one with a carry over digit one this takes one step now the number only has one digit the carry digit will result in one more digit to the left and result in the binary string one zero we know that 1 0 is an even number so we divide by 2 and obtain 1. which is our last step finally we reduce the number to one in six steps now let's talk about implementing this process in code we first initialize the variable L to be the length of the input string -1 the length of the input string -1 the length of the input string -1 the variable category is initialized to zero step count to zero the function enters into a while loop and reads the string from right to left and iterates when L is larger than zero in the while loop the function checks the value of the last digit of the binary number and as the carry value if the number is even and there is no carry the result will be even and divided by 2. so we increment the step count by 1 and set the curve to zero if the number is r and there is a carry the result will be even and divided by 2 except we need to carry over a digit so we increment the step count by 1 and set the curve to 1. when the number is even and there is a carry digit or when the number is r and there is no carry digit both results will be odd so we are one to it to make the result even and divide by 2. that takes two steps so we increment the step count by two and set the carry to one the while loop stops when we reach the first digit of the given binary number which is always one after that we check the value of carry if it is 1 it means that a carry over digit 1 needs to be added which gives one zero so we need one more divide to make it one which is one more step and increments the step count by one finally the function Returns the step counts it takes to reduce the binary number to one this is the full solution to a problem number of steps to reduce a number in binary representation to one I hope you found this video helpful please like subscribe and leave a comment thank you | Number of Steps to Reduce a Number in Binary Representation to One | print-immutable-linked-list-in-reverse | Given the binary representation of an integer as a string `s`, return _the number of steps to reduce it to_ `1` _under the following rules_:
* If the current number is even, you have to divide it by `2`.
* If the current number is odd, you have to add `1` to it.
It is guaranteed that you can always reach one for all test cases.
**Example 1:**
**Input:** s = "1101 "
**Output:** 6
**Explanation:** "1101 " corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.
**Example 2:**
**Input:** s = "10 "
**Output:** 1
**Explanation:** "10 " corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.
**Example 3:**
**Input:** s = "1 "
**Output:** 0
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of characters '0' or '1'
* `s[0] == '1'` | null | Linked List,Two Pointers,Stack,Recursion | Medium | null |
783 | welcome back friends today we are going to solve lead code problem minimum distance between vst nodes so before we start looking the details into this problem i just want to mention that i often create lead code solution videos in java j2 technology as well as java j2e interview helpful videos for junior and mid-level java developers so junior and mid-level java developers so junior and mid-level java developers so it can you know help you in your interview preparation and you know you can take a look at different solved examples uh with the java code so please subscribe to the channel you know it has a lot of good material to uh look at and helpful for interview preparation so please subscribe so let's look into the problem details so given a binary search tree with root node root return the minimum difference between the values of any two different nodes in the tree the size of the bst will be between 2 and 100 bst is always valid each node's value is an integer and each node's value is different right so this is the problem description so we have been given a binary search tree for example like this right and we have to find out the minimum difference between the values so as you can see 2 minus 1 is the minimum difference so we will return 1 here so similarly for this binary search tree if you look at the this one and two this is one difference or two and three this is also one difference so this is the minimum difference between the value so we have to written one here so um we are going to solve this problem by you know we will do a dfs like uh dfs traversal on this binary search tree and when we are visiting each node we will uh add these nodes into a linked list and after the dfs is done then we will sort the link list right then the linked list will have like for example the link list for this tree will have one two three four six right after sorting and after sorting is done we will just iterate the list and we will compare each node in the list with its next each value integer value in the list with its next value so one we will compare with two so minimum difference is one so two we will compare with three like this we will go comparing with each element with its next element in the linked list okay and then we will keep track of the minimum difference that we have seen and at the end we will return that minimum difference so let's take a look at the solution that i implemented here so uh first i will just show you the dfs so the this is the dfs where we are passing a route and we are passing a list of integer here so if root is null then we will just simply return right this is the base condition of our recursive function otherwise we will add the roots value into the list and then we will again do the dfs on left subtree and right subtree means we will pass left child and right child of the root on the dfs so at the end of the dfs we will have this list which will be populated right so let's look at the main uh function here so we just created a error list here of integer we pass that list and the list will be populated at the end of this dfs now we are going to apply a collection sort so this is n login time complexity right the sort thing then we just created one diff variable here which is 0 in the beginning and here we are iterating through the sorted list and we are comparing each element here with its next element as you can see here i element with i plus one element here and we are calculating the difference and if we find a difference which is minimum then our mean variable we are updating it so we are keeping track of the minimum here and here uh the mean is defined like here right so min is here which is defined as the integer max value and at the end we are just returning mean so um let's just run the quickly the test here so the solution is accepted so let's just submit this and make sure it's getting submitted so as you can see the it is best percentage right 99.18 so it is best percentage right 99.18 so it is best percentage right 99.18 so this is pretty good uh and this is the time is 142 ms and memory cost right so this is pretty good solution for this problem so i just thought that i'll share uh this problem solution with you for a junior uh developing a position as well as for you know like um for white boarding sessions or for even telephonic rounds so you can get this question you know even online white boarding session you can get this kind of questions so please try to understand how the recursive function works using dfs in the binary search trees uh so as i said in the beginning i often create lead code solution videos for you know to helping uh others to like uh with solutions as well as the java j2e concepts and java that we interview frequently asked questions and their explanation uh you know details so check it out i have created a couple of playlists there one is for at least lean code like solutions it has a lot of problems with examples as well as some programming concept videos are there like the bfs dfs dynamic programming link list hash map those data structures you will get a lot of good things there so please subscribe to this channel subscription will really be helpful so please subscribe thanks for watching the video | Minimum Distance Between BST Nodes | search-in-a-binary-search-tree | Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) | null | Tree,Binary Search Tree,Binary Tree | Easy | 270,784 |
252 | welcome back for another video we are going to do another deco question the question is 2 5 2 meeting lungs given a array of meeting time intervals where intervals i is star i and i determine if a person could attend all meetings example 1 intervals is 0 30 5 10 15 20 the output is false example 2 intervals is 7 10 2 4 the output is 2 let's work for the code we first sort the array by starting time we then iterate overly array to see if each meeting ends before the next meeting starts time complexity is o n log n space complexity is o one and the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching | Meeting Rooms | meeting-rooms | Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106` | null | Array,Sorting | Easy | 56,253 |
713 | welcome to september's leeco challenge today's problem is sub array product less than k you are given an array of positive integers nums count and print the number of contiguous sub arrays where the product of all elements in the sub array is less than k i don't think we actually need to print the subarrays but we need to count them and return the number we have a input of 10 5 2 6 and k of 100 we will return 8 because there's gonna be eight subarrays ten five two six ten five two um two six five two six and that's gonna mean a total of eight you can see ten five two doesn't count because it equals a hundred which is not less than k now a note here is that the numbers are going to be between 0 and 1 000 so we don't need to worry about negatives or even zeros no division by zero no negatives so that's going to be a big advantage now they give you a hint uh it's a little bit confusing what they mean here but they basically say to keep track of the smallest eye as we go through so immediately when i see this question the very first thought i have is kadan's algorithm could we use some sort of greedy method but that's going to be a little bit hard to do um so let's forget about kaden's algorithm instead start from the very beginning if we were to do this brute force how would we solve it well basically we would just figure out every single possible continuous sub array and measure if it is less than 100 so we could start with 10 and then say 10 5 2 ten five two six all right now move to five now five two five to six and just count up all the possible sub arrays that are contiguous and measure the ones that are less than a hundred that would work but that's going to be you know n squared so that's not going to pass so how could we do this in one pass well let's go to my notepad and try to figure out our intuition here so our example was 10 5 2 6 and we have a total of 100 that we want to be less than now let's think about how many sub-arrays are there at each number sub-arrays are there at each number sub-arrays are there at each number one of the things you might realize is at point zero there's going to be one sub-array zero there's going to be one sub-array zero there's going to be one sub-array here there'll be two sub-arrays there'll be five and 10-5 two sub-arrays there'll be five and 10-5 two sub-arrays there'll be five and 10-5 right here there'll be three there'll be ten five two here it'll be four ten five two six and so on and so forth and that actually is every single possible contiguous summer raid so there's a total of nine seven nine ten actually ten there'll be a total of ten our mission now is to figure out how can we go through this sub array and count up the number of contiguous sub arrays that there are that are less than 100. so remember that all these numbers are going to be greater than zero right so if that's the case that gives us some uh easy methods of being able to do this so let's say here we start out by counting up the total product so far is 10 right yeah and products so far it's 10. so we can say immediately all right add one to our total so our total is going to be like one then we move on here and we say all right what's the product so far it's 50. and that means we could add 10 5 and 5 into our total so that's going to be plus 2 that's 3. what about here well product so far is a hundred right so that means that we can't add this to 10.52 but we should be able to figure 10.52 but we should be able to figure 10.52 but we should be able to figure out can we add anything that comes before that so what we need to do is have some sort of pointer that points at the very beginning to say all right this doesn't work but can you move up this pointer divide up our 100 by subtracting or dividing the 10 here so that was divided by 10. now we have 10 left and at this point yes we are less than a hundred so that means we could add the whole summaries here of two right five two and two so this number here needs to get decreased by however many times we need to increase our pointer so there's going to be a pointer here we uh say call it like a i and we should just keep track of this pointer and what's great here is that when we move to 6 now we can do 60. but say that this was like 660 or something and this was 600 now we don't need to worry about everything that came before here because if we need to recount everything here would make it greater right because it's all positive we already know what the minimum number is so now we can just start at this point and continue on to see where this number can get below 100. so basically we need to keep track of uh total subarrays at each number i guess the product so far are pointer for the minimum i and just move through our entire array to figure out our total hopefully that gave you a decent intuition how we might go about doing this let's start coding it out okay so let's start by initializing our n that's going to be the length of nums and we will have our product so far and this will start with one since we can't start with zero because if we multiply anything with zero it's going to be zero so i'll start with one luckily everything's positive so we don't need to worry about any weird things going on our minimum i will call that mini we'll be starting at zero and our total sub arrays at each number i guess start with also zero right and we also need our total number that's going to be what we return so for i in range of n let's move through and figure out what we need to do the first thing i suppose we'll need to do is we'll have to add to our sub arrays add to sub arrays then we are going to move our mini pointer or index to check to see if we need to move this pointer up because if that's the case then we need to decrease our sub array and increase our index number so while loop to increase mini and decrease sub arrays finally if we find that this product so far is less than k then we could add whatever total sub arrays to our total right so add sub arrays to total and it might not be it might be like the number might be 200 or something here and if that's the case we can't add to the total like the sub will still be one but we shouldn't add so make sure to have this if statement here all right so we'll add to our sub array i'll also calculate our product so far all right so let's see um first we want to calculate our product so far we'll do a multiply by the nums i now i'm trying to figure out do we increase our sub arrays i think we do so let's start with that now what do you want to do we want to see if our product so far is if we need to increase our index pointer for the minimum i because our product so far is greater than k so we'll say while product so far is greater or equal to k because if it's equal to that doesn't count either and our mini i is less than equal to i let me think less or equal to i because that's going to be the next point and if that's the case we will have to decrease our product so far divide it by the nums whatever our mini is at this point now we increase our mini we decrease the number of sub arrays and we continue our loop now once this part is reached either our product so far is now less than k or our mini is pointing to the index that we are at we'll check if product so far is less than k then we're going to add to our total number of sub arrays now after that we just return our total so let me get rid of my comments so i don't confuse myself and let's see if i did this right okay so far it looks good let's try test out like if we added something like 600 321 just see if that made sense okay looks like it's working so let's go and submit that and accept it's always nice to get on the first try all right so hopefully that explained to you this is like an o of n solution it's kind of like a sliding window sort of but basically you'll be able to do this one pass with essentially two pointers so thanks for watching my channel and remember do not trust me i know nothing ah | Subarray Product Less Than K | subarray-product-less-than-k | Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
\[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\]
Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k.
**Example 2:**
**Input:** nums = \[1,2,3\], k = 0
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `1 <= nums[i] <= 1000`
* `0 <= k <= 106` | For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function. | Array,Sliding Window | Medium | 152,325,560,1083,2233 |
83 | welcome back everyone we're gonna be solving Lee code 83 remove duplicates from a sorted list so we're given a head of assorted linked list we need to delete all duplicates such that each element appears only once and we need to return the linked list sorted as well so we can do this in place uh because it's sorted so let's say we're always going to have a pointer when we deal with linked lists so we'll say current is going to be pointing to our head node to start so what do we have to do we need to say so if we take a look at example two right we'll say current is pointing at one we need to check if the value at our current node is equal to the next value if it is we can just take current.next if it is we can just take current.next if it is we can just take current.next pointer and set it equal to current dot next pointer which will be one we'll now skip over the second node and be pointing to two so in order to do that we need to run a while loop while we still have you know a next node to compare to so we'll say while current dot next is not none we want to say if current dot val is equal to current dot next dot val then we know we have to remove that node so we'll say current dot next will now be equal to current dot next otherwise we can just Set current equal to current dot next and then at the end we can just return the head so let's run this we passed both test cases we'll submit okay what's wrong here none type object has no attribute next head let's see number of nodes in the list is in the range of 0 to 300 okay so we have a base case I should have checked that first so if head is none what do we want to return we can just return the head so let's rerun this it should work this time and it does perfect so what is the time complexity of this the time complexity is going to be o of n right we are looping through and at worst case we will touch every single node in our list the space complexity is going to be o of 1 we are not creating any new data structures we are just looping through our original data structure | Remove Duplicates from Sorted List | remove-duplicates-from-sorted-list | Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order. | null | Linked List | Easy | 82,1982 |
68 | Hello gas welcome to me YouTube channel, so today we are going to solve problem 68 text justice, so here it is hard level problem and dislike ratio is also more in it because this problem is a little understanding problem, rest of the question is easy, not hard. Okay, so let's see, so what is this question about, I have been given an array of strings, okay and I have been given a with, okay, which is max with, okay, now I have to format all these words like this. What has to be done is that the space in the word sir should be evenly distributed, he will explain what is the meaning of evenly and whatever word is formed will be left justified by you, okay, you might not have understood this, okay, so this is the question I have, like So this is the question and what is its output, this is your output, okay so this is the output, so what has been done to it, so what has to be done in it is that whatever word is there, it is okay to split it into multiple lines and whatever is in one line. There can be any number of words but it should not be in one place from 16 lines and there should be a space in between every word. Okay, this is your question, so how to do it, then it should remain till 16. Okay, 16 should go. So we will start keeping 12345678 910 11 12 13 14 15 16 This will be completely deleted, we will not be able to keep the space in between, we have to distribute it evenly, so it is like there is a space, how much was the total here, how much is the total in this 4 2 6 2 8 And how much was the total then? It was 16 size and where was the total? After that we will lick again. After that N. See, now this is yours till here. Now see how there will be something different in the other one. Till N came here, one became mine. So see, this one is ok, then what is the other one? Example of text, one again, we will make 16, three, five, six, eight, no, 10, 11, 12, 13, 14, 15, 16, ok, start keeping it again, now instead of keeping the destification, we can put it in front of it. So keep it till the text, okay, so now see what happened in it, how much space is there, I have a total of three spaces, child, three spaces and my total was 16, 13, so I failed in 13, so there are three spaces, so now what is the total in it, there are 3 letters, meaning. Space has to be failed at two places. There are two spaces in the 3 letters. Like after the example, after off, it is okay, so failing at two places. If there are 3 letters, then I have to fail at two places. And how much total space do I have, so the example would have been removed here. Now see what will happen here, two left, there will be only one flower, first and then one extra one, which will go to the left, then it is off, then here, then only one will be left, and then what happened. Look at the example of tax, here there is one and here there are two. Why is it because there were three, so see here in the question it has been said that see here it is written IF D number of space on D line the note divide evenly between words on D left bill B assigned more species. And if space is added then here it becomes two and then here it becomes one space okay now for Justice okay so then 16 so how many children do I have now space is 3 space is in the last so this is one more thing here It is said that see what is written between the words Justify and No Extract, it is fine but if you do not want to give extra space, then what will you do in the last line, you will just put the word Sir on one space and like other letters Rahat, you will keep it on one space and as much as As much space goes back, you can leave it later, see what has been done in the justification section, now there is one more letter child, there is relief within 16 characters, like justification, after that, easy is also relief, so see further. If you write ahead also and the number of children you have, then this has to be done, it is okay in the last one and even if you do one side, it will be the same, there is only one size in front, mother, then where will you give space, then you will give space only here, whatever space is left, it will be the same. Also, if there is an even expression, then how will it be between the first and the last, so as you see, if Justice A comes last, then we leave space after three, okay, now what will we do in this, there will be one space, it is okay to evenly distribute the extra space in this. So a knowledge mate will not come, okay, it will not come in this and here again three spaces and here we could have made up to 16, this one started giving one no leg minute word in all, so keep as many letters as the video is okay, given the salary, now see. Last, this last line is the last line, so what will be done in the last line, except 1 liter, we will not distribute it now, after that, whatever space is there, we will leave it like this entire space will remain, okay, now we will not distribute it, as soon as in all Kiya The Vat Mast B Kiya The Na After giving one space, to make it unlimited, if the last word and one word remain, then we will leave as much space as the child has, okay, so this is your question, make the result, okay, what have you taken? Started from air zero, okay, from here we will take this also, if we get it, then how much length can we make a line, max with length, okay, so J < N, unless and Ki, started from i + 1. < N, unless and Ki, started from i + 1. < N, unless and Ki, started from i + 1. And so I got the size, first stored the size in C directly and this is what we have created to store the word size. Okay, this is yours. To store it with a space, we have created C and created WC to store the word size. If it is okay to store it, then I have stored the word size I, so as if we are running it here, what to do otherwise, okay, then they will see it, so they are doing the same here, keeping their head on it, they are looking at an ad in it. Why are you trying because one is your space, right? In the first one will be added like this, then check by adding one more space and plus, one space in the middle and one, we will just add the size of the word. Do it okay, when the example is done, there will be time to add the example. In the break, while making the first line, we did plus. Now what to do if k is equal equivalent, meaning we are making the last line, meaning there will be no time to make the last line like here. Must have come, we will start from here, this one came, then the next one came and reached the next one, that is, if we are making the last line, then what has to be done in making the last line, directly add as many words as there are, add one space each and as much as in the last line. Space child, if you add it then how to make S and as much as it starts from I to I, there will be a break from I to J till the first one, when you give a greater, then only till the time you add Sir and then as much space as you want. Where will we get the length of the word 'child', after subtracting it, the number of children will be equal to the space, then we made space in the space, added S plus space, now pushed it in the result, okay, this one, so how was it that if there is one side and If it reached the last, then it was 'L' and the same did not happen on one side, reached the last, then it was 'L' and the same did not happen on one side, reached the last, then it was 'L' and the same did not happen on one side, like see here there is only one word, then there is one word, then just added it directly and as much space as there was, the number of children was put in the last, okay, so this is So it's done, now mother, this one is length relief, so how many words do I have in total, how will it come out, if we index the minus i here, then it will come out, how many words is there, if there is more than one word, then how will it come in this and one word relief. So after reaching here, I would have mined one, see here, okay, after taking out the total words, now what will be the total space, max with as much as max was, your Maxwell is 16, so by mincing the size of the word, your space will be taken out, so see the words. We have kept the size of the word here because we have kept the size of the word here, now if we minize it then the space will become A. Your total space now has to be distributed, how much should it sit, if there are three words in between then it will become two, space has to be given like If there is a CN, then there is a space of 20 inches in between it, then we will divide it as much as it fills, so as much space as there is, we will give it in between, like if there was 8 space then do it in between this and do it in between this. I gave it to you, so keep it and how much is your extra, mother, take it, no relief, what do we do, then we start on the left, we gave four each, first we keep five here, then five here, and then relief is right from the left, isn't it? Start and then one by one, take out one by one, how much extra space is there, ok, take that out and then what did you do sir, you are adding words in it and what are you doing, see there is extra space in it and from the left. If we want to add, then we will keep adding the extra space in the left one, we will keep adding one more and we will keep mining it. Okay, so after that, we will keep mining the extra space and we will also add that extra space which is four. -First of all, four were given, here the example was given, four. -First of all, four were given, here the example was given, four. -First of all, four were given, here the example was given, after giving the example, off test was given, here there was O, here there was F, yes, there was the test, so what happened here is that I had three space A's. And I had 3, I had a, I had two places to put it. You could put it in between the two places. You could put it twice. We will put it one by one. Once it goes, we will start putting one from the left. After the example, one here, instead of one, two have gone. Now this mother, take two reliefs, even after this off, one comes and here there is some relief, there is only one relief, here both would have ended, otherwise they are doing the same. Here we are just adding the extra page which is there and we are doing the minuses, okay, we have to fill in from the left, so it is okay and when will we put the space in the last space, now see if p note is equal to you, the minus one is okay. Meaning, if you do n't want to give it at the last place, then like here you have done the flower, here if you reach the last place, then you don't have to give space, after this, if you don't want to give it after B, then if you reach the last place, then that much space to check. It is giving that we put it in the result and made i = j - 1. that we put it in the result and made i = j - 1. that we put it in the result and made i = j - 1. Here too i made i = j - 1, so now a Here too i made i = j - 1, so now a Here too i made i = j - 1, so now a went to which, a went back to n, next time i will be plus, then the example will go again here. If we start counting from, then what will be its time complexity? Order of n and space, so it is happening inside this string which we are making, all this space is happening to it, so we can say order and more, okay, see you in the next video. please like and subscribe tu mi channel | Text Justification | text-justification | Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth` | null | Array,String,Simulation | Hard | 1714,2260 |
791 | Welcome to One Arena, today we are doing question number 791 and in this question we will see the problem. What is the problem saying? By saying that we have been given two strings one named order and one named S. The name of the problem is Custom Sort String So in the order we have been given a string in which we have been given a custom sorted that it is custom sorted, we have to follow it in S, so basically the string we will get, we have to sort it according to the order. And when we come to the examples, we see the order in the examples, the order is CBA and SAB, CD is SAB, so we have to follow the order of CBA, so we are like ABC. So it was changed to C, B and A and the D which is ours, whether it is applied here or it is applied here, whether you make it like this or make it like this, the result will be right there, they will accept the result in both the ways, this thing also these people It has been told here that make DC BA, CD BA, CBDA, do any kind of permutation, but within the order given by them in the sort or whatever sequence they have given of the letters. It should be followed, there should not be any change in it, so there is a very simple solution for this, I will share that with you, I have already written here, we were looking at the second example, the same thing is there in the second example as we have order Inside is B C edge and like this our A B C D so now here we have given B C A so here B C A then B C A and then D so this will be an accurate result this will also be an accurate result so this will be given here But let's see how it was solved, first of all, I have used a counter here, so what is the benefit to me by using the counter as I am directly creating a frequency table and a frequency dictionary which does not know about the counter. I will give the link in the description of the documentation, please take a look. What it will do is that according to each element in the string, we are taking the string S at Y and will create a dictionary of its frequency. So now it will create a frequency dictionary. So what we did is I treated the variable named Result as VmStr in which we have run a for loop on which over the order string so that the orderStr which is our custom sort is maintained, then I checked whether this character is inside this dictionary or not. So obviously it is the stem, then what I have done is I have multiplied it by its frequency, so the frequency is Ds, which will come inside our D dictionary which we have created with the help of counter, then suppose there are two A's here and If there were two B's then its order would have been B A a. So to avoid repeating it, here I have multiplied C by D S with its frequency. After that I have made that frequency zero so that it does not get repeated again and added. Let me tell you where the repeat will be. In this way, when I have added all my elements which were in the order, now what we are doing here is we are again running a for loop on D by doing dot items. I have run it where I have taken both the key and the value, so now here in DC, now here I have made it equal to zero, so what is happening to it is that whatever element was in the order, I made its frequency zero so that it repeats. So that it does not become redundant, our result should not be repeated again. Then, whatever frequency is multiplied by the value of that element and that element, both should be deleted and in this way ultimately our result which is prepared, OK one. Let's look at it again on Y. What we did first of all is that we created a frequency dictionary of I had made a dictionary from the counter named D, through it I took all the frequencies from it became DC, then I multiplied it, which was our C, from that, we will have one element in C, like if our first is C, then in C, which is our most. First element came, this is the same count, so only C, which is our race, which is our result string, got added inside it, then rest which is C, then came B, then B got added to it. If their count was more, then This would have added more meaning if there were two C's in different positions inside it, even if there are two C's added consecutively, then it is handling that case also. I hope you have understood all this about the code. Explanation I have given here is the code and solution you will get the link will be in description and if you have any doubt after this you can contact me using comments or contact me on disk and like share and subscribe and keep watching for such videos bye | Custom Sort String | split-bst | You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**. | Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right. | Tree,Binary Search Tree,Recursion,Binary Tree | Medium | 450 |
1,696 | everyone welcome back and let's write some more neat code today so today let's solve jump game seven and this is pretty similar to the other jump games that you might have already solved so the main difference with this problem between the other ones is that in this case we're given a range of jumps we can do so before we were only basically given a max jump that we could do and then everything else everything below that we were also able to do but in this case there's a minimum jump for example a minimum jump of 2 and max jump of 3 that means we have to jump a distance of two or a distance of three they basically said that zeros are positions we're allowed to land at and the ones are cactuses which we are not allowed to land at and since we're not allowed to land at once we're also not allowed to jump from one so we do have to keep that in mind if there weren't any ones in this input array then it would be trivial right basically we would guarantee that we could reach the end of the input array so now you can do this problem with dynamic programming similar to how you can solve a couple of the other jump games but that's going to give us an overall time complexity big o of n where n is the number of positions and times let's say j where j is the range of jumps we can do and it turns out we can actually do better we can cut this algorithm down to big o of n if we solve it with breadth first search and i'm going to go ahead and show you that breadth first search solution which is going to be big o of n time as well as big o of and space complexity so let's look at a couple different examples in both of these examples we're going to say that the minimum jump is two and the maximum jump is three so we know that we're starting here and this is always going to be a zero now it technically turns out that the end position might not be a zero obviously if it's a one that means we have to return false if it's a zero then it's technically possible so we know that from zero we can jump to a couple spots right we can make a jump of 2 which would land us over here we can also make a jump of 3 which would land us over here right so basically in our breath for search this is going to be the next frontier right we're done with this position now we're gonna look at these positions we're gonna start jumping from here so let's start with this one right well it turns out it's a one so we can't jump from here at all right so we're not even gonna try but next we're gonna look at this position it's a zero so technically we can jump from here so let's do the same thing that we just did a jump of two which will land us here and a jump of three which is going to land us here so then you know we're going to look at these two positions we're not quite yet at the result right this is the goal that we're trying to reach but we're not quite there we're going to look at this well it's a 1. so we can't jump from here we're going to look at this it's also a 1 so we can't jump from there either so in this case we've determined that we cannot reach the result now let me just change this example slightly i'm going to change this zero in change that one into a zero just to illustrate why we can do this in big o of n time if we're doing breadth first search because we're not going to revisit the same values twice and we can do that with breadth first search and we're going to basically maintain what is the farthest position we have so far reached which is going to allow us to not revisit the same values multiple times so since we're using breadth first search we are going to be using a cue structure but i'm not really going to show you too much because i think it's pretty self-explanatory pretty self-explanatory pretty self-explanatory how the cue is going to be structured as we go through the problem but we are going to be maintaining one other variable farthest which is going to tell us what's the farthest index we have reached and added to our queue so far so that we don't end up repeating values in our queue right because if we do repeat values in our queue then the time complexity is going to get to big o and squared and we want to try to keep it big o of n if you actually want to pass this on late code even though personally i think if this is a medium problem n squared should be good enough but for some reason it isn't on leak code but so initially the farthest is going to be 0 right because we're starting at zero so we know from zero we're going to make a jump of two or we're gonna make a jump of three and i forgot to update this so this is gonna be zero that's what's going to be different about this input array so i added the indices of each value up above because that's what we're going to be using for farthest and so when you know we're starting here we're starting at index 0 right and we're going to go from index 0 plus 2 all the way to index 0 plus 3 the way i'm getting these is basically from our minimum and maximum jump right because we know that's what the next layer of our breadth first search is going to look like right 0 plus 2 all the way to 0 plus three right these positions right and when you look at the indices two and three it does match up with what we have here so this is our next layer now let's look at the first index right so this is index two it's a zero so therefore we are allowed to jump from here where are we gonna jump to we're gonna jump from index two right plus the minimum jump of two all the way to index two plus the max jump that we can do which is three right so we're gonna basically go from here to index four and index five right so that's going to be our next layer oh and by the way i forgot to mention but before we even jump to this next layer since we've reached this layer already what we can say is the farthest index we've reached now is three so instead of zero we can say it's three right this is basically the farthest we have reached so far and so since the next positions we're trying to reach you can see two plus two is four and two plus three is five and since these are brand new positions right these positions are greater than the farthest we've reached so far right so technically yes we are going to add these positions as well to our queue okay so now that we have reached these positions let's take a look at the new farthest that we've reached right we can clearly see that so far we have reached index five now since these are ones we're not actually going to be jumping from them but we do want to remember that we have reached all the way to index five so now the farthest we have reached so far is actually index five and so by the way we've already jumped from this position now we're trying to jump from this last position of this layer so we know that this is index three right so three plus the minimum jump of two is where we're going to be jumping to plus as well as three plus the max jump which is three so we're going to be jumping to index five all the way to index six right so from here you can say that we're jumping to index five and index six but wait a minute we can clearly see we've already reached index five right so in reality we want to actually skip this right so when we say we're going to be jumping to index 5 and to index 6 we actually want to say we actually want to start at farthest plus 1. so you know instead of having this as being a five i want this to be five plus one because the farthest we've reached so far is five we wanna skip five so we wanna start at five plus one which is six right so really what we're saying is we're only going to be jumping to index six so notice how we had a five here nope that's going to be a six this is a six as well so really we're only from this index three we're only jumping to index six because that's the only addition that we can add right so and once we've done that we can also update our farthest reached to six and we can say okay we have visited this value now right basically we don't want to be adding this sa this index 5 to our q twice and we don't even want to be looking at it twice we don't even want to look at what value it happens to be there twice and so at this point you can see we're going to have three values in our queue right three indexes in our queue and yes we're always going to be doing them from left to right basically first then first out just like you know a q normally would be so we're gonna have index indices four five and six we're gonna look at four well it happens to be a one so we can't jump from there look at five it happens to be a one we can't jump from there look it's six it happens to be a one we can't jump from there at this point everything in our queue is going to be empty right where we have popped everything but we still were not able to reach the last index and we have nothing left in our queue so we have no choice but to return false so i think you probably do know how to do a breath first search on this array i think the main trick that most people will have forgotten about is to maintain the farthest that we've reached so far to eliminate the repeated work to get this problem to be a linear time solution as well as linear memory solution that being said let's jump into the code i bet you probably already know how to do it now though so as i mentioned we're going to be having a queue which in python is going to be a deck and we're going to be maintaining the farthest value so that deck is initialized with a single value and that's going to be a 0 because that's going to be the starting position for us and the farthest reached is also going to be 0 initially and we're just going to continue to we're going to continue to make jumps until our q is empty if our q is not empty we're gonna pop from it so q dot pop left let's get that index that we have popped we know we're gonna be jumping from i we're gonna be jumping to values right what's the first value we're gonna be jumping to well of course it's going to be i plus the minimum jump right that's the closest value we can jump to but what happens if i plus min jump is something that we've already jumped to then we would want to skip it wouldn't we that's where our farthest comes in we're always the first jump we're gonna make is always going to have to be a new jump we can guarantee it's a new jump by taking the maximum of this as well as maximum of farthest plus one because farthest is a point that we've already reached a new point would be farthest plus one and so we're just going to be iterating through all the possible jumps that we could make from starting at this index i so j in range from the start that we just calculated all the way until the end now what's the end going to be well it would be i plus max jump right but what happens if this i plus max jump is out of bounds so it's possible it could be out of bounds right so what we're going to do to make sure it's not out of bounds is we're going to take this and take the minimum of this as well as the length of s and actually to this we are gonna add a plus one the reason being in python basically the end range is always non-inclusive so in python the always non-inclusive so in python the always non-inclusive so in python the ending index is always non-inclusive which is index is always non-inclusive which is index is always non-inclusive which is why we're adding this plus one to it because we definitely do want to jump to i plus max jump so to make sure we do we're just adding a plus one we're going to be jumping to these positions so we do want to check if that position so s of j if this is the character 0 only then are we going to be adding to our q so if it is then we're going to add to our q that index j what we're saying is that index j can be reached therefore we're adding it to our q now what happens if index j happens to be the goal that we're trying to reach in that case then we can just immediately return true right so if j equals length of s minus 1 that's the last index right if that happens to be the case then we return true immediately if not then we continue now don't forget after all this is said and done we do want to update our farthest reached which is basically just going to be i plus the max jump and if we never end up adding the last index to our queue that means we'll never be then we that means we never reached the last index and if our entire loop executed and we still didn't then we have no choice but to return false so that is the entire code as you can see it does work it doesn't seem like it's super efficient but it is a linear time solution and linear memory solution so i hope that 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 | Jump Game VI | strange-printer-ii | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104` | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? | Array,Graph,Topological Sort,Matrix | Hard | 664 |
523 | hey guys how's everything going this is Jay sir who is not the good algorithms I'm making these videos to prepare my interview next month in this video I'm going to take a look at five to three continuous uh barista or given a list I'm not negative it might be zero but a members and a target integer okay it might be - write a function to okay it might be - write a function to okay it might be - write a function to check if the array has a continuous abre of size at least - that sums up to a of size at least - that sums up to a of size at least - that sums up to a multiple of K that is sums up to n by K where n is also an integer maybe zero in might be - so that's something like this might be - so that's something like this might be - so that's something like this we're giving to search for target six because - for sums up to six okay for because - for sums up to six okay for because - for sums up to six okay for this array all of them sums up to 42 it's 6 by 7 so it's also we need to return - well the first ideas come to return - well the first ideas come to return - well the first ideas come to mind is to do multiple why do I see multiple a bhoot force right so how many sub arrays are there if we pick a starting X and n in X there will be and square right and then we need to calculate the sum right so they will be x + so it's actually it's an will be x + so it's actually it's an will be x + so it's actually it's an cubic space there is nothing space and nothing used so it's constant so obviously cubic is not good we need to improve right one thing is that if we freeze a starting next like 23 when we are loop choosing we can do we can fix this starting X and choose all the possible ending XY 2 4 6 7 & 4 that possible ending XY 2 4 6 7 & 4 that possible ending XY 2 4 6 7 & 4 that actually for the Sun we can cash the sum of a previous calculation like we catched we cash the sum of 23 + 2 and we catched we cash the sum of 23 + 2 and we catched we cash the sum of 23 + 2 and then we can just + once to get the sum then we can just + once to get the sum then we can just + once to get the sum at 4 right + 1 - 6 + f7 at 4 right + 1 - 6 + f7 at 4 right + 1 - 6 + f7 actually we could improve to and square right without the final the big extra end we're getting it in index of an index and we're getting a sum at the same time so this might be good let's first try to improve this one okay yeah so the idea is very simple we first choose the start index which will start from zero to thumbs because at least to write we start and end here sum is equal zero if some divided by k might be zero remember so we need to if K equals zero and some equals 0 return true for the Oh No whoa check if sum equals zero we return true when K is not 0 if mod it equals zero we return true right aha so actually the problem becomes we can just if k week we set it to zero we get mod right it ma equals k zero then it's um it's off if not it's this right and then we say if mod e equals 0 return true we can remove all this and then finally return false so this should work yeah yes I meant what's wrong some mod K if not equal zero it's true so for zero we start with one that's right it's not easy it's not and then one I'm stupid should be Muslims I cool were accepted and Kui couldn't be include this I tried to improve it okay I remember was that we're doing with any question it's about getting also getting a summer a something from array the idea is that if we want to calculate the sum of a sub array rather than we sum them up one by one the other case is that we can cache the result like sound this and then just to do the subtraction right if we can sum here the sum here equals the sum of this array minus the sum of this array right so that's give us the hint if we can improve by improved by that and at the same time we're gonna check the if the sum equals to the multiple of K let's analyze the input like this actually for the Sun we could just mod the K right it doesn't change the result like you are giving the if we divided by six beforehand it's actually is the same as the input of five to four zero or one right remember that the subtraction we mentioned if we calculate the sum of like two is four of the Sun the sum is the MA is the multiple of K then if we modded by K it must be zero right so the summer here the mod some of the sub-array must be zero so reminds us the sub-array must be zero so reminds us the sub-array must be zero so reminds us that if we accumulate the sum then there must be a substitute right let's try to some them up this is the model array then the sum from 0 from the start to here would be 5 and here will be 7 right seven mod 7 ma 6 is this one right and then here it's 5 again we see we made a 5 it means the numbers here actually sums to the multiple of K right because these mods are the same well this is idea let's try to do it so we need we're needing we're getting the mod array right and a check if it exists or not to check the if take to check the existence we could use search but we could use a map to do it quickly more quickly right and we need to check it at least to 2 so we need to also store the index so it's a map passed mods new map its MA map mod index okay blah let's start there's some equals zero mmm cool now of course first with some of the lumps right some number and then we check if the sum has is already in the mods map right if it is we check the index if it's so - at it's we check the index if it's so - at it's we check the index if it's so - at it's evidence - if it's - what if it's two evidence - if it's - what if it's two evidence - if it's - what if it's two one - so see this the index is 2 before one - so see this the index is 2 before one - so see this the index is 2 before to slot before then it is valid okay so let's see if not oh the Sun it might be over that it might be over k we need to check it right if it is zero we do nothing right if it is not zero we steep muddy okay and then if mod has the sum and what if should we update the index no we should not update index so if there is the same but instance is just one before then like this for and this is what is zero then they have the same mod should updating XA here no because we're getting at least two so the far the better father the better so you've has it doesn't have this at it if it is not in the map we will update it right set some I if it is in the map we get check the index if mods get some more than I minus one then we'll return true and the for loop is done we return the force right let's try to run code yay my answer in please double zero because for 0 the sum is 0 okay is 0 so we don't do it - nothing okay is 0 so we don't do it - nothing okay is 0 so we don't do it - nothing mod well 0 it has a both are has a sum 0 but index is only one slot up before so we didn't return true well but obviously this is the true case how do we should we do it if we suppose that there is a false head at the beginning it will make things better right if we add a force zero and 4k is not a zero the zero would not harm right why let's suppose that there is a sub array sum to a specific K which is not a zero then if there is it if the zero is in the middle it should be included but if it is the head it should be avoided right if you will not be a be counted because the son array like this only change when the number is not zero so if even if we add a zero it doesn't matter or it is another way we check this we can say there's a special case of all 0 so if sound is zero if sum is zero like if is six the Sun is all the Sun is zero right sum is zero and then so the some will not if some equals zero and the K is not zero and it there must be it must be to zero or it's sum up for some up to sum up to that number right yeah 22 for the sum would be to zero right okay this is a valid case actually so if this is that if the FIR ah I see if the top the first two like four three first several numbers sum up to the multiple of K then there will be actually 0 the first zero occur so actually if we say mods get some smaller than I minus one we could just add a force zero here right yeah I say mod set zero minus 1 suppose there's a zero at the beginning it will handle this case very well and if not big if not the case like this it's like 2 4 + 2 not the case like this it's like 2 4 + 2 not the case like this it's like 2 4 + 2 3 and then 1 5 you'll see that it will be 5 0 and 5 so it still doesn't matter right so we add a 0 here let's try to submit loads is not defined oh not cool we are accepted and or I think if for this for the rather than we set a false hat we could check if this is the first 0 and this index is bigger and this index is speaking at 1 if the first one is 0 then actually if we forgot by the men some must to 0 actually will be a valid result the only invited one will be only 1 0 right so if not handsome or some equals 0 and is that bigger than 0 this will also I think this will also work no hmm ready so the sum 0 okay and I a speaker than 0 right ah oh no my bad add a special case here if this returned true this should also satisfy our needs yeah this is the same cool special case of excluding okay if sum is zero then all are 0 only invalid cases 1 0 so we feel like this one case out let's try to analyze the time and space complexity for time we using one for loop and yeah that's it so very good it's linear time space we use a map to store the Sun right actually worst case is um K equals zero and the last two numbers being zero right for that case we need to store all the sudden lump all the sums so the worst case is yeah in here for but generally if K is not a 0 if K is not 0 it should be in K minus 1 if K is not 0 right because we mod it cool that's all for this problem hope it helps see you next time bye | Continuous Subarray Sum | continuous-subarray-sum | Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1` | null | Array,Hash Table,Math,Prefix Sum | Medium | 560,2119,2240 |
315 | What happened if this welcome to back run loot soiled note problem counter small numbers after sales do subscribe like and share the video key notification for future videos a suddhen kuch nahi job type hot and say that your ribbon in danger in that and you how to Return New Account Are Lakhan Terrace The Property Where Contai Is The Number Of Moral Me To The Height Of My Electricity Board Wanted That Point Is Element Me To Find All The Element On The Right Hand Side Business Model Dangerous Element 5825 Vs In A Limited Knowledge And Right hand side and 130 element with right hand side saw its 0ur ab soayenge is particular that this and night solution will be fair using back to rooms and water drop mixture root divert element and kinnar lutu i plus one till the last element and will just compare In this life it's modern basically we increase the counter is a but this solution is more time complexity of mode of square which will be slow and also like sharing in list is difficult to submit there feelings at will feel with time limit sirvi so let's See How They Can Tackle 20 Problems in Interview Scenario and How They Can Think About to Get the Correct Algorithm and Scheduled Tribes Candidates Are Suffering Due To Deficiency Disease Elements 102 Show Me to Get Smaller Element Inside Right Hand Side Vishnu Five Words Right Five Fridays Compare 5252 Element With This Seems Like A Great Mood With Element Right Side End Events Can We Do Something Like This And Will Look Like This Point To 56 What Happened Here But After Starting And You Will Be Amazed I Stood There Seems Like 512 MB Element And Correct Position in the director of key setting to support to reserve one element and tourists correct position in the short direct 15601 Limit and tricks correct position in the short and elements in solidarity for 18518 number one day match 252 right championship-2013 element of oo right championship-2013 element of oo right championship-2013 element of oo tomorrow morning Bhi Vikalp Come Up With Anil Gautam Which Will Do Something Like This Is It Means Vriksha Simple Hai That Surya Vihar Bane Are Of Elementary 532 6 And One Should Opt For This Is For 5-day 6 And One Should Opt For This Is For 5-day 6 And One Should Opt For This Is For 5-day Night Element Right Hand Side Curved 2 And Soon And Awards Returns The index of switch of this basically index of five original index 501 electronic to two and so on the effigy apply shot mode on this particular is what happens to see what happens when will be split into two drops of support 506 b 323 and dissolve In to-do support 506 b 323 and dissolve In to-do support 506 b 323 and dissolve In to-do list into individual 6 2 and logic will decide march 2017 right side is done sleep pcb is particular reconsideration battery 19 this point surya bbc.in energy 5135 vs correct position bbc.in energy 5135 vs correct position bbc.in energy 5135 vs correct position in english 105 number element in the right hand side 53132 right Hand Side Is Hair 6060 Android Final Stage And Will Give With To Like To 16 2012 Original Position On That Uske Kheer Paise Distance 6S 102 Raj 1010 Jump Andar Right Hand Side Hai Mein Nine Movies This To Are 315 126 Days What Will Happen First One Will come into its position and will come into its position and 102 days just once which was previously on the day three will come into picture hai a sudhen civil jab amazon students Bigg Boss-3 and one and to go din five already Boss-3 and one and to go din five already Boss-3 and one and to go din five already hai dose sweetness Cross 3 End Cattle Class One End 245 Basically Two Kayak That Sea Right Hand Side End This Will Come From The Right Directly Morning Butterfly Specific Pattern Agree Time From Left To Right Something Is Most Mist To Take Date Minimum Tweet One Is Time When Number Of Element Which were deported from the writer and physically in this particular 14322 steps to correct position on 2015 odds to log in coming from left side suite already jump 360 sweetheart 2012 lutyens notes23 james and 6pm to right side should not any extra while we sleep jump and triveni Coast Wave Championship 100 Number Four 600 800 Photo Bihar Awal Pooja-Path Pimple Like And Also Pooja-Path Pimple Like And Also Pooja-Path Pimple Like And Also Expected Cut Off The Question On That New Ten Second Thing Is Pay Note Successful Others Like One Two Three Four Wickets And Others Neetu Return And Result Inter SIM Order In Which The Amazing Events Like The First Position Will Be We Cannot Answer Like 2012 301 Marriage To Answer Like 3210 04 2015 2016 Final Key Airport Se Intact Will Be Fool 2513 0316 Try To Right Left Side Implement This Logic And Shifted The Correct Answer Create The result is below the list stopping by adding a new art lace and fruits the result is I will eat become global variable account which aims to our account feature process drop account hours the number flight saffron light jump for each of the element's bodice Sila is contest new in do kar do now we start length that and believe they are to soravar index loot qualit original intx ki special peeth according to top one is kar do a look and willing to assign value photo original intact school se ipl 2018 sandalwood Start a i link tha plus point r ko ulti nahi index of ic code to i have 500 index life events of the existing are super but particular is 12345 despite delhi cantt previous go for shopping for hindi short milk pass names are in power a Have and is channel intake that and they will pass the starting point conduct bond and right from its or length - bond and right from its or length - bond and right from its or length - one who and where the result will be in this country are willing to convert in last point is a that i plus city with Pimple Thoughts That Would Suit With Me To Write The Short Function's Shot Will Be Selected To The Short And Functions Of Pride For Warmth 100% Twitter Account Number One Thing From Left To Right Side The Light a MP3 Ringtone Of This Intex Clear Getting benefits and enterprise hai ki a computer ka atishay 10th ki hindustan right tennis career on pimple plus right loot ki awadhi so seekers with flower shopping ho loot are o kar do ko switch request whatsapp image 2 minutes kar do main tenu rikat 2070 right side special Treatment plus one here half much for the laptop compound pass lunar day and night only will be such vitamin kind much function very fun feel low do a sumo bill okay to connect with loop bandhe loot wali do tomorrow morning 430 Some days and basically sugar to that is the size of power lifter points serial yeh rishta is absolutely two minus loot one can get right side meanwhile is right - net and wicket lootere meanwhile is right - net and wicket lootere meanwhile is right - net and wicket lootere now all these things new of intent of this is a doing Create and right are popular in two, it has happened that the above lines were ready with 30 minutes popularity electronic was 200 Om Vipal Dhoop Si Road and place is photo gallery at first site Faisla Plating and left and right very sweet dreams will play with the end Off the number is the original value The mode is switched on to succeed The original You will need a to and the journey to succeed The index of all the numbers middleing the original print and electronic and the left key light Bill is a loot place in the back right are And Film Co From I Plus B Plus One Quarter Right Side Is A Ruk Su Chi For Trading Displacement Letter Android All Next Chest Last 500 Pimple To Bill Sexual Through Witch To The Point Witch Will Hear Something Right The Counter Witch Will Right Hand Side Is Loot File IF Bus Stand Collector Size Hai Hua Ki End Cheese Listens To Right 0 MP3 Se Puck And Tissue Speed Start Matching Se Puck And Tissue Speed Start Matching Se Puck And Tissue Speed Start Matching No This Is The Date Vihar To The Number Of Secure Champion Basically Normal Merge Sort Situation Thursday Like It Is the right side basically oppo light to turn on the number to the comparison with something like this is which will give me the number and left there will give me the point to that is not left side second position of it and then suddenly equal to You are right side se right here and share this mins that right side are this etc last days right hand side left side 12512 six numbers are basically a in which police is present this number is batter pressure tire point interpreter cancel Africa continent should be in the right Hand side with right hand side is the question paper for morning in that particular case with just one number and the counter currently not jumping in morning Dussehra's original intake of ki lift teri of I will also find the value of I in this Video Tablet Was Proud Of U That Anjana Can Find That Other Wise That If 22 President S One Vihar The Left Hand Side Value Of Birth Gender Right Hand Side Saugandh Right Hand Side Basically Choice 595 Compare To 65 This Model Number To I Need To Jump into a loot channel account off costing rs of ship that and sing sir chapter note came or birth problems right counter increase will increase the right increase the day in this year will come under increase the valley of my that and listen clear All set to and pet collector and right here and win in to-do list condition verify something from the and right here and win in to-do list condition verify something from the and right here and win in to-do list condition verify something from the right side of something on the left side early morning something is left on the left here something is left on the left here something is left on the left here in a key facility dust hut special you A vo blue chips plus ki aisi age ko support thing stand festival MP3 ki sui das particular ki a ki film hua hai looteri cheet Ajay Devgan thing first class and kill plus app kal su police officer par strike rate and si ki loot box par so This attitude of extra and sea has duplicate number 40 - sea has duplicate number 40 - sea has duplicate number 40 - 50 - pants on a sweet kitni kar translate into submitted a ki ukta koi life aap mil sake 200 250 1MB saugandh repeat compare this with a difference koi solution into a beginner very long time and misses Pet Solution to Difficult Problem Thanks for Watching the Video Welcome Back Ball Group Computer Programming Questions on | Count of Smaller Numbers After Self | count-of-smaller-numbers-after-self | Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104` | null | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | 327,406,493,1482,2280 |
290 | Everyone Welcome to Difficult Silent Test Questions Board Pattern Alerts Frequently Benefit and Spring Dale Senior Scientific Air Pollution Patton Hair Fall Means Fool Maths David Warner Letter Important Alone in This World Spring Boot Depression subscribe Video give subscribe diy ocean now half losp. net it's too time of doom possibilities of fact that is not possible for subscribe do subscribe to the film has lived a slideshow 300 spartan debit to 100MB at 4 inch and app but free example sir which will help you vote solution for yourself thank you Need To Go Beyond Your Own This Point Video Consider Logic Solidification Incomplete Subscribe Being And Dogs Dog Show That Coma String And You Will Hydrate Pure Map Are You Traitors Rings Patton And What Is Character One World Should Fight Against One A Games To Check The Current President subscribe to the Page if you liked The Video then subscribe to subscribe Video subscribe The Channel That Is Dog Portal Or Exist Even Attempts To Gain Swift Industries Complete And I Don't Know Less Time Busy 501 You To-Do List And In Turn Will Give You a Look at These 108 Names of Dog in the Third Cases Pet Dog and Vs Again Being Attempted to Be Mapped Dog Already Has Been Used in the Best Country Subscribe to a We Can't Used Ones Saw This One to One Pinch Between 20 2013 Near Kidnapping Sanwarlu Saunf Do You Want To Talk To Do Subscribe By Pressing The Subscribe To That And Distant Significance All The Volume Darwin Said Bigg Boss Student You Don't Give But How Can Also Recited With Algorithm Tiffin Counted But It's Already Present In The Map Qualities In The Map Turn Off Handsfree Mode Switch Board The Subscribe Way Request All Due To These Decades Readers You Need To Take Care And Check This Effect New Key For Updating In Turn Off The Current String Value Has Never Been Used In The Past Fuel Directions Values were reduced to this information you stole the information and Values were reduced to this information you stole the information and Values were reduced to this information you stole the information and set this will keep track of all the Malaviya Darwin user interface tiffin under user password enter process and other wise of new updates the map and its soul is highly recommended you at right to good by your Specific issues beyond this video were defining measure of formal tank must bring a politician of new hospital that Ashwin of that defining set for springs service to the child use and has been used in the past absolutely set new heights that aunty limited spring has been displeased by Your past by yatish aloo serving plate mein sthala 200 swing are spring wali juice a request oo sstr dot in the body was separated by space and bond or no case of women in the algorithm if value support length is not equal to part in the bab. la that Typing Bodoland Benefits Application Forms for Example and Special Recipes Part-2 Touch Liquid Subscribe Soil is not Part-2 Touch Liquid Subscribe Soil is not Part-2 Touch Liquid Subscribe Soil is not possible to take new media site for the Patan and IGNOU Airport Sincere in T20 is done in this that I plus that these points Paint fighting and china ₹10 these points Paint fighting and china ₹10 these points Paint fighting and china ₹10 character ki tractor loot 48 aaye what ki tractor loot 48 aaye what ki tractor loot 48 aaye what is the bollywood current wali best friend the current bal a spear bal images for less tasty arbaaz ji a question tr balu us ki get some guidance and this name don't The content is that the list of passing was already content that cigarette is a string value from that I am biscuit b that a lion is Bollywood so s to existing live that this note is equal to daughters how to the current affair wali current wali Please get the notice or office phone calls that 22 Aaj Duba Lider River Ki Jo Notification Dam Of Death Penalty West E Will Update The Arvind Set This Post Tagged With The Bollywood Actress In Do Set Kar Note This Painting SPR Volume 800 Bollywood In Return for all otherwise se dot s volume settings us that and updating all cases hotspot ki coma spr wale ki this dispute language and complete length half episode video return from her and lemon juice tribes code of a rule at this time tud a good paste bye Entries Logic Once Mode Switch Off Freedom of Characters and Spring Vestige Character Point to Single Program The Pattern Distic in Through a Particular Ras Principal Predicate subscribe and subscribe the Channel Please subscribe Abhi News Underpass Episode 325 Subscribe And New Updates Reviews and News Time Complexity of the Length Subscribe to the button on the button | 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 |
202 | hello friends in this video we will see lead code problem number 202 and it's called happy number so why is it called happy number i don't know but the concept of happy number or rather it's called be happy number where b denotes the base of the number and we are generally concerned with base 10 so in our case we are concerned with n happy number or we will simply call it happy number so let's take an example let's say we have 19 again in base 10 so if we do the square of its digits so what we have to do at each step we will replace the number with the square of sum of its digits this the sum of squares of its digits in this case it's two digit number it can be more digits also so 19 becomes 81 plus 1 that is 82 then we move to 64 plus 4 or 68 then 36 plus 64 which is 100 and this is 1 plus 0 so it becomes 1 so whenever you reach 1 then we will declare this number to be happy number the original number uh but this will not be always the case because sometimes you may keep looping and keep reaching to this same number and once you reach a certain number uh you and you have reached you took the square you reached here then you reached some other number and you reach again a number which you have already seen let's say we reached here after certain calculations and we reached uh let's say 25 so sum of 25 you if you do the square and sum it will become 29 then uh it's 81 plus 4 it's 85 then 64 plus 25 is 89 and then it becomes 72 plus 81 which is 153 then it becomes 25 plus 9 plus 1 which is 35 then it's 25 plus 9 which is 34 and it's 9 16 which is 25 so you reach once you reach 25 you are guaranteed to move to 29 and again 85 and this will keep repeating and you will never reach one so if you reach a number which you have already seen then you will declare this number to be uh unhappy or sad number or not a happy number and another condition is that it should be natural number so it should be greater than zero negative numbers are not natural numbers neither is zero and uh let's just take an example of another base although we will be solving for base 10 only let's say we have number 6 and again in base 10 so if you do the square of 6 it becomes 36 then it becomes 36 plus 9 which is 45 then 25 plus 16 is 41 then it becomes 17 then 49 plus 1 is 50 then 25 plus 0 is 25 which we have already seen as an example so after 25 it will reach there and again it will reach 25 so 6 is not a 10 happy number that is in base 10 but you if you look at 6 in base 6 then its representation will be 1 0 in base 6 because it's 0 times 6 raised to the power 0 so 0 plus 1 times 6 raised to the power 1 so which is 6 and if you do the square of digit it becomes 1 plus 0 equal to 1 so this is denoted by p and this is already we have seen b so p we will take at 2 always and this was just for your information purpose in this video we will be solving for base n only so let's look at the lead code problem now so here it again says starting with any positive integer because it's true for natural numbers only and it's the same example of 19 so first solution is very simple it may remind you of solving the loop in linked list problem so one way is to keep the keys in a map and you start traversing the list and once you reach a key which you have already listed that it's in the map or the set then you will declare that there is loop in the list here also we will do similar thing we will keep storing the sums into a set as set and calculate move to the next number and we will again check if this number is present in the asset or not if it's present we will return false and if it's not present we will insert it into the map and additionally we will also be checking if we have reached one or not and then the second approach of finding loop in the linked list was that we have two pointers one slow and one first so here we will have two numbers one slow sum and one first sum so in slow sum we will calculate the sum of squares of digits of this number and in next iteration whatever is the value of this slosum we will again calculate sum of a squares of this and for first sum we will we have to move by two steps so we will do sum of squares and sum of squares of this f so this f denotes the first sum so we do it twice it's like moving next in the linked list so let's see both of these solutions one by one so the first condition that we need to check is that if a num is less than 0 then we have to return false so if n is less than equal to zero return false no processing required and we also need a function to calculate the sum of squares so we will pick the last digit do the square of it up and add to the sum and divide it by 10. so while num is there now we will write our main function so we need one asset unordered set so find returns an iterator so if it finds a given number in the set it returns iterator to that position if it doesn't it will return and iterator so if it reaches n that means this is not present in the set and this loop will continue until it's a fresh number so this loop will terminate when either at any stage some of the squares become 1 when we return 2 or we reach we start iterating in a loop so in that case this will find it in the cache so in that case we will return false let's run it on our case so for 19 it's true for negative it will obviously return false and that should be also expected from the problem definition of lead code because it also says starting with any positive integer so it's correct so let's take one negative example which was 6 in our case it's correct so we can go ahead and submit it so it says better than 58.5 so it says better than 58.5 so it says better than 58.5 let's try a couple of times so in this case it's not varying generally i have seen this number vary a bit when you do multiple submissions okay so it's adamantly stuck at this value let's write the other solution which is finding just like finding loop in the linked list this is also finding loop in the linked list but here we are using additional space here we will not use space so this condition remains the same then we can get rid of this slow sum is number itself first sum equal to sum of squares of this so we make them unequal it can become equal only if n is 1 in that case because square of 1 is 1 0 we have already eliminated square of 0 is 0 and square of minus 1 is my plus 1 so this is true for just one negative numbers are not there so these will be equal only when n is one so let's check we can add a check here itself if n equal to 1 return 1 or it will work here as well so maybe it becomes one in the very first stage then our first sum will become one now we need to run the loop so we are moving this by two steps and then we need to check this condition and finally return false it works for 6 let's try 19. again it works obviously it will work for zero and negative because we are returning here itself so we can go ahead and submit it this is our second solution and luckily this gives hundred percent better than c plus and that than in terms of timing and also in terms of space so i hope you enjoyed both the solution especially the second one because we got some memories of finding loop in the linked list using slow and fast pointers thank you | Happy Number | happy-number | Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1` | null | Hash Table,Math,Two Pointers | Easy | 141,258,263,2076 |
171 | uh hey everybody this is larry uh this is me doing day 10 of the august dairy challenge uh let's get right to it uh hit the like button into the subscriber and join me on discord uh excel sheet column number given a column title as up appear in a sales sheet returns corresponding card number okay that seems to make sense um and it's only up to seven anyway uh yeah so this seems like a base i want to say like a almost like a base 26 uh or base 27 number um or just a base 26 number maybe yeah so that should be pretty straight for oh you have to go the other way for some reason i thought it was fun from column for number to the column uh but yeah but i mean i think you could figure out this formula by doing it converting it to a base 20 uh 26 number uh by and there are a couple of ways you can and handle this with the base 26 um now you just have to make sure that uh you handled off by one correctly or something like that uh so i yeah i think we could probably go for it let's play around that so basically we want the ordinal value minus the ordinal value uh capital a plus one two because we start at one maybe uh it's base 26 and then we return count plus one maybe something like that uh and for me to be honest uh wait and maybe this is not the best way for interviews to be honest but the way that i usually do these is that i have a formula that i'm confident about uh but it may be off by one so i like just kind of see where i'm off by and then calculate from that um okay that's interesting oh so okay so actually we do want this one here um and then oh yeah then we don't need this one here um but i think for this um so i mean i'm going to submit it should be okay and this is uh linear time in terms of the number of uh characters in the string um yeah so the way that i usually think about this to be honest it's just a little bit of a pattern matching and just going through it uh in this case you know that every character will be um yeah it's a it's just a lot of ways to be honest it's a little bit of an experience and it's just practice and i've recognized this and when you see like um every digit adds 26 or a multiple of 26 so you know there's gonna be some variation of the base 26. uh this is a little bit weird in that yeah you need to add one here um so the math on this is a little bit trickier but you know as long as you could show it should be okay uh between a and this thing okay fine but uh but yeah let me know what you think let me know if there's any part of ambiguity and i could answer it because i think this one is just um for me anyway or intuition or slash or practice or intuition from practice and recognizing the pattern so yeah uh let me know what you think and i will see y'all tomorrow bye | Excel Sheet Column Number | excel-sheet-column-number | Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`. | null | Math,String | Easy | 168,2304 |
376 | 28 Welcome to Take Good Bye Nivedita Ants Video We are going to solve Dil Subsequence So given in this problem statement that here you have been given a puzzle and it has been said that you have to find Dil Length of the Longest Vikal Subsequence of the Names So We are all fine, it's new, it's fine and this is the will sequence, here we have given you an option, sequence, pure sequence, more difference between two successive numbers, stick click, alternates between positive and negative, so the address given to you, now none in What will you do about it, now you will do the difference side of the elements, okay when you do the front side, now you will object here whether the positive number is 191, then there is positive and negative, friend, negative and positive and negative 50th In this case, if any cancer is forming then it is Bigg Boss equal. OK, in such a situation, you can increase the total length by how much maximum length longest option sequence? Now sir what happened in the sequence? What can happen? After the difference, you again get a positive difference. After the modern A difference, again you get a requested. If there is a difference, what to do in that condition, we will skip the element, we will not consider this element in the sequence, despite this, how much of your longus can become the paste, now we have to see the school and finalize it, so let's give an example of both the legs. Let us understand the problem and then we will come to the solution. Okay, so first you will see the difference. Finalize it. Okay, the difference is, you are the six of seven, then the serial of 47 is the five of 30394 and the serial of 2729 is the five of 0522. Okay, then see if it is positive, then the native of the relationship is measured, negative, then positive, that is, all the elements have made a sequence where your difference is first in equity opportunities first, either negative personality, positive negative, if positive had come, then your visual sequence would have been a silent. We are setting up a party from Total Animals How much is your education Answer Untrained Now you will see only in the exam The difference between these two is either positive or negative Okay, so both of them will not make you participate Let's just look at the next two elements in making For three four, this is its difference rice for - 3121 is positive, it does for - 3121 is positive, it does for - 3121 is positive, it does not have element T otherwise we will see for negative corporation whether it has come or not, so I have to make both these numbers so here two is your answer ok now for this you have to Here's your caffeine, here's your - 12th, here's your - 12th, here's your - 12th, here's air, five, and here's your real, here you have two, here's your - side, here's your - side, here's your - side, here's your I square here, glue here, six, okay, posted but subscribe. Do this but like I did here first do this then we need but we turn on the gas again so we got it here we do different if we do it - different if we do it - different if we do it - play the song again 1111 we got only a quarter of an inch set the friction party or Then after this we will see that the difference between these two is set - will see that the difference between these two is set - will see that the difference between these two is set - 8. Was it positive in the first one, did it get a wicket or not? How many elements are participating in this sequence? 1234 What are you doing after 4? 5 6 7 Okay, the total is 737 up. The answer is now let's come to the code how to do it Hmm I have a resolution mother how will be Bhim's swine flu solution Mamta will see how the son did so here we are going to take the final decision take care of a previous difference or ok 11th April difference Haryana What is Candy Crush in Ka or Me? One is the total for you, that is for the other by one post, you will see that if you have found negative then do it on less than the Prevent one, not if we have found positive then subscribe the page by commenting the total and also taking it with you. Let's keep on making this sequence back then you will get the difference continuously, subscribe, so here we will keep updating the total, when both will do it together, when both will make the total payment, then first we will do the difference that these two This difference in the first wash will be the fight difference. Okay, so we will check it. Is this our zero? Is it not coming? If zero is coming, then we will update its descent. If it is not coming, this is a reminder of the second stomach. Do this, let's do this, ask and update because both are taken first, the one who does n't come, what will we do after that, now if we file the difference of both, then 5th - 17th will come, file the difference of both, then 5th - 17th will come, file the difference of both, then 5th - 17th will come, now your Candy Crush will be - 12th, what is the prevent difference for this? - 12th, what is the prevent difference for this? - 12th, what is the prevent difference for this? This will be the 16th. Okay, for this, use training. We will see the best result. Opposites of both of them are that in 16.3, recognize Sai that in 16.3, recognize Sai that in 16.3, recognize Sai Vrat, by inviting increment crores here, let us come to the next element. Okay, we will see the difference between these two. The difference of that your five is 5ghz of that current prevent which will be second, what will be the effort for it, in the environment which is your paint, what cant happen for it, then - for the twist, then - for the twist, then - for the twist, we will see the ka or previous account, its file is fine, let's We will look at both of them, if both are opposite, then we will increment it. Okay, now what will we do, what will be this five, will it be the previous for this, will we calculate the difference for Yagya, then we will see whether this is your free difference or that difference is free. Earlier there was Sun, that too was your positive, this is also a festival, so we will not maintain it, we will move ahead, okay, it will not do increment, we will move ahead, OK, after that, what is yours, you will differentiate between these two, if you differentiate between these two, then it will be 403 many. Thirteen 's tattoo will come out, the first half cup review is that 's tattoo will come out, the first half cup review is that 's tattoo will come out, the first half cup review is that side, okay, five will remain there, your woe is going to come there, we did not go inside the update, what is yours, this is your negative, you did not find it here, that is how we do ours. Find it, we will keep it water, what will we do after this, keep five, now let's see the difference between both, let's see again what or this you have turned out to be 2152, if both are positive then you will keep it, you will move ahead for fiber privacy or now see, if you point out the difference between both, then only the difference will be defamed - File That difference will come out then only the difference will be defamed - File That difference will come out then only the difference will be defamed - File That difference will come out - Water has gone out, both of them are - Water has gone out, both of them are - Water has gone out, both of them are opposite to you, now what will we do, will we increment and - Side scrub, what will happen then it will come and - Side scrub, what will happen then it will come and - Side scrub, what will happen then it will come out, now we will point the difference of both of them, now we will see where is the difference of both - Sahiba - 5m, if both are negative then - Sahiba - 5m, if both are negative then - Sahiba - 5m, if both are negative then What will we do? Will we leave the remedies? Will we take the measures forward? Will we increment further? Will we move ahead? Here we have come - York will freeze, now both will be left, but if you mix them, then you will move ahead? Here we have come - York will freeze, now both will be left, but if you mix them, then you will move ahead? Here we have come - York will freeze, now both will be left, but if you mix them, then you will get this lemon, send it to your palace - Fiber, get this lemon, send it to your palace - Fiber, get this lemon, send it to your palace - Fiber, both are opposite, that is, increment the score, then aloe vera juice. Now we will take out a difference march between these two, the robbers will come out of you, slow down the school so that what will go to you, if the intake is done, then you will calculate the total and centralize it here, we will check the balance on the man-eater part, what is the centralize it here, we will check the balance on the man-eater part, what is the centralize it here, we will check the balance on the man-eater part, what is the end and what is the end. Is there a moist size here or not? This person's size is Scorpio. Do the oven. If there is an element, then what to check. There is a tight answer for that. We will discharge. Then we will enter the difference point. The first one is the man's okay. Total. We have taken the element in inches, this will remain zero, first of all we will check that you have posted the reverse difference here, if that is also there, then there is no employment, the total will be two, Allah total will be one, now from the tour till the end, we will check that Will do different joint, after frying, see both are opposite, both will do subject somewhere, one is quality, other has given guidelines and the other is positive, one of the two will do more addition flower total plus and also update the reverse difference as friend difference ma'am. Let's communalise the type, we will kill you here, we will make you run, we will submit Tanuja, it's okay, Adnan Sami, why don't you hide it? | 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 |
12 | That's a Hello Hi Guys Welcome Back to the Video Today is Question and Central to Mind Question Located in The Roman Reigns and Represented by Seven Different Symbols I B X L C D M Spotting Balance R15 to Zu-Zu Glasses Video and Roman 2ND Year Zu-Zu Glasses Video and Roman 2ND Year Zu-Zu Glasses Video and Roman 2ND Year Conversation Which will infringe description far cycle broken protector look at examples and additional presented by three lives for is represented by is followed by g ki shivling noel presented by is followed by Is Represented By Name Is Over 100 Which Bath Team In Final I Would Support So S Not Canceled Actors In Roman Reigns Namely I Which Depend M With Access Point Interview Loudest Your Suggestions Look At Some Examples Were Being Converted Into Service To Roman Opposition of Numerals Example Woman Presented In Nine Roman Numbers S3 Price Civil Defense Force Represented As Is Followed By Also A Similar Notice Today Represented As If Lord By Its Very Presence Of Eggs Pain Stand Up 123 Done Is Back Purified Air Shift Can Be Divided into two fifty plus five plus 3 in the character which represents soil is L5 preparation for baby in pictures consider infosys gram pati presented by ti cl company delhi ko 58th bell b jo women is jhalar latk traffic jam paanch bhed volume is 1994 ashwin month 100 Represented By N Choudhary Mentor Is - 1898 Is Represented S Choudhary Mentor Is - 1898 Is Represented S Choudhary Mentor Is - 1898 Is Represented S Cm Similarly In This Represents A B C And Forestry Project By i20 Company DLF 1994 Will B M C M Shift axis in the temple and decrement idiot number 203 perform similar operation in case of mine in the road suite consider the example 1994 initially switch of the benefits 120 inspectors a meeting element 100 from 1994 0994 and B.ed and paint M2 speed romantic hai navduniya Valley Of Not Miss 1994 Fakir Way More Than 4 Votes Porn Videos 600 800 Interesting And Decrement Not From Jeth 14 Leaf Romanticism CNN Telephone No News Again Ricky Ponting Weather 9 4 This Great Content Is Us Strong For Having Entertainment On It From Them Shruti Anu Malik Free Namaskar Andheri Improvement Is m-seal m-seal Election Improvement Is m-seal m-seal Election Improvement Is m-seal m-seal Election Vicky Ponting From Top Toe Bottom Matrimonial It's An Order For Living In Danger That Insignificant Develop It's Request For Girls For B.Ed I Doodh Spring For Girls For B.Ed I Doodh Spring For Girls For B.Ed I Doodh Spring Indictment Phir Main Bhi Pehle Daaba Leaf Na Mu0 Suicide Note Chuck Father And Will Return The Romance Languages MCM Dars weather number scripters 13202 that this period rwm to a roman rains a bluetooth initial listing of mt and have contacted m2ts the indictment are coming and number vitamin e that eighth medicine people were taken his condition which often mansion this great update and Thick 12910 600 internet fast train hai ki with CM wishes Ajay ko loot FD Dharmendra wale of number 104 loot ki election also perform simmer operations in case of 510 05 ki election ki chakradhar vibrator 10.00 tears ki election ki chakradhar vibrator 10.00 tears ki election ki chakradhar vibrator 10.00 tears A B C D ki indictment number phase ki aap Conditioner interesting and vehicles accident phone every forces 10v concatenate distic with cd indicant no. 410 that a few simple steps in case of 120 hearing this under witch represents a zee difficult romantic scene indicant no. 10 that similarly also add this condition pictures Wither away with greater noida and contacts hero man witch representatives 1981 mental of november 10 aur sunao hua hai ka milan de chak 15th dravida team 8 minutes ago pick content and width trains 140 episode 80 that accent loot indictment volume of number 1540 respectively to Perform in tips for channel like this ki bollywood a downtrodden sequel to 9 loot nine aankh house rent agreement not ki a which girl minutes after class five 114 loot bollywood specific on karte net ab sorry vpn difficult saeed bin adh ajay ko Torch Light Bill Gates and Equal to One Wiki Tested Positive Indication Number One That in the Final Year Turn All His Wealth and This Condition Will Return District Roman Typical Equivalent Roman Representation of the Interior of Hearing the Code Is Code Find the Symbol Different from Shampoo Submit code is good luck madam co dot submitted successfully su find your help full debit the like button subscribe to my youtube channel for more sach upcoming videos thank you to | Integer to Roman | integer-to-roman | Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
**Symbol** **Value**
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used:
* `I` can be placed before `V` (5) and `X` (10) to make 4 and 9.
* `X` can be placed before `L` (50) and `C` (100) to make 40 and 90.
* `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.
**Example 1:**
**Input:** num = 3
**Output:** "III "
**Explanation:** 3 is represented as 3 ones.
**Example 2:**
**Input:** num = 58
**Output:** "LVIII "
**Explanation:** L = 50, V = 5, III = 3.
**Example 3:**
**Input:** num = 1994
**Output:** "MCMXCIV "
**Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4.
**Constraints:**
* `1 <= num <= 3999` | null | Hash Table,Math,String | Medium | 13,273 |
149 | hi everyone so following us all the code daily challenge problem number 149 Max points on a line so the given problem statement is given in area of points where points of I is x i comma y I basically these two are the coordinates of our point uh represents a point on the X Y Line written maximum number of points that lie on the straight line okay and they have given some examples on those uh for this problem where we have received a array of points and we can say that all the three points lie on the same line so the force intuition which comes to my head after seeing this question is uh this must there must be something I have to do we'll have to do with the equation of a straight line which is y is equals to MX plus C where y intertons your y coordinate and it's the slope of the line X is it x coordinate plus C is some constant which we can neglect uh for now so we are going to be using the same uh formula like the same concept of equation of a line and we'll have to find out the slope of each coordinate pair for example slope between first point second point so between first point and third Point second point or third point and so on okay so this is what you have to do eventually and yeah like uh we'll be using hash to store the count for each slope in the results and yeah that is it I think so let's move for the solution first of all I want to sort out my given array which will sorry which will help for me running the loop okay next I want to Define some variables so slope is the hash which I was talking about in which you know we'll be keeping a track of how many uh how many lines have same slopes okay result is the maximum we will receive with this like the maximum number of uh pair of coordinates you will see with the same slope so yeah next I want to run a loop and I want to start with index 0. in this comma there are two coordinates right X comma y and you enumerate I'm using enumerate as it gives us index and the values uh in a single group okay so yeah also like I want to clear my slope or additional every time I pick a new point to start with so to do that I will be using two part layer for now okay next what you want to do you want to check the slope for all consecutive pairs so for X1 comma 51 in points and I don't want to use the same uh point so I'll be using uh all the points after this index so index plus 1 till end okay and this is done now uh if you check the equation of formula m is equal to X2 minus X1 divided by Y2 minus y1 so I'm going to use the same concept over here so X1 minus and as you find d y over here D1 is also the same uh y1 minus y okay uh one more thing which I want to do is I want to take a greatest common degree divisor or for the slope because uh there is a possibility that you know the overall answer still can further can be divided with let's say two for example if we see Ms four by two okay uh then it can follow them simplify two by one right so for that purpose I'll be getting or let me use some the new creators coming to do five minutes right gcd or PX comma d y okay and then slope is simple I'll be using DX flow division with greatest common divisors and d y latest common devices okay uh next we just have to increment the value for this particular in our dictionary and we'll be good to go uh at the last time I just want to like update the result value if Loop of n is greater than light result then I want to pre-initialize my value with pre-initialize my value with pre-initialize my value with slope of M okay and add the last at the time of return will have to increment 1 in the result as for example if uh yeah for example you know if you are taking if you're considering two endpoints two points for a line till this moment like when we are calculating this so you will get you are considering only one programmatically right for example you were trying to find out the slope between A and B right but you are using initialize that with a zero and we are incrementing one for example now A and B or you will say like uh if we don't do this use it we there was only one point on the line right so we were not considering the initial point so that's why uh we added one in there so let's run the test cases okay so there's some type of this one okay we received a key error over here correct it must be okay so let's do this if there is there are two methods for example like what I can do is I can check for this key every time I'm putting in or I can Define default date with integer values so let's see now foreign 97 96.29 of the submitted solution 97 96.29 of the submitted solution 97 96.29 of the submitted solution so yeah thanks a Time guys for watching the video and stay tuned for that coming month thank you | Max Points on a Line | max-points-on-a-line | Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**. | null | Array,Hash Table,Math,Geometry | Hard | 356,2287 |
103 | hello everyone welcome to our channel two bits in this video we will discuss a medium level lead code question zigzag level audio traverse we are given a root of the tree and we need to return the zigzag level order travels now what is zigzag so the question says that we need to go from left to right for the first level then right to left in the next level then left to right in the next level and if there was any other level then we need to go from right to left so this is the zigzag manual so in the first level we will start with left to right so we have one then we need to go from right to left so we have 3 and 2 and again we need to go from left to right so we have 4 5 6 and 7 so this is the question now it seems difficult but it is quite easy so if you have not watched the previous video which was level order traversal then please go watch it as it is a similar question you need to have the knowledge of level order traversal for solving this question so like in the previous video we were returning an array for each level similarly in this question we need to return an array for each level so we have one for first level then three two four second level and four five six seven for third level now let's see how we will maintain this zigzag order so in the level order traversal what we were doing was we were maintaining an array called current level which was storing the nodes at each level so let's say in the first level we need to go from left to right let's say we make it true we have a variable left to right which initially is true that means in the first level we need to go from left to right so in the current level we add 1 and we have left to right as true now for the next level let's make left to right as false so now we need to go from right to left as our variable left to right is false so in the current level we will store the values in right to left manner so first we will go to 2 we will add 2 to our current level then when we go to 3 we will not add 3 to the right of 2 but we will add 3 in front of 2 so this will give us a right to left manner then again after completing this level we will make left to right as true so now when we go to the next level we will visit 4 we will add 4 then we will visit 5 so we will add 5 then we will visit 6 so we add 6 and then we will visit 7 so we will add 7 so what we are doing is after going to each level we are changing left to right to not of left to right so we are changing this variable after each level and this variable tell us whether you fill the array which is current level in the left to right manner or in the right to left manner if there was any other level after this we would have filled it in the right to left manner which means we will append the values in the left each time now let's see how to do this through code now this is the c plus code for the zig zag level order traversal this code is very much similar to the previous code for the level order traversal that's why i have asked you to watch it if you haven't we have made very few changes in this code so what we will do is we will create a vector of vector named answer we will take a boolean value left to right which is initially true now if the root is null we will return the empty array otherwise we create a queue we push the route into it then we will iterate till the queue is not empty we will take size which is the queue size and the queue size represents the number of node in the current level so what we will do is here we have made a change from the previous video so what we will do is we will create the current level of size similar to the size of queue as we know there are only going to be that number of nodes in the current level so we will iterate till size we will pop the front of queue then if left to right is true if we need to go from left to right we will add the current value from left to right let's say that our size is 3 so that means the current level is going to have three nodes so we have a current level of size three now what we need to do is if we are going from left to right so we will add the current value from left to right so current level of i so i will go from 0 to size minus 1 that is 0 to 2 so if we need to go from left to right we will add current level of i equals to curl dot value so let's say the value was 3 4 5 so i will go from 0 then it will go from one then it will go to two so the values are added in left to right manner now we saw the case for left to right if it is true so we will add the current level in the left to right manner now let's say if it is false so suppose again the size is 3 and we have the values 3 4 and 5. so we will have current level which is equal to the size so we have 3 as the size and i will go from 0 to size minus 1 which is 0 to 2 so currently i is 0 and we are going to check the else condition so i is 0 size is 3 so we will add it to 3 minus 1 that is the second index we will add the current value which is 3 to the second index then again when i is 1. and the value is 4 so we will go to 3 minus 1 that is the first index we will go to the first index and add our current value that is 4. now you see that the current value is added to the left of the previous value so this is the case when left to right is false so left to right is false now again when i becomes 2 so we will go to 3 minus 2 minus 1 that is the 0th position and we will add the current value 5 so we get 5 4 3 in right to left manner so let's say this is the tree so in the first level we will go from left to right we add one to the current level in the next level we will go from right to left so we will visit 2 we will add it to the last index then when we visit 3 we add it before 2 so we get 3 comma 2 in the manner we wanted now in the next level when again left to right becomes true we will add 4 5 6 and 7 so this is how we get a zigzag level order traversing so as you can see this is if left to right is true otherwise we will add it in this manner now again we will follow the same procedure as we did for level order traversal so we will check the children and we will add it to the queue then we will add the current level into our answer and after each level we will do left to right equals to not of left to right so this was the c plus solution now let's check out the python solution now let's see the python code for this exact level order travels this code is very much similar to the previous video we have only made a few changes so what we are doing is if the root is null we simply return null now we take a variable left to right which is initially true and we take our answer array which we have to finally return we take a queue and we add root to the queue then we iterate till the queue is not empty we take size which represent the number of nodes in the current level so we take current level now this is the line where we made a change from the previous video so we take the current level and we initialize it by zero so current level has a length equal to size and it is currently initialized by zero now we will iterate through size we will pop the current which is the front of the queue then we will check if our left to right is true or if it is false if it is true we will add the value into the i-th position so let's say our into the i-th position so let's say our into the i-th position so let's say our size is 3 and i will go to 0 to 2 then we have current level equal to size so we have one two and three values now when i is zero we will add the value let's say three four five are our nodes so we will add the value three into the zeroth position then when i is one we will add the value four into the one at position and when then and when i is two we will add the value five in the two position so if left to right is true this is how we add the values now let's see what happens if left to right is false so we are let's suppose at second level and we need to return the values in the right to left manner so here the size is two as we know the queue contains two values we have our current level and i will go from zero to 1 so when i is 0 the size is 2 so 2 minus 0 minus 1 will give us 1 so we will go to the 1 index and add the current value which is 2 then when i becomes 1 we will go to 2 minus 1 that is the 0th index and we will add the next value which will be 3 now see that 3 got added to the left of 2 this is what will give us right to left manner so this is the change that we made in our code and next what we will do is we will add the children of current into the queue as we did in our previous video then we will add the current level to our answer and after each level we will make left to right to not off left to right and in the end we return answer now in python there is also an easier way to do this exact level order traversal so in this method instead of creating current level as an array with a length equal to size and initializing it by zero we can make it as q so the current level will also be a queue then we can easily add the elements to the right if it is left to right otherwise we can simply use append left if we need to add the elements from right to left so you will not have to anything just use append left and this works on the queue so this is the easier way to do zigzag level order traversal in python so this was the code for python and c plus the link for the question is given in the description do solve it yourself the link for the quotes is also given in the description and the link to join our telegram channel is in the description please join that thank you for watching if you liked the video or learned something new then please like share and subscribe to our channel | Binary Tree Zigzag Level Order Traversal | binary-tree-zigzag-level-order-traversal | Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100` | null | Tree,Breadth-First Search,Binary Tree | Medium | 102 |
71 | what's up guys I'm Tiffany land I do hacker rank and neek code question tutorials as well as just general programming tutorial so check out my channel and subscribe if you haven't already today I'm going over simple Python link oh it's a medium problem the description reads given in absolute path oops for a file unix-style simplify oops for a file unix-style simplify oops for a file unix-style simplify converted to the canonical path the parrot refers to the current directory I'm sure you guys know how the UNIX style file system works double period is going back directory or open directory make it should not end with a journaling flash and it must be the shorter string reference representing the absolute path so they did want us to get rid of so get rid of extra slashes the periods we have to read if we have dots we have to remove some of the directories accordingly so right away this should read hint to you that we need to use a stack so stacks less than first out I'm sure you guys have used it the last thing that you put into the stack is the first thing that goes out of the stack you pop it off so for example spam if for example this is the password given this one would we would normally pop something off but it's already empty so we just skip it whoops I mean to do that so we don't need to do anything we put a into here we remove this slash we just skip it basically we have to pop off the a so they were there put in the B we skipped the circle doesn't mean anything and we add the C so what we would return is slash b /c so what we would return is slash b /c so what we would return is slash b /c so let's just code that out I already have it all written out okay so first things first let's create these back string Google's new stack so I have green and then let's create the array so what I'm doing here is we're going to use the split function which is a function for strings in JavaScript and we're gonna slip the string that it's is path by the slashes so we basically remove the slashes and create a list out of it or in a ray sorry so if it was slash a slash B it would return a comma B so that's that and for string so let's do today we're gonna look through the boughs so if the first thing we want to check is if we logically the first thing I will check for is if it's periods we're just gonna pop it so if bow that equals so back pop so this actually would not work because it's possible that the stock could be empty so let's check for that as well stack let's make sure it's not empty so that will work and the other thing is just so push that's the only other option I guess the other option is to do nothing but we don't really need to code that because that'll be encoded in here basically so stack that push Wow and so the scenarios for this is the Damned the only scenario where we're going to push is if it's not a period it's not empty Val that is and it's not a single period so let's code that out now that is equals sorry so just empty so that kind of orders all the scenarios and then we just want to return we're gonna want to add a slash to the beginning because it says we don't want to add a slash then we're gonna use the join function so we have the array which is the we have the stack so we're gonna want to the stack is a string so we're just gonna want to add slashes in between that so the join function does that we just put slash and then we put the stack what we want to put the delimiter is not the delimiter and the way you'd call it in this case so that's for work submit it and using Java scripts you might sleepy alright perfect so the it works it's open run time because we have to loop through the stack and I believe it's just oh well then yes peace complexity because we had to create a stack so there you have it thanks for watching guys | Simplify Path | simplify-path | Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path. | null | String,Stack | Medium | null |
828 | hello guys welcome back to Tech dose and in this video we will see the count unique characters of all substrings of a given string problem which is from lead code number 828 so this is a substring count or a window count type problem before looking at the problem statement I would like to announce about our live interview training program which occurs for three months and it is a live interactive program happening on all the weekends Saturday Sunday which contains data structures and algorithms and you will also get live doubt clearance with the curated assignments and you will also get your interview guidance if you want to know more about the course then you can connect us on WhatsApp let us now look at the problem statement in this problem it is said that let's define a function count unique characters of s that Returns the number of unique characters on S for example calling count unique characters of s where the string is lead code then l t c o d are the unique character since they appear only once in string s therefore the count of unique characters is equals to 5. now you will be given a string s return the sum of the count of unique characters of the string T where T is actually a substring of s the test cases are generated so such that the answer fits in 32-bit integer so you answer fits in 32-bit integer so you answer fits in 32-bit integer so you will not see any overflow in the count notice that some substrings can be repeated so in this case you have to count the repeated ones too so you will have to count the repeated substrings too let us now look at some examples in order to get some better understanding now in this case on the left hand side let's assume that you are given a string s and let's say the string is ABC and the goal is to count all the unique characters in all the substrings of s so one simple way can be just enumerate all the substrings of s and count the unique characters in all possible substrings and just add them up so if you get the string S as ABC then all the substrings of s will be a b c and ABC now if you look at all the substrings then the count of unique characters in all the substring like the count of unique character in a is only one in B it is one in C it is one in a b it is 2 in BC it is 2 and in ABC it is 3. so the total count of all the unique characters over all possible substrings of s will be equals to the addition of all these numbers and this will be equals to 10. now if we look at another example where there are repeated characters you will see that all possible substrings will be a b a and a b a okay now if you count the unique characters for all the substring type for a it will be 1 for B it will be 1 for 8 is 1 for a b it is 2 for B8 is 2. now if you see for a b a this a the first a and the last a are repeating and so they will not be counted and we will only count B so the count of unique characters in this substring is one so the total count will be equals to the sum of all these counts and it will be equals to 8. so our goal is to find out the total unique characters in all possible substrings of a given string so I hope you understood the problem statement and the simplest approach can be to just generate all possible substrings of a given string and count the all the unique characters and just add them up to get the result but that will take a lot of time since you already know that for a n lens string you will have order of n square number of substring and minimum time will be n Square now the intuition for solving this problem is counting of all the unique characters in all substrings of s is equals to the sum of total contribution of each character as unique character in all the substring of s so if you look at our previous example then how many unique characters we had three unique characters ABC now each of the character's contribution can be added in order to get the total unique character contribution okay so let's see that with an example let's say that your string is a b now the substrings where a is uniquely present we have to see the substrings where a is uniquely present are this a and this a b right so a b for the first day for the second day you will have this b a b right b a b so you have B A you have b a b then a single a can also be present so this is also given and a b is also present so this is also given right so I have written those in two different columns for the first a this is for the first a the contribution from first a and this is the contribution from the second day I have not written ABA because in ABA a will be repeating two times so it cannot be included and similar is the case for a b because here a is repeating twice so you can't take all those substrings where a is repeating right so since I am counting the contribution made by a I will take all those substrings where a is uniquely present and then I will add like I will count all the substrings so this is 2 plus 4 which is equals to 6 number of substrings so the total contribution of character a is six now we have to count this for all possible characters and in the question you are given from A to Z so we can have a total of 26 characters at Max here I have counted for a in this case we have only a comma b as a unique character so let's count for B if you look at it for the first B if you look at this first B its contribution will be a b ba and also a b a so A B A and A B A all these four from the first B because I cannot Repeat b twice okay now again if you look at the second B this is from the second B and the second B is to the right hand side and it contains b and a b you cannot include a b right and you also cannot include a b definitely because B will be repeating so the strings the substrings will be b and a b now if you add all these contribution you will have 4 plus 2 which is again equals to 6. now you do not have any other unique character except for A and B so you are done processing all the characters in your string and so the count of all unique characters in all substring of s will be equals to the contribution from a and the contribution from B which will be equals to 12. okay I hope you are understanding the intuition how it is getting solved now the next question can be how to count the contribution of each unique character so we should focus on uh learning how to count the contribution of each unique character and so it is just a repetitive process for all the characters and you just need to add them up so let's take a bigger example let's take that the string is a b c a b d a now given a character or given a string a single character can either be occurring once or it can be a repeating character right so let's first solve for a non-repeating character a non-repeating character a non-repeating character in this entire string you will see that D is not repeating it is a unique character so if you are talking about the contribution made from D if you are talking about contribution made from d then we have to include all those substrings which are containing d and the cases which can arise from all the substring can be a substring ending at d a substring which starts at D or a substring which contains D somewhere in the middle like somewhere in between right so let us see what are all those substrings which are ending at this D and you will see that it is a b c a b d so this one ABC ABD then you have b c a b d you have a b d and d all these are the substrings which are ending at this D now if you try to find out all those substrings which are starting at D then it will only be D A now I am not including D again because it will again be repetitive because I have already counted D here so I cannot uh write it here again right otherwise we will be counting it twice which I don't want so d a is the only substring in this case which is starting at d now if you consider the third case like the substrings which contains D somewhere in between so you will see that a b c a b d a is a substring which is actually the entire string you will have BCA BDA c a b d a and BDA right so now you just need to add all these substrings and this is six this is 1 and this is 5 and if you add them up it will be equals to 12. so this is the total contribution made from d now if you closely look at all these uh calculations you will come to know that the contribution of d is not about is not all about enumerating uh all the substrings which are containing D uniquely but it is also about if you can take the left window like this is the left window right which is containing D uniquely and if you can take the right window so this is the right window which contains D uniquely what is the size of it the left window size is 0 to 5 so this is 6. the right window size is 5 to 6 which is 2. and if you just multiply them you will get all possible combinations which are containing D uniquely within the substrings right you will get all possible substrings so this is nothing but doing cross product now if we look at this technique as well then just for calculating uh the contribution of D which is a non-repeating character you will see non-repeating character you will see non-repeating character you will see that I will have to take the left window of D which is this one then I will have to take the right window of D this one you find out the total number of characters in the left window which is equals to 6 5 minus 0 plus 1 is 6 and this is 6 minus 5 plus 1 is 2 and the total number of such combinations will be equals to 12. so if you look at it by enumeration then the left window all possible substrings in the left window will definitely end at D so what are all the substrings ending at the Abc ABD and so on till this D this I have already written on the previous page right and all those substrings which are starting at D you will see that this is D and D A now in this case I have written it repeatedly you will see that this is nothing but a join operation or a cross product or a joint operation and in this operation this D this particular column and this First Column like this last column and the First Column are the same element so if you have seen the join operation on a table using a column we do not repeat that column so in this case as well when we take the cross product or a join operation this D when it is joined with this D it will not be repeated but only be written once because this is the common key now in this case if I write it again then you will see that a b c a b d will be multiplied with this D right and if you join them then this D and this D will merge together and it will be the same string and if you write all of them combining with this D then it will be nothing but the same substring right so this is where I have written it but if you combine it with the second one with d a then D will be common and then a will be appended to the end right so you will see that all these combinations are written on this portion and then you will just add them up to get the total result now this can be shortened up you do not actually need to enumerate all these substrings so what we can do is we can just multiply the count of it like here the count was 6 and here the count was 2. so all possible combinations will be equals to 6 into 2 which will be equals to 12 this is what you need to write and so uh we can write it as the left window size multiplied by the right window size which will be equals to 12 right so finding of the all possible substring having D has the unique character is nothing but the cross product of all the substrings or the window on the left side which uniquely contains D multiplied by all the substrings or window on the right side which is uniquely containing D now D was unique so we had taken the entire string and divided it into two parts at this point d right now how to calculate for the repeating characters so let's take an example for a now for a repeating character you will have to take different slices and you will have to consider them as a separate string where a is occurring uniquely right so I am calculating for a you see that a is present at 0 at 3 and at 6. so what will be the slices of the substring where a will only be present to one time so the First Slice will be this one ABC now in this slice a is occurring only once this is the largest First Slice where a is occurring only once right and in this case if you see the left window it will contain only a and the right window will contain ABC so if you can just multiply them 1 into 3 it will be equals to 3 and I have also written the enumeration of it the left window will contain the right in window will contain a b and ABC right and if you combine them you will get a b and ABC now what about the second day if you look at the second day then it should not contain either the left hand side a or the right hand side a so the slice for this second day will be this big okay now in this particular slice from index one to five the left window will range from 1 to 3 so its size is 3 and the right window will range from 3 to 5 so its size is also three one character has to be in common right in order to apply the join operation now the total number of such combinations where a is included only once including the second day it is equals to 3 into 3 which will be equals to 9 so you have to write the cross product enumeration of with of these two windows right and similarly from for the third window you will see that you should not include any a on the left side and any a on the right side you do not have anything and on the left side you have a at three so the left window size will be ranging from 4 to 6 it is of 3 length and the right window size will only be of size 1. so you multiply them together and it will be equals to 3. so there were three A's and the contributions were three nine and three so you will add all these contributions and it will be equals to 15. we had already calculated for D which was equals to 12. now if you try to calculate for B then you will see that you have two B's here right the first B has a left window size of 2. and the right window size of 3 which is from 1 to 3 because you cannot include the fourth index otherwise B will be repeating and so for I mean this is 3 so 3 into 2 is 6 so this will be 6 and for the second window you will see that this B has a window size of three and on the right hand side its size is also three so three into three is nine so the total contribution from both the B's will be 6 Plus 9 which will be 15 and similarly you can calculate for C you have only one C right so if you have only one see the left hand side window will be of size 3 from 0 to 2 and the right hand side window will be of size 2 to 6 which will be equals to 5. so 5 into 3 will be 15 and we already know that for D it is 12 so the total contribution from all the unique characters of this substring is equals to 15 plus 12 which is 57. this is what we want to find that is count of unique characters in all substrings of s right so this was our goal now the solution technique will be to keep track of all the window sizes like the left hand side window on the right hand side window sizes in order to do that given a string s you can maintain a list of list or a map of list where the maps key will be the unique characters which you are solving for in this case it can also be a list of list format where the indexes are given now in this case I have only a b c d as the unique characters but in the problem statement you can have from A to Z which is from 0 to 25 total 26 characters you can have it now in this particular example I will write down all the indices where a is present so a is present at index 0 3 and 6. so 0 3 6 is given now I will append I will like prepend all the list with minus 1 so that I can always have the left hand size window right I want to have the left hand side window so for this a the left hand side window on the left hand side you do not have any element so if you subtract this index 0 with minus 1 then you will get definitely a value of window size one right so that is why this minus 1 has been prepended or appended in the beginning now this 7 is appended at the end for the similar reason let's say that for this a I do not have anything on the right hand side so I will subtract from 7 minus 6 will be 1 so the right hand side window of this a will be of size 1 and similarly for this D you do not have any other D on the right hand side so its window size will be 7 minus 5 which is 2 right so that is why the string size is appended at the end and minus 1 is appended in the beginning and all the occurring indices are there in between so we have to iterate over all these elements right so if you want to find out the contribution of a then you have to go to this point like the contribution of a let's say c a is equals to zero when you are at 0 you find the left hand size window uh left hand size window so the less so the left hand side window will be 0 minus 1 it will be size 1 right hand side window will be 3 minus 0 which will be equals to 3 you multiply them in order to find the cross product and this gives you a contribution of three so this 0 is updated to 0 plus 3 which is 3. when your pointer goes to the next a then the left hand side window will be 3 minus 0 which is 3 and the right hand side window will be 6 minus 3. which will be equals to 3 and so the total contribution will be equals to 9 so 9 will be added to this and it will become 12. when you go to the next one which is 6 left hand side window will be 6 minus 3 and the right hand side window will be 7 minus 6 which is 1 so the contribution is 3 you add 3 and it will be equals to 15. so this is how you can iterate over all the indices all the yellow colored indices the actual indices and you can calculate the contribution for each character and you can keep adding them for all the characters and finally you can return it as an answer so I hope you were able to understand the intuition and how to solve this problem the time complexity is definitely the length of string and we do not involve any other time complexity in this so this is the simple code implementation which I have written here you will get your string s and I have taken a list of list named as hashmap it's just the name hash map like I have not created any hash map it is just a dynamic list of list now in the question it was mentioned that you can have from capital A to capital Z so you will have total of 26 characters numbered from 0 to 25 so that is why I have taken a size of 26 now I will iterate over all the list and I will prepend all the list with -1 okay will prepend all the list with -1 okay will prepend all the list with -1 okay all the 26 list with minus 1. and then I will go to the entire string and I will append the indices wherever they were occurring right one two zero one two four seven and so on right I will prepend all the indices where the particular characters are occurring and finally all the list will be appended at the End by the string size with a value n so that I always have a left hand size window and a right hand side window okay I hope you know the explanation like I had already explained that now I will take a counter equals to 0 and I will iterate over all these list of list and will keep on adding the contribution by each of the character so this is iterating over all the character and this is counting contribution for each character so the count maintains the contribution for all the characters in all unique substrings and finally we return the count as answer and this entire solution is order of string length which is let's say order of n where n is the string length I hope you were able to understand the logic and all the explanation behind this problem if you want to know more about the tech dos course then you can WhatsApp us and you will get all the details regarding the course if you like this video then please hit the like button and subscribe to our channel in order to watch more of this programming videos see you guys in the next video thank you | Count Unique Characters of All Substrings of a Given String | chalkboard-xor-game | Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`.
* For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`.
Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
**Example 1:**
**Input:** s = "ABC "
**Output:** 10
**Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
**Example 2:**
**Input:** s = "ABA "
**Output:** 8
**Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1.
**Example 3:**
**Input:** s = "LEETCODE "
**Output:** 92
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of uppercase English letters only. | null | Array,Math,Bit Manipulation,Brainteaser,Game Theory | Hard | null |
79 | well while you thought you could go to your google interview and not study word search you'd think hey of course there's some sort of search engine so of course you would want to know how to search stuff except that when you go here you find out what companies actually asked this question in the past say six months you see that google is not actually one of them at least not in the past six months okay so they may get back to asking this question which says given an m by n gerd of characters that would be grid of characters board and a string word return true if the word exists to the grid the word can be constructed from letters of sequentially adjacent cells where adjacent cells are horizontally or vertically neighboring the same letter cell may not be used more than once there will be some test cases with a board or a word larger than constraints to test if your solution is using prudig okay well not sure if that's relevant here okay so you just need to find a particular word in this case it's a b c e d we see that we found a b c e d over here like this in this example they ask you to find c and you see it here you see c okay in this example they ask you to find a b c b you have a b c e at all kinds of combinations but no abcb okay how the hell do you go about doing this well um you can see this right here um you could see that you could just search letters just as you would do you could go along the grid and whenever you see the first letter of your word you could just start searching in a depth first search and go through everything else the problem here is what happens if you already did a and you go down to s and then how do you tell it don't go search a again you just came from there well that's where backtracking comes in so you temporarily save the value of a as something else to indicate that you already searched it then you send s into your into whatever magic method you put in there and s will now think that a has already been used up but by the time your recursion comes back to a then you know that you could put back the original character and start all over in some other direction okay so that's how we're gonna do this thing okay the first thing that we're gonna do is we're just going to do a little sanity check so if uh let's see though if word is empty or um board is empty return um return false now then we want to come up with a bool did we find the word and we're going to set it by default to false and at the end of the function we're going to return found match so this kind of syntax just means return whatever it is if it's true or false it'll return it now we're gonna have to modify that by some sort of method so we said we're gonna iterate on the board and this is how we do that classic uh classic antique oh sorry and um int i equals zero i smaller than 4 dot size i plus and we're going to have int j equals 0 j smaller than board 0. dot size j plus so all we're doing is iterating through this thing and um so if we see that if board i j so if we hit the first letter equals s of 0 if we hit that first letter let's just mark that hit first letter then we know that we could use our little magic function here which we're going to call search word and how are we going to play this we're going to send in the word we're going to send in well we're going to be building our word and so we're going to send an empty word and that would be the current word that's what we're that's how we're going to set this we're gonna send the board whatever it is um we're going to send the current index we're going to send i j and finally we're going to send found match which will be modified to whatever the value is if the word was actually found and as we're iterating we if we already found the word we don't want to continue iterating so if found match this is before it moves on to the next character uh it found match return found match so if it's true then we return it so okay let's just make a little bit of space now let's write that search word little magic function here so void search word okay and we said we would throw in the word first so now just because leak code doesn't use this std notation and so on doesn't mean we're not going to they also don't pass things by reference we're not going to do that because we're cool we said we would have our current word so that's going on finally we're going to send in the board and again we're going to use that std notation after the board we just want to pass in an index by value this time same as int i into j we could make those constants as well now we send in the found match by um by reference because we'll be modifying that okay so we have let's see now if our current word this is our base case if our current word dot size equals our search word dot size then um then we could just return but prior to returning we send found match equals true and then we return otherwise okay now we just do a little sanity check so let's see how we play this if x smaller than zero or y is smaller than zero or i bigger or equal to four dot size so we're just checking our the size of this thing see how this goes um or j bigger than big or equal to board 0 dot size so that would be a column um or what else do we have let's see now well okay if this letter over here does not correspond to does not equal the word at the current index or we've already found the match so if somehow we were all we already sent our search word in here before we actually returned uh for whatever reason um and we're starting to run this thing we might as well go back right away then we could return over here that's all we have to do with that um so now that everything's been checked and where to correct cell within our grid we could start playing around so current word plus equal so we're just going to increment the letter word index now um we're going to now this is the kind of interesting part here we want to set a temporary value variable so this is our temp character um what is it this is our yeah this is our what is it um this is our temporary character and we want to set it to um let's see now board um yeah why did i put x over here this is actually i that's what i'm looking at over here so something was off there like i could see something was off so we're dealing with y i and j so that's our temp character then we're going to set this to board equals sorry let's see it out now we're going to set board i j equals something um and this something actually uh we're going to go back here the reason why it's going to go the reason why it's never going to find a space as soon as this is not the same as word index we're going to go back here so it's going to return and that's why this is a good character to put as a temporary character over here and let's immediately before we do anything else just set this back to temp now is where our recursion comes in so we could do our search word okay so we send in word we send in current word we send in a board index uh index plus one and then we have okay let's just write i j and then we have found match let's just copy this three more times so we want i plus one i minus 1 j plus 1 j minus 1. so this corresponds to i think i wrote something wrong here i plus 1 over here i think that's all we need let's see what happens if we run the code so this is going in every direction up down left right that's all it's doing let's see if this miraculously works and leak code taking a strange amount of time it does these little freezes every now and then let's see what happens if we select everything and do a little refresh come on leak code you could do it and our survey says what's its problem here if board error undeclared of identifier s oh it's word sorry and did i do the same mistake here no it looks okay let's hit run code undeclared identifier y again i was using x and y's line 35. i um i j okay that looks like it works and now we have a winner thanks for watching everyone oh wait a minute that can be that looks a little slow there let's run that again okay so i'm not sure what i did right there looks like in an iteration before now it goes at 440 milliseconds the exact same code that i was copying from has 80 milliseconds what's up with that leak code um not sure so too bad see you're out everyone sp completely could have fun | Word Search | word-search | Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
**Example 1:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED "
**Output:** true
**Example 2:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE "
**Output:** true
**Example 3:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB "
**Output:** false
**Constraints:**
* `m == board.length`
* `n = board[i].length`
* `1 <= m, n <= 6`
* `1 <= word.length <= 15`
* `board` and `word` consists of only lowercase and uppercase English letters.
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`? | null | Array,Backtracking,Matrix | Medium | 212 |
290 | hello guys welcome to code enzyme and in this video we are going to discuss the problem 290 word pattern of lead code in this playlist I upload daily Solutions of late word problems so if you are interested you can subscribe now so let's read the problem statement given a pattern and a string as find if as follows the same pattern so it is an easy problem here follow means a full match such that there is a bijection between a letter in patterns and non-empty words and strings patterns and non-empty words and strings patterns and non-empty words and strings so this is a question of sets and bijection and the constraints are the length of pattern is 300 so not very big constants and we can easily solve this problem let's see the examples so first we have a pattern A B A and dog cat dog so let's form sets we have a in the pattern string we have a and b and a is mapped to dog and B is mapped to cat so and here is the output is true let's see the second example in this example we can see a is mapped to dog B is mapped to cat and a is again mapped to fish so the output is false here are two things to notice here the length of set of characters in patterns is not equal to the length of set of words and by set I mean that the characters are not repeating so and we can also see that a is mapped twice so the number of edges is also not equal to the length of a set of is also not equal to the length of set of characters in pattern also in the example 3 it is the same thing we have the length is not equal and the a is also mapped to and the number of edges is more than the length of set of patterns so basically we need to check for three things the length of pattern string should be equal to the number of words and the length of set of characters in pattern should be equal to the length of set of words and at last we have to check for the number of edges which should be equal to the length of set of words actually this should be equal to length of set of characters in pattern but if this condition is true then this is also true so let's see the code first I am finding the words using the split function in Python and once I have a list of words I can first remove the edge cases that is the length of this is the first one length of set of patterns not equal to length number of words if that is the case then I am written in false if the set of words the unique words is not equal to Unique number of characters in pattern then also I am returning false else I can I'm making a set which is storing tuples of the pattern character and the word character and if the length of edges is not equal to the length of pattern then I am returning true so I hope I was able to explain you this properly so I uh if you are able to understand this kindly like this video subscribe to my channel I will see you guys next time thank you | Word Pattern | word-pattern | Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**. | null | Hash Table,String | Easy | 205,291 |
301 | right so today I'm gonna try to talk about 301 removing violet purposes basically we have a string input with purposes and some non professor's characters with which we don't really care about in the end I guess so the question asked us to do is to remove the minimum number of invalid parentheses to make the stream valid and we should return the all the possible results so just looking at the example here we have an input stream looking like this we can move remove the one two three four the fourth or the fifth character which are the or which are both closing purposes to get the first ballot a string result which is open causing open cozy open closing is the other possible result here is obtained by remove the second character here so - so this example tells us here so - so this example tells us here so - so this example tells us that for the same input string we can have multiple result so it's a it's true that it's a plural here and I guess another thing is the all the result in this results collection are going to be of the same lands because they are obtained by the same minimum number of the removal if one of the string is obtained by you know more number of removals the world violate the definition you know they are obtained with the same number from the minimum removal so they're gonna be obtained with the same number of purposes being removed from the original input string if they are in the or in the results collection the second example here in terms of the purposes they are the exactly the same as the first example we just have a number of s character mixed in there and as a result the result is actually the same it just you know still have that non professes character in there the third example it's a closing and opening purposes there's no way we can remove one only want to make it a valid so as a result we remove everything to you know to go to the worst case from infrastructure empty string so this tells us that in the worst case we have to search for all the possibilities so let's say we have M purposes the you know the every character every purposes has a option of being perp you removed or not we can potentially go to two to the power of n possible substrings to a search for so that's the worst case so if we think about this question in terms of treating this substring source nodes in the graph and we're doing some kind of searching inside the graph then there are only one kind of no edges at all going edges directed are all going edges and it's connecting a node of string of course to a node with a string that's a lens one - that's you know have one less lens one - that's you know have one less lens one - that's you know have one less character compared to the source substring and that edge represents to one single removal of parentheses operation so that's a pretty much the space we should search for we are operating and we are given a root node to that graph if we treat all the substrings of the same lands as on the same level if we then can do a BFS search on this graph from the rule node will be just consider all the possible sub strings with the lines L minus 1 then all the possible sub strings with lands and - - that sub strings with lands and - - that sub strings with lands and - - that would be breadth-first search we can would be breadth-first search we can would be breadth-first search we can once we read if we do this once we reach a valid string the first one that we encounter we know that it's the minimum number of removal we have been performed and once we get there we know all the results that we want are gonna be on the same level so this leads us to very naturally just think about let's go for BFS search it's not a horrible first attempt so we're gonna cut that up in the beginning just start a few quick notes before we go into the code I guess the start to code this thing up I guess one observation we can get from this example is that if we have a consecutive closing purposes or opening purpose the purpose of the same time we can reach at least the based on this example we can reach to the cin nodes on the next level you know substring that's less one short there are multiple ways there are multiple edges that are connecting these two nodes so there could be parallel edges and we don't really care about how we reach there how we which edge we pick so we clear some mechanisms to reduce the redundancy in there so that's just one quick observation by looking at this example here so with that said let's start code let's say that we're using a settler stored the results because you know there could be duplicates if we if no implementation is not optimal or not it contains sensor and redundancy in the code in the logic then we can use except to the duplication so it's not a idea but it will be a reasonable first try and we got a the candidates which represents to the current level of searching which initially is the input string we're going to try to code the man logic here so the wire loop it's going to be level by level and this is explored this level we're gonna have a temporary set to collect the possible notes in the next level just to do with the duplication so that when we do four nodes in the level we are eliminating all the duplicates and for every substring in the same level what are we gonna do is to test the whether it's valid or not it's in the bits of valid we're gonna add it to the results collection otherwise we'll see do we really need to go even further to into the next level we can tell that by just looking at the results if it's not empty meaning that this level is going to be the level then we don't want to do any further exploration so we don't push any thing any next level nodes into this collection otherwise we would do that so since I said it's our update here I know we'll have some de valid to here and this get next it would be some helper method we will cut up shortly after this man logic part so that's pretty much the level by level traversal BFS and for each of the levels we testing the candidates and if we have it we push it on to the results otherwise we will try to go from the candidate node and to follow all the possible edges we can follow - to grab possible edges we can follow - to grab possible edges we can follow - to grab all the nodes in the next level and just collect all of them into this set to do this deduplication and then we set it to be the level that we want to explore in the next iteration so just to quickly cut up the helper message here for determination of the valid professor string basically we do a linear scale from left to right we keep track of the unclosed opening purposes and whenever we see opening professors we increment that counter whenever we see chosen professors we decrement a counter when that counter goes below zero meaning that we have closing purposes that close nothing we should then the string is invalid and in the end we should have the culture to be zero meaning that all the opening purposes has been successfully closed so that's a linear path constant space code for checking whether the string is valid or not for the characters in this candy we're going to test if it's opening purposes we can increment the counter if it's a closing one then we decrement the counter we test whether the counts is less than zero do we have closing purposes that has nothing to close in the end we returned we test the whether we close all the opening purposes so that's the quick that's the message to test the validity of the cannulate string and then we have a helper to generate all the follow their edges to all the edges to go to collect all the nodes in the next level that's associated with a node in this particular level we check all the locations in the string if the character is a num / emphasis one then character is a num / emphasis one then character is a num / emphasis one then we don't care otherwise we would just construct a substring by eliminating a one of the purposes so that's the helper to generate all the possible follow the edges of this node to grab the next level nodes that's associated with this node we do the duplication with this being a set so that's pretty much the code so you can see that in the first level we would you know this would be order of N and if we exclude the time to construct a string which we should because it's linear then you know just to think about this level we have n next level for n nodes it's gonna search for M minus 1 possible candidates and let's say that we have K minimum number of purposes we need to remove all just multiply those things out we will end up with something like n to the power of K so that's a exponential in terms of the possible all the parentheses of the lands of the C string in there so in the worst case it's saying it's looking like that exponential number in terms of time and as well as a space so let's say if this code works is yeah so the code works and it's not too slow the really brute force testing everything except to use this set to do something to plication can then be like 50 percent of the code in there so that's a that's this first version of the BFS then what kind of duplicates we have in this code here and one of this the one is that these get next here so for all the candidates it doesn't really care about which purposes if you got rid of in the first run you try all the possible professors to get rid of this time so let's say that you do you did a move to zeros location in the in terms of the original string and you get rid of the one string and you know in the second generation character location one character in the second branch of the node in the first level which is you obtained by get rid of the first character in the original input the first branch for that particular leaf node would be getting rid of the zeros location a character in the original string so you basically doing for i from 1 2 and 0 to n minus 1 I'm nested with another for from J from 0 to M minus 1 so it's like a double counting one thing we can definitely get rid of this as this so to have the second loop nested loop to only try the eliminations that's after there for the parent 1 we could passing a location in here so instead of 2 just at the candidate a substring we also passing the last modified location in the in terms of the current candidates string here so we change the way that we are enumerated over the string and for that to work so the stuff on the levels here are gonna be a top aways the kind of a string as well as the last modified location and so to unpack this will grab both of this information the get necks they will need two piece of information those the candidates substring and also the last and modifier location so this will eliminate the double counting before the set by the applet has said the reduction is not I don't think it's having the problem size so we should get a little very tiny little bit of speed up that's from my guessing I guess so let's quickly check whether this quick small modification it's okay yeah it looks okay let's see if it works okay so what most so it really isn't so well we could try to implement try to find some other place that we can do improvements I guess okay so let's look at the string here to see if there are obvious mistakes that we have here let's say that the in the last iteration we removed opening purposes the for the next generation we don't want to remove the immediately closing purposes after that last removal because if we do that we will the to the two consecutive removals we just basically removed a valid professors in the string that will cause us to even if we ended up in a valid string you will cause us more than the minimum number of removals so this is a quick check that we can put into this get next to method here as well so let's put that in there so for that to work when you do adding one more information here in the beginning the last the removal is nothing there's nothing being removed it's empty so we need to also unpacked this allows the removal here and pass it into the link following method here so if the last removal is the opening purposes and the current character we are looking at it closing purposes then we would want to skip and I guess another one is if we have that's the very initial observations that we got from looking at the first example is that we if we have a consecutive parenthesis of the same type we don't need to do the edges basically are parallel so all we need to do is just follow one of those so let's add that logic in here as well so if we are to the yeah so this is saying that the previous location is the same character as this current one that we are looking at then because we already tried the folder link there we don't follow the link here so these are the few additions that we did in there and I think that let's try to submit this actually okay we find an arrow okay the unity we should hear the last modified last to remove the character which in the case here is the one that we are removing so you shall work now so yeah we get a quite a huge a jump in terms of the speed in time complexity the reason is that this is pretty much the this is actually the case for duplication right this is this means the parallel edges inside the graph and things that once we consolidated all the parallel edges so there are the row for this set here become you know not existing because if we are not generating duplicated nodes on the levels then there's no need for self here so yeah we're gonna do a quick modification to eliminate the need for the set because the set here you the key is a topo right and the first element in there is a lens and string I guess the hashing that can be you know it's not as if we just directly put this onto an array so I guess this will save a little bit of time in Serie so let's do that so we no longer need this thing here instead we're gonna do like because we're doing BFS let's use a Q since there are no Q in Python we use deck I just copy the type thing here and we should get rid of this also for because so for level wise we just have a full loop with the number of nodes in the level instead of this for loop here and we can pop this information out front from the front attack pop front left it says also that we are doing BFS and here the updates it works for self and not for the deck here so it's candidates extend and we don't need this anymore okay so let's see was this here we pretty much consolidate with lessness here we consolidated all the parallel edges and hopefully we can have some speed ups okay yeah let's try this okay it works slightly faster it could be around random things alright so I guess one last thing we can do is to actually pre calculate the for this BFS version is to pre calculate the possible depths the number of links we should follow in the sequence to get into the minimum number of removals because that's actually something we can in calculate it's not so obvious to me in the beginning that when I reach this solution I don't realize that but when I read some of the solutions I find this could potentially be a time-saving could potentially be a time-saving could potentially be a time-saving initial addition into my to my solution so we can do very similar to this validation for the string to be valid or not we can do one pass through the string and just counter the number of opening and closing purposes that we see and just based on line information or we try to decrement or incremental thing to counters and we will be able to figure out exactly how many invalid opening purposes and how many invalid the close and purposes are there in the string so that for all this nodes here in the graph we can actually use that additional information to help us to even you know trim the search tree even you know prune a tree even further whether that can listen to some speed up and that's based on depends on the test cases you have I guess but in series you should be able to help do getting these are some speed ups let's say that we write a simple procedure similar to this valid here I've actually put it here ok so initially we have zero left and right we'll use this to we're able to indicate the number of unclosed the open purposes and dangling closing preferences you extra closing purposes so we're just going to do one pass through the string if it's open then we increment this contour for the opening purposes if it's a closing purposes then there are two things we need to do if we do have an opening one we decrement L otherwise we'll increment our so again so in the end the variable L is the number of opening purposes we need to remove o and R is the number of riot purposes you know the closing purpose is that we need to remove so we start before we do anything we actually grab those two values by scanning through the string ones and then in the next we can actually use this to information so the logic is that if we already get rid of L number of opening prophecies then the only one that we can get rid of to get to the next level grab the notes in the next level it's going to be those that we can go through a pass that by eliminating a closing purposes if we shouldn't remove left parenthesis and this character just so happened to be opening purposes we don't want follow that edge and here it will be if we follow the left link if we remove left parentheses we decrement this could be done by let me actually just convert this so if we follow our edge of left purposes simple opening purpose assume simple we decrement this if we follow the right one we document our that's pretty much the thing here and the for this to work your pass these two things on to an hour nodes and that as a piece of information of the nodes in the graph so that's become a little bit to Claude it so I guess I just clean it up a little bit and the substring is just the zeros filled in this candidate topo and I'm just gonna Park it here let me get rid of that old version so if you wanted to look at the progresses you can you know pull back the timeline I guess so that's pretty much the code oh yeah there is one more use usage of this and are here that's in the determination of the valid candidate we know when we are at the exact level that's when the remaining our and our the opening and closing confesses we need to get rid of is sum up to 0 so they are exactly zero at the same time so that we can modify this condition so if we are not at the level yet we actually don't go one pass through the string to check the validity so that could potentially be some kind of time saving so let's quickly check if we have problems but this looks like a so let's try submit this jeez so that's for fun runs through example and submit okay it's working on again I think the tester set in the Leko website is not too big so even though I think there should be some benefits in doing this it's not obvious here note that the space here it's always really bad here and not very good here because that for the level wise traversal you can imagine that it's exponential in terms of number of possible nodes in the worst case for each level that you go further and so since that now it's a deck here it just change one line of code we can change this to DFS and this will save some space at least in CV let's see if it works No why I see the reason is that for a depth-first search once we is that for a depth-first search once we is that for a depth-first search once we find a result it's actually exited so for this to work to become that first search what we can do is then we test whether the candidates as MD or not and we actually don't need this loop anymore let's say that this works geez yeah I guess first thing we can do is through this is should be a set here and the condition here seems to we shouldn't be testing this yeah the reason that we missing long here is that the original testing logic is wrong if it's a valid we just ended there otherwise we would try to extend this candidate sphere and the prevention of us being going to the next level is actually done by here all right so if Bo's era and are zero you will never you think it will never do this unless it's a constant character which will be appending to the ride or yeah I think so let me grab this test case yeah I think it will work so how are we doing more space not good but this is I think it's indeed DFS so if you think about the tree that's fanning out you follow one branch and only branch over there and go branch even further until the minimum lands and then I go back track so I think it will be N squared of the total notes that's maximum in this stack area where there's in the BFS version it will be you will be exponential potential so yeah so that's pretty much my solution um I'm avoiding the time and space complexity in accurate and detailed numbers because I'm not a hundred percent sure about the my analysis so I think I need more to grab some combinatory books analysis of algorithm books to help me to reasoning so this more in more detail but I think it's in the exponential territory and for the space is in the quadratic space if we do DFS if we do BFS there could be in the exponential territory again and I guess if you go DFS in the first trial Ari I think it's okay but it's not that straightforward as at least to me it's not that our natural I think to have a BFS version even the naive version that just blueforce through all the branches as the first trial and try to look into the possible situations of the you know the edges between those nodes what are you atopic hunting when you a topic hunting and what are the parallel edges how you know from using a set to do explicit deduplication to make sure that the generation the traversal does not follow the parallel links it's a good progress at least so that's the question for today it's getting too long and not quality anymore | Remove Invalid Parentheses | remove-invalid-parentheses | Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return _a list of **unique strings** that are valid with the minimum number of removals_. You may return the answer in **any order**.
**Example 1:**
**Input:** s = "()())() "
**Output:** \[ "(())() ", "()()() "\]
**Example 2:**
**Input:** s = "(a)())() "
**Output:** \[ "(a())() ", "(a)()() "\]
**Example 3:**
**Input:** s = ")( "
**Output:** \[ " "\]
**Constraints:**
* `1 <= s.length <= 25`
* `s` consists of lowercase English letters and parentheses `'('` and `')'`.
* There will be at most `20` parentheses in `s`. | Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options:
We keep the bracket and add it to the expression that we are building on the fly during recursion.
OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed.
Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values.
0 1 2 3 4 5 6 7
( ) ) ) ( ( ( )
i = 0, left = 1, right = 0
i = 1, left = 0, right = 0
i = 2, left = 0, right = 1
i = 3, left = 0, right = 2
i = 4, left = 1, right = 2
i = 5, left = 2, right = 2
i = 6, left = 3, right = 2
i = 7, left = 2, right = 2
We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them. | String,Backtracking,Breadth-First Search | Hard | 20,2095 |
66 | Hello everyone, Evgeniy Sulima nov is with you and today we will look at the problem years code number 66 plus 1 according to the conditions of this problem we are given a non-empty array of problem we are given a non-empty array of problem we are given a non-empty array of integers which is a positive integer and we must increase this number which seems to be increased by 1, but it is not said that each element of the array is one digit, that is, from 0 to 9, and the first element of the array cannot be the number 0 only if we transfer only 0, for example, we receive an array of 123, this means that the mass will have the number 123 and that means I must return feel 24 in the array is the number 124 the second option is four three two one this means that I was given the number 4321 and at the output I should get the number 4322 and I actually have an array of 4322 let's first try the option in the Lord which we don't think of, that is, I first define the index of the outermost element, that is, the state king index is equal to digit . state king index is equal to digit . state king index is equal to digit . links -1 after that I take that digits index -1 after that I take that digits index -1 after that I take that digits index + + and at the end I do return + + and at the end I do return + + and at the end I do return diger let's run this solution in the promo and see what we get bronzer forum we think until we see that everything is fine, that is, we got 1 2 3 as an output got 122 124 and expected 124 well, that’s exactly why I love this well, that’s exactly why I love this well, that’s exactly why I love this problem, it’s because they teach us to problem, it’s because they teach us to problem, it’s because they teach us to think about what can break our Thai algorithm, you highlight corner cases that are fatal for us, let’s cases that are fatal for us, let’s cases that are fatal for us, let’s assume that we have such a data sample as input that is, 999 and here I expect to get the number 1000 to but if I run the current algorithm with this data in konami, then I will get 9 10 at the output, which is in no way acceptable for me in the problem statement because here we expect a thousand, that is, 13 0 a I get 9 10, what should I do? I can go through the array from right to left and find out that if this number from the array is 9, then I make it 0, and the first element of the previous one, I increase it by 1, this is clear, the worst case is when all of me are nines, yes then is in this number and this means that in this case I doors create a new array which is larger in size where I have all the zeros of the operation ment became one date and steel connections I here got one 1000 how can I implement this approach that is, I write that I go in a loop until the digits index is equal to 9 and while this index is equal to 9 I say that the digits index is equal to 0 and in Yandex I shift there is now well, what if my index is less than zero, that is, I have reached the first number, as it were, I have the first element was nine then I create a new array I write that digit is equal to new and the size of the gidget links + 1 by 1 element of course + 1 by 1 element of course + 1 by 1 element of course becomes equal to one, that is, digits 0 is equal to one and I leave my array here I write after this cycle I say that if only if Yandex did not reach me, that is, if the index is greater than or equal to zero, then only in this case I do the digits index plus there is a check, yes, that is, we received from three nines, I say nine current Gould repair then you will make a bunch of them have 0, move the index to the left and again go through the cycle then the synds are all greater than zero nine he city and thus I go through three times we get 2 3 0 Yandex became -1 and times we get 2 3 0 Yandex became -1 and times we get 2 3 0 Yandex became -1 and only in this case I especially in the array in which everything zeros but I now have a one ahead, let's run this code, see that there are no compilation errors and everything I have from working on 3 nines param-param hurray on 3 nines param-param hurray on 3 nines param-param hurray worked now we can try this solution for bend and see a couple of cutlets option for everyone from the songs The approach differs from me that it worked very quickly, that is, very quickly the solutions are difficult here for me in time from m because we have to go through the entire array in the worst case from memory at the hotel because we do not have to increase create a new data structure for this solution, this is where we end review of this task I say goodbye to you all the best | Plus One | plus-one | You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
Increment the large integer by one and return _the resulting array of digits_.
**Example 1:**
**Input:** digits = \[1,2,3\]
**Output:** \[1,2,4\]
**Explanation:** The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be \[1,2,4\].
**Example 2:**
**Input:** digits = \[4,3,2,1\]
**Output:** \[4,3,2,2\]
**Explanation:** The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be \[4,3,2,2\].
**Example 3:**
**Input:** digits = \[9\]
**Output:** \[1,0\]
**Explanation:** The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be \[1,0\].
**Constraints:**
* `1 <= digits.length <= 100`
* `0 <= digits[i] <= 9`
* `digits` does not contain any leading `0`'s. | null | Array,Math | Easy | 43,67,369,1031 |
744 | Hello everyone welcome back to me channel once again so here we are going to talk about the problem of late code daily challenge and today's problem is also lift code easy problem missing okay whose name is finance give smallest letter target this question first we People, let me tell you a simple approach which will be your one liner search, basically you will know it to many people but we will also discuss the approach of research and I will discuss it for a minute if you want. If not, then check it out, you will get everything like code etc. Also, it is not related to this question and has not been made public, this video will be just the end, below I will link you to the video solution and will post it to you where you can get it. I have discussed both the approaches of linear search and tried to give you a step by step overview and have provided you the code here in all the three languages of linear search, binary tried to give you a step by step overview and have provided you the code here in all the three languages of linear search, binary tried to give you a step by step overview and have provided you the code here in all the three languages of linear search, binary search, C Plus and Java Python, so you can do the same in any language. If you are doing it will be easily available here. Okay, so I will add its link in the description box below and if there is anything else in this and you feel that something needs to be added, then you have given the link of discard in the description box. Come there and tell me, okay, so you have to read the question, what is being said in the question that you have an error in the character, right, this character is given, which is the letter from the name of the letter, which is this, it is sorted in non-decreasing order. which is this, it is sorted in non-decreasing order. which is this, it is sorted in non-decreasing order. Which was the problem of daily challenge of lift code of just previous day, in the same way there was non- same way there was non- same way there was non- decreasing order and we had discussed what is non-decreasing order, what is non-decreasing order, what is non-decreasing order, right, so what happens in it that you get one of your characters. Okay, you see it in the increasing way but with equal sign, you will see the possibility of egg character target also, you are getting it, so there is a target character A Maa lo, you have got it, you will have at least two different characters in it, okay, so not all are unique. Will be main's answer story or story is possible I think it could be a fish so what do you have to do now return which is the smallest character of the smallest character which will be greater for lake geography? The graphics that will be the latest ones can be much more than this. Okay, there will be many characters that will be requested from A, like if we talk here, CFG is the largest among all the three by doing such graphics, returning it is the biggest here. If C was the smallest then it is okay among these three, if we talk here then there will be no C in the comparison of C. Okay, here I have given C, so this will be the whole of it, no one here will be big, so we What to return, how indirect, whatever is the first character of the letter, return that first character. Here the complexity is correct. If we talk about 10 to the power of 4, then you will eat it easily. We can do it by traversing it. Right then easily you travel to it. You can do it by doing and we will discuss the same first, okay, we will optimize after that, so this is basically not fully optimized, okay, so story or story, you will have to think a little more on this, now if you are going in linear way. What is the simple concept that you have a character, if we are talking about solution one, right, let's talk about solution one, we have one of length, right now, what is it and we know that if we travel in 1 second. If you are thinking then you will compare 10 Power 6 and 10 Power Rangers. Okay, as our expectation is that whatever character is bigger than the target, give greater target, whatever target support is ok, so we will do it in this way. If you analyze its time complexity is fine then what will happen if time complexity is done here, you have checked access to all the elements, is it greater or not, after that you took mini, then your BON complexity is getting rich, it is not wrong but it will also be acceptable but Let us discuss a solution second. I think there is nothing much in it. If you want to see its code etc. then I will tell you the done code etc. Here you will get the blog which is here. We also discussed this and its code will be found here. It is easy for you too, you can do it easily, okay, now let's come to the solution which is a little optimized and you have to learn this approach basically, otherwise there was no special meaning in giving this question to you, now understand that there is one piece of information here. In the question, what we have not yet thought about, we have not done it in the bigger picture, many times there is extra information, like if you had gone for an interview etc., then you would have provided if you had gone for an interview etc., then you would have provided if you had gone for an interview etc., then you would have provided extra information, but here it is such that the less information is the bigger one, we think about it. Decreasing order is software, okay so it is sorted in non-decreasing order, so we have sorted in non-decreasing order, so we have sorted in non-decreasing order, so we have sorted the part only then no one did it. If I look in approach one, there is no one, nothing, we thought in the bigger part, so what will happen now, basically understand sorting. What is the meaning of Okay, in increasing, what is going on is ABC and Di. Now understand here, hitting a particular position, right in this particular position, A is lying supposited here, F. If we are talking about Di, then now What will happen to di? So if we compare it is okay like this is di which is right which is bigger than C. Di which is bigger than C is the right one. ABC is the best so all the characters after di will be as many as there will be here. All will be bigger right from ABC, so if it is ok, then if this one is ok, particular position, whatever is ok, position, particular position, whatever is ok, particular position, if this one is ok with the target, then all the tractors here will be big, so there is no point in checking here because We need that first greatest greater, okay or let's take left, here it will be good, left and right come up, so now what will happen is that till now we were searching so much here, ours was this. Area: This area will shrink, it will ours was this. Area: This area will shrink, it will ours was this. Area: This area will shrink, it will break and this area will be broken and this area will be formed. Now your answer will like in this range. Do you understand what it means, all the elements here will be bigger, there will be one before this, okay, there will be one before this, then our range is. It will come here and what will happen to us in this, it will shift to the right, okay, if it shifts to the right, then what is your possible, from here till the next position till the right, okay, then how will it shift to the left, and we will do this thing again and again. So what will happen to you first, as it is so big, okay, it is like this, then after that there will be half more, then it will be reduced to half and after half, your last bus will come here, so now what will happen, we will do these elements every time, I will show you the code. Now we are with the court, I have also added a comment here, it is okay and you will get the semicon here in binary plus one also, so I have added the entire comment from there itself, right here, it is okay, so we This is where we come to understand, first we determined the size, left and right, okay, we have two points to set the truth, but before that we checked whether the target is on the right. What is greater than, then how is indirect? If it is, then you have left now at zero, so call it directly zero or call it left, it is the same thing, so we have returned the first character, now coming to our loop, in the search one, we have taken out made. And this is the thing, if the target is bigger or equal then we will shift left and that will be ours, what will happen every time, the event will run, okay, so finally when this entire search will run for you, okay what after that? You will have the one on the left which will be the painter. The point on the left is telling you which is the first element which will be bigger but just greater than it, the first position which will be the smallest will be greater. Give the target, he will be keeping you its position, so its If there is a position, then we can find it out by doing a simple position in the letter, okay, so this is what we returned, it was a simple serve, okay, almost the concept of boundary search from SIM is the same thing has happened here and Let me tell you, whenever you calculate, then do this method, the chances of overflowing flow are lost. If you directly do left plus right, then it is possible that some slightly larger ones are possible. Wherever this formula will be set, but if that formula goes out of its track for you, then there are chances of getting an error, so always keep one thing in mind that this madam is right to use such a formula, so let's discuss in this video and If you have any doubt, please tell me in the comment box below, it is ok and the link code of this block etc. is given in the description box below, see it from there and check it out, if you will get the court here then not me. It is being said that I will have to add a separate getup link for this solution. Okay, so I will simply add the link of this block below and you can take your reference here. Is there any suggestion like this for the questions regarding the blog? Description about the video below | Find Smallest Letter Greater Than Target | network-delay-time | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. | Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path | Medium | 2151,2171 |
1,582 | hello guys and welcome back to Le Logics this is the special positions in a binary Matrix problem this is a lead code easy and the number for this is 1582 so in the given problem we are having an b m cross and binary Matrix mat and we have to return the number of spe special positions in the binary Matrix mat now let's see what a special position means so a position I comma J is called special if the Matrix of I comma J is equal to 1 and all the other elements in the row I and the column J are zero so the cell value should be equal to 1 The Matrix of I and J equal to 1 and all the elements in the same row and the same column of the cell should be equal to zero so let's see for this input uh the cell value one 1A 2 all the elements in the second column are zero except for this cell and all the elements in the first row except for this cell are zero this means this is a special position and it is the only possible special position because for this one is colliding so there can be no more uh special position so the answer to now let's see example number two here we have 1 one 0 1 and 22 so for 0 is there any other one in the zeroth row no is there any other one in the zero column no so one is a special element 0 is a special element now similarly for 1 one and 22 there are no corresponding uh ones in the their rows and columns so these two are also special elements so the number of special element for this input becomes three which is the answer now let's come to the approach how we are going to solve this problem so you can also solve this problem by simply iterating over the Matrix and uh at each point of time checking that in the current row there were how many ones and columns but it will make the solution too complex instead what you can do first check for the rules if the rows are satisfying the condition then only check for columns so let's see for this input that was the same as the example one so first of all we'll check for the each row so is it possible for zeroth row then we'll say no because there was this then we come in the second row we find one we check for this is this possible yes then we'll check for the column only for second column we do not need to check all the columns we only need to check the column or the cell because the row was already satisfied that there are no more ones in the row now then when we'll check for the column we find that there are no other Z no other ones so we can definitely say yes it is a special position and increase the counter so yes this is how we are going to do first check for the r and if uh it is possible then check for the columns so let's start with the coding section but before that do like the video share it with your friends and subscribe to the channel so first of all we will Define a variable to count the specials special positions so we need to define a method check row and in the check row we'll pass the Matrix and the index uh this particular index is the row for which we are going to check and if the index is greater than equal to Z and check column so you see we have already checked the row and now we are going to check the column and for this we have to pass the I as well as the index because the I and J both we have to pass for the particular cell and if it is true then do the special Plus+ otherwise return the Plus+ otherwise return the Plus+ otherwise return the specials now we need to define the check row and the check column functions private in check row it will take a matrix and it will take a variable I as input parameters initially the index will be zero J equal to Z J is less than M do uh I think it should be m.0 l because do uh I think it should be m.0 l because do uh I think it should be m.0 l because we want to see The Columns then if the index is greater than equal to Z we return a minus one this we return we will do index equal to J and after this we can return the index and similarly now we have to make a private boo check column function so it takes a Matrix it takes a i it takes and so we check matx of J and index if it is equal to 1 and J not equal to I so we have found in this case we have found another one in the same column which is uh not good for the special position matx so that's why we'll return a false here and if it passes this entire Loop then it will be definitely true it will be a special positions so we can pass here to I think the code is complete now let's run for the sample test cases are passed cases the sample test cases are passed let's try to run for the hidden test cases as well the hidden test Cas is also passed with a good time complexity and a good memory complexity so the time complexity for this solution is O of M cross n where M and N are the number of rows and the number of columns of the Matrix and the space complexity is actually constant because we are not using any extra space and we are using only the Matrix which is provided to us and no extra space so that's why the space is constant so you can also check the C++ Python and J the JavaScript code the C++ Python and J the JavaScript code the C++ Python and J the JavaScript code by going into the solutions panel from the lead code and then you can check my this solution this one it consist of the intuition approach complexity and the code Java C++ py complexity and the code Java C++ py complexity and the code Java C++ py JavaScript and yes remember to Upward I hope you understood the logic do like the video share it with your friends and subscribe to the channel if you're new to the channel thank you for watching the video have a nice day | Special Positions in a Binary Matrix | design-browser-history | Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**).
**Example 1:**
**Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\]
**Output:** 1
**Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0.
**Example 2:**
**Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Explanation:** (0, 0), (1, 1) and (2, 2) are special positions.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `mat[i][j]` is either `0` or `1`. | Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ? | Array,Linked List,Stack,Design,Doubly-Linked List,Data Stream | Medium | null |
146 | hello everyone welcome back to my channel this is stacy today we are going to look at number 146 problem lru cache before we jump into the problem let's look at some pre-info the problem let's look at some pre-info the problem let's look at some pre-info that would help us to understand it better first what is a cache is a component that stores data so that future requests for that data could be served faster if you look at this graph cache is closer to cpu comparing to main memory that's why the time to read from cache is much faster also it has smaller space so the limited space could be easily filled up then when the new data comes in we have to get rid of something first but which one should we remove there are some algorithms to solve this kind of problem we also call them as cache replacement algorithm and lru is one of them since reading from cache is much faster we like to keep those atoms that we may use over and over again in other words we'd like to get rid of the atoms that we may not use for the longest period of time so how do we find them here comes the lru which is least recently used it's basically a prediction based on the fact if the last time we access it is a long time ago then the next time we access it would not be anytime soon thus we invicted let's use this example to see how lru works supposing we have a cache of sas 4 and then we put one two three four in turns into the cache so the cache is full then five comes we have to get rid of the least recently used one which is one since we put one into cache first after we removing 1 we put 5 into the cache and 2 becomes the least recently used one now if we access 2 at this moment that means we used the 2 recently then 2 is no longer the least recently used atom instead 3 becomes the least recently used one now and finally when 6 comes we remove the lru atom which is 3 so that we can put 6 in and 4 becomes lru atom now that we understand how lru works let's look at the problem now in this problem we're going to implement lreu cache class when we initialize it we define the capacity and the in function returns the value of the key if the key exists otherwise return negative 1. for the put function we update the value of the key if the key exists otherwise add a key value pair to the cache if the numbers of keys exist the capacity from this operation we invict the least recently used one there is also a requirement for the time complexity which is o1 for get and put function alright the problem is not cleared let's think about algorithm next okay the first question we need to handle is how to mark our u adam some people may think to use a tab stamp because the lru atom is the atom we accessed earliest but is there a battery to do this let's review what we did in the previous example in this example the red atom is the lru atom and it seems like it always shows at the end of the cache on the contrary whenever a new atom comes in we put it at the beginning of the cache for example when 5 comes in another thing to note is that whenever we access an atom from the cache we also put it at the beginning of the cache for example we will access two here so it seems like the position of the atom kind of represents the time stamp we access the atom and it actually does if we think about the cache as a list from the head to the tail it's from the most recent ones to the least recent ones if we represent the cache as a linked list there are three different situations first when there is a new atoms comes in for example the five we are gonna create a node and add it to the head and second when we access an atom in the cache we remove it from the current position and also add it to the head since that's the one we used most recently last but not least we will reach the capacity we remove from the tail which is the lru atom the second question is how can we make sure the get function is o1 time complexity because the get function is the key to get a value and also its o1 it's very easy for us to think use a hashmap here the key of the hashmap is the key we put in and the value of the hashmap is the node of the linked list which includes the key the value the next pointer another question similar to the above one is how can we make sure the put function is also a one time complexity as we all know for linked list the add operation is one but the remove operation is on because we have to traverse the list to the node we are going to remove so how can we make the remove option is also o1 the answer is to use a double linked list let's look at this example supposing we're gonna remove two here is what are gonna happen we make three point two one instead of two at the same time make one point two three instead of two at this point the next node of 3 is 1 and the previous node of 1 is 3 which means we removed 2 from the list so for the double linked list the remove operation is also o1 and since we use the double linked list we also need a pre-pointer here we also need a pre-pointer here we also need a pre-pointer here so in conclusion user hash map makes the get function its o1 and user double linked list makes the put function is also o1 then comes to the question 4 any other details we all know in linked list for the boundary nodes we have to do not check when adding or removing it just makes things complicated so is there something we can do so that we can forget about all the null checks luckily there is we can use a dummy head and tail after adding the dummy head and tail we basically say goodbyes to boundary node situations and of course at the beginning there is only a dummy head and tail connecting to each other as we solved all four questions let's jump to the solution let's look at the note class first there is key and value prey points to the prenode next point to the next node when we initialize the node we pass in the key and a value then comes to the dummy head and tail next is the add function of the double links list we use this function to add the node to the head of the list which is the next node of the dummy hat let's see how it works supposing we're adding a note to our initial state first know the prey is head then know the next is head next then how the next dot pre is node finally how about next is node after these four steps node is the next node of the dummy head which means it is the head of our list then come to the remove function it removes the node from the current position let's look at this example again so node.next node.next node.next is node.next means three point two one is node.next means three point two one is node.next means three point two one instead of two and no the next stop pre is noda pre means one points to three instead of two till now we have three and one connecting to each other which means we remove the two from the list the last function of the list is the update function it basically just call remove function and then call add function why do we need this remember we said earlier if we access an atom in a cache we need first remove it from the current position and then add it to the head let's basically combine these two functions together so here it is the update function finally come to the lru cache we have count and capacity to keep track the size of the cache and the map to store key and node pair so that the get function is one time complexity when we initialize the lru cache we define the capacity initialize con at 0 initialize the map and create dummy head and tail node then connect them together the get function we use the key to get a node from the map if the node is null it means the key is not in a cache we return negative one otherwise we update the node remember first remove then add it to the head in the end we return the value of the node and finally the put function same as get we use the key to get a node from the map if it's now the key is not in a cache so we create a node use the key and value then call add function added to the hat don't forget also put the key and node into the map and increase the count as we have a new atom if the node not equals to now means it already in the cache so we just update first update the value also called update function here remember remove it from the current position first and then add it to the head it's because when we get the atom we use the atom so we have to update and move it to the head finally if we exist the capacity we need to remove the lru atom which is the tail we can get it by dummy tail.pre dummy tail.pre dummy tail.pre we call remove function to remove it from the tail don't forget also remove it from the map and decrease the count one thing to note here is whenever we create a node and add it to the list we also added to the map and increased account whenever we remove a node from the list we also remove it from the map and decrease the count next let's verify the solution on lead code first the node class then the dummy head and tail then the add function the remove function the update function the lru cache where we initialize everything then the get function finally the put function we run the code it's accepted then we submit the code it's also accepted finally let's review the key points again first we use the relative position of the node in the links list to mark our u atom from the left to right is from the most recently to the least recently used ones then we use a hash map to make sure the get function is o1 and use a double linked list to make the put function is also a 1. finally to avoid boundary nodes situation we use a dummy head and dummy tail alright guys here's all i have for you today if you enjoy the video please give it a thumbs up and subscribe the channel i'm stacy thanks for watching i'll see you in my next video | LRU Cache | lru-cache | Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Medium | 460,588,604,1903 |
142 | Most of the defeats will be good, they will be dry in this, they will have learned a lot, they must have been doing as I was telling, then definitely there will be a lot of good motivation and confidence in them. When Bigg Boss, I have watched many editions of Bigg Boss and have watched many series till now. And whatsapp questions are still going on, many missions are going on, tickets are coming, now we are waiting for the liquid water level, I have been on many good opportunities, friend, I have always gone, whenever you feel that brother, I am not getting confidence. You look at my lips in the topic, I guarantee that you will also get confidence, this question will be asked of you and you will become so big, do you think anything about how to approach this position, okay on any particular topic, today we will talk. Less all cutlet relief, like every time I would say that before doing something important, the most important thing is to watch the impress videos, friend, the sequence plays a very important role, we feel that we know, we should be riders, the topic is known but it is not there. Which is a gradual sequence, while leveling up, you gain confidence in a particular topic and you also feel like stopping videos, it is okay to interact well with those data systems, so please don't stress that much. The question is not being asked, the reason for this is that you are making its sequence, okay, for this question, I will be able to do it, the question is much better and it is quite good, okay, look, the question should be seen in the forests, you should be able to do it in one night, if you have followed my example. If you watch the video of Hansi, when Ansh asks advanced questions about verification, it starts reducing by two-three liters. questions about verification, it starts reducing by two-three liters. questions about verification, it starts reducing by two-three liters. Okay, then we have to think about how to drive, like use something, such questions are the first button Italy. I am going to tell you about its 28 nutrition, a new approach and a better solution which is an expert interview from Italy to know the better solution but officer, so I am asking that you must have attended and you are not being deceitful, friend, I do it every time in the videos. What do I say, children, why do you say sent money and define, I feel that you are doing your work, so please do not develop and if you learn by speaking the truth, you will move ahead in life, this is my belief, okay, so now let's talk, what is the question? He is saying, friends, read the question carefully. You will search for the pictures and videos of this question. This is a very famous question, you will find it everywhere, it is not that you will only find a button or a retailer, I will get it done for you, I guarantee this. Why am I? Learn to do what I am saying in development. If it is okay then if you want to be successful then understand that the first question is whether you have given yourself a clean chit, it is not necessary whether it is cyclical, whether the cycle is present in it or not. Let's know its cycle percentage, so where is the cycle bagging happening, we have to return it like it should come after then, in normal which is liquid, it should be brought last but do not tap it has returned from someone's back. If you point a note to any list, then which note is that note? Two to two, we are the blacksmith, the answer is okay, this gives the treatment of Bagiya 320, so off course, here the list is not the President, so please, it is not the President, we are simple. Will return means that when cycle is not ready, sorry, it is not cycle ready, I don't understand, nor will I liter, okay and if there is cycle mode, then where cycle is being initiated, if we start reading on this from the question, we will see that after coming here, we will return this. The motorcycle is starting. Okay, so front this note to us. Basically, return this note. By combining these questions till the last, we have seen how to find out the loop which is the cycle in the link list. I will go to find out whether it is a cycle or not but if it is a cycle then find out from where it starts. Maratha step is fine. Let us understand against it whether you call it score live approach or did you do basic approach? Have a little brain. What comes in it brother, why don't we do the work, we start doing liquid reverse and maintain an unordered set, item like notes, serial date will come, note will go, it means that whatever note we have made triables, we put it in the set. It is fine and whenever we travel, we will check if it is not present or not, if it is present then we will return it is simple, many people did not understand, can I tell you something, what are you doing, if I reverse it, start it like this current is fine. If it is the first Jatin printer, otherwise we will set it in then we will come to this tree two. Okay, if it is 2%, no, we will insert toe, then we will is 2%, no, we will insert toe, then we will is 2%, no, we will insert toe, then we will go, if there is zero percent on this, no, if it is not zero percent, then we will set whatever is there, then it is - Dr. If there is a percentage, then we will set it abroad, is - Dr. If there is a percentage, then we will set it abroad, is - Dr. If there is a percentage, then we will set it abroad, then where will the contra vouchers be taken to those people, but 2%, yes, but we will return it to the center, because those people, but 2%, yes, but we will return it to the center, because those people, but 2%, yes, but we will return it to the center, because now the ultimate treasure was on tap, but it was pointed back on some dua and note where it Have pointed our entry point stitch points so list open the calorie cycle app it is starting we have returned so simple what is the problem what is that it is taking up the space of off these attacks okay don't we know that the space is not We have started development and we know that in one loop there are drivers in the form of fennel and seven drivers. If I fold it and tell you, look at the code above, look at the code, it is simple, we have maintained a set of things in an order. Kind of list note is ok about this address we will maintain another address we will maintain vitamin abuse and acquits can be done by going to 4 percent on any note on the address like this song that was we will maintain one address settle we People start the list by adding notes from one current to another and keep it off file until the current is not equal to null. What do you say brother? If cycles were prevented then unlimited internet times group would run but it will not work. Hmm, driver will check where. But we got a note there, we will break it, check this play, a hum episode, this straight hona, sorry status waali to a fat dot n subscribe that current president is not equal to set dot and jiso nahi pata yaar hum log abhay singh mein travels How to do this, you are fitting the signal, respect in one, but the time complexity is not increasing anything, just go to one off and hit the space and we will get this button, we will put it here but the current that we Received the mails, if not received then what will we do? Will we set the cotton shirt? Make the current simple and this is the end of all the last matters. In the end, this cycle was not even a percentage, so what will we do? Will we return it? Make waves with it and then And here the spelling of installed is shirt will be the first thing and the second thing here is one thing and whenever this time it will not work we will fly away what to do in this that the current has to be made to Mumbai then the next of the current is not such a kidnapper. Just submit and the real submit button will appear. This is not the solution which they want. We don't want this. We want this. They will ask in the bedroom interview. Friend, you should practice for open space, then we will get stuck. Then comes 1 liter. Good approach which you should know is that play on the album, decide a little, you will get a logical formula, play on it, open and look at it, then based approach is best in lava, to understand the meaning, you need focus and you need a little more tension, light submit, fly. You will have to keep some tips, then I will explain it in one go and you will also understand in one go, but carefully catch one of my WhatsApp, what are you trying to say, ok, let's give our input here, ok, I have given you a look here. And this is the current that we have to note that Aman is a WhatsApp, we will understand the concept, we will do 11 mathematical and depression, we will decide according to that, Pumik should be next or mukarna c example boy 320 - 56 and here the actual is placed above, sure, there is no - 56 and here the actual is placed above, sure, there is no - 56 and here the actual is placed above, sure, there is no problem here. But in case of any problem, now slowly I will understand from here I have given you a head, okay let's call this entry point our deep entry point from where our cycle is starting and a meeting point, well let's say meeting point. So remember, whenever in the loop, we used to point out whether the cycle percentage is in a list or not, make 12 points and make the password, the fast was doubly special, this computer is slow and where Indore fast is available. That point is called open meeting point, slow fast, if found, it means that yes, the cycle is percent, okay, then our first task will definitely be cycle recent, but if it is not told that the cycle will be ready, then definitely 239 points question that you are not in such a situation. Return where there is no cycle entry to the cycle stand. That's why we have to find the thing. Is the cycle student or not? So the student was found and at this point we found out that both the slow and pass point are of 2 minutes. Okay, now look carefully. Understanding Letter Yes, this time is wasted, it is here and this is the entry point, call this distance open and album is okay, this is the entry point, the cycle is starting here and this is the meeting point, call that distance and turn it is okay, even then it is not enough, that's it. To increase your blood, it has been said that understand it easily, you will understand it easily, okay, and the breast left now is from Ultimate 500 to this is a seen cycle, okay, so this is from the meeting point till here, but 3.32 and China point. From till but 3.32 and China point. From till but 3.32 and China point. From till this is our distance back tell it to next ok divide once again laugh a distance what happened to us this distance is done album is ok from entry point to this is the meeting point this is our end to Of course, this loop is fine and this loop is basically a loop, it is circle president, it means a circular thing is percent because the ultimate loop is made, it is okay, if it is seen, then it is zero, if you are made to feel the loop turning thing, then - 45 and 6 more. thing, then - 45 and 6 more. thing, then - 45 and 6 more. Sorry sex 209 hai six ok and this three and two nt true president ok so if you are on this route then take from zero the length from this entry point to the meeting point which you are considering as belt and the arrest which is saved ok What is left is 560 but this is completely fine till here Disturb from here, Ayub is able to understand that I am talking about distance, now we have a similarity with him, okay this is clear now understand carefully here if we If we come to know about the album then we will travel the Alwar distance with our heads and reach the entry point. Our answer will come. Our motto is that if we come to know about the album then it will be fine. Meaning that we got the Android number, why Vikas Judge Head Dept. We have to tell you, we will type the Selva distance and our entry point will come, how will we do what will we do, everything will be understood by WhatsApp, now see the distance which was traveled slowly, the actual travels that are here. Station, place, exam, this is the meeting point here and this is the point here, it has started like this, go away, then you can say the distance, go away, but in between, it can happen that many times circular rotation. If we have done circular rotation many times, then we can say that this point of plus two, this point and this entry point is fine and this is our meeting and this is ours, how will the first fast work, first fast will work like this, Albert Shift. What did you do, you started this rotation, circled one circle, circled 2 circles, circled three circles lost, I don't know and then in the last or when you completed so many circles, then came here in the last and then in the last came here, the meeting point of the ultimate limit. But alto also went extra, so album plus ultra went extra plus and times what we can say from Alp to plus next because what became the parameter of the circle, what became arrow alto and this arrest bus is running in the circle considering it as an exam. To alto bana aur x bana to end times end to plus To cash or understand again, I am ready for the constitution again. See this add, this is the entry point, this is the meeting point and this rest which is left is basically a circle, if seen half circle then exam and this rest is this thing, this is a circle, okay. This is on L1, this help to take away your travels, this travels, that's the only thing, hit one Ravana, okay, then during, hit again, hit install, and then hit one further four rounds, and then went here, but ultimately the meeting point. Then he came back here fast and then he came here and got it so what can we say album plus and times and two plus two This is the thing I wrote here, distance traveled by road, distance of life, fast, it is ok, I definitely understood, it takes a little understanding, but you understand, it is not pocket science, ok, till now, definitely fast, double sports, welcome to Shlok Tamasha, what can we give? The distance traveled in the time interval is slow center middle two times if the distance traveled source is equal to the fast one sure student look at your shirt when you will solve this question will come ok then how to activate I assumed that the value of one is one Due to the value of the hand, you are able to turn the canter that fast, only one driver has done only one circular revolution, which is fine but if the office has done one driver, then we get the eggs Hanumangarh on two-three reversals, as far as get the eggs Hanumangarh on two-three reversals, as far as get the eggs Hanumangarh on two-three reversals, as far as I know. Address and that very big penis Saurabh Pandey5 differences, the diversion Dabangg is found in it, but to make you understand easily, I have mentioned here their value as one, there is no other significance in it, only then you will get equal to the album of X, okay Ultimately, now you could have written in Active and Customs also, it is not a big deal, but I asked for 100 wins to get one for the travels, completed the revolution and met him at the Awadhi meeting point. You may be the person. Declared that if the butt on you is green to explain then you can update your can with this C interpretation has come out very good here that your value of And after eliminating this fast, how much is So what do we do, let's start with health, it's okay and keep going but I don't know where to stop, we know that we do n't stop after coming to the album, but we don't know how good the album is, now we We can do this and what do we do by coming to Run one in the same speed, here we make Katrina Vary, run both in semi support and where both meet, that is our entry point, this is the complete conclusion friend, it may have gone a bit long but you definitely understood digital. If you understand what is going on then please comment and tell me whether you have really understood what you were trying to explain, okay, the distance of the ad from the album and the same entry point and the entry point from the slow place where both met. The distance of both the distances are equal, why the development should be seen from people and we have kept this entry point the same, this is our Run it on semi-skilled and where Hawaii is our Run it on semi-skilled and where Hawaii is our Run it on semi-skilled and where Hawaii is our entry point for both, don't set it. You have understood, okay, it had nothing to do with it. If I try to do its final traversal, then understand the final journey. We should first set the meeting point. So it's slow, it's fast, okay, both address cases are running, so in the first traversal, it's people and it went fast. In the second traversal, it's done and it's fast. In the third traversal, it's slow and it's one or two, it's fast. Came here again, ok, went slow in Central, went here and fast went here, meeting point for Khelo is ok and what we did is we typed what is this distance from the meeting point, if we have covered that much distance then go slow and connect here. They make points, they make points different from Titan, entry is fine, let's run these two points explosively, that is, entry is equal to entry's next and slow is equal to slowa, next is fine Anil, as long as entry is not equal to slow, we people. Okay, and in the end we will fly that brother, we have found our answer, I think you are understanding it, let's do this by looking at the question, I have to write the entire Ramayana to explain it to you people, only then I have not understood the thing. If you find out, if you understand what is going on, then please tell me that it really makes sense, okay, I have made a list of things, let me explain the very simple process, because already the video is long, Shoaib, equal head, okay. Fast is equal to head and attraction in trees that NTR Hawaii = head social norms do that NTR Hawaii = head social norms do that NTR Hawaii = head social norms do oil and run oil that fast do next do the work first brother that fast do next9 2222 that municipality has to point that loop is recent that from this Tourists can apply Fedor, if it doesn't bring equal amount then brother, just return it, why tap because of the question of doing sanitizers, now we have tested the traversal and checked that it made people run it at slow speed and made Next9 and Fast run it for AIDS patients. Run fast and check this, if slow is equal to slow, it means we have found a loop, we have got a list, now what will we do, we will start traversal till the entry is not equal to slow, what will we do, we will run slow. We will run the end entry at slow speed, anti larva entries are fine from the stomach and at the end we will return the media slowly and if nothing happens then we will return it as tap, I submit it, send it after wearing it is necessary, maybe there is something wrong in the court. If sentence becomes all anything then sentence ra jadiya such expect development will be slow star fast here and there will be interest here if understanding is declaring when scooter commission understood that ride's in- scooter commission understood that ride's in- scooter commission understood that ride's in- depth record logic pdf all will be available you understand focus Do a very good circle, I am telling you, I enjoyed it, I liked teaching, please tell me if you understand, please do me some good by sharing it with your friends, friend, share it in the college, congratulations brother, I think you have read well. So there is no harm in sharing, now I do Chrome Hero, see you next fake is still there MP3 | 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 |
210 | hello there today I'm looking at the question 210 course a schedule 2 which can potentially be a follow-up to can potentially be a follow-up to can potentially be a follow-up to question 207 course is scheduled for this one 207 all the question is asking is about feasibility so we want to determine whether it's true or false that we can finish the task described by the problem here but for this potential follow-up question 210 not only that we follow-up question 210 not only that we follow-up question 210 not only that we have to determine this feasibility if it's a feasible to solve this problem we have to return at least one of the whole circuit so that's why this is can potentially be a follow-up or to that potentially be a follow-up or to that potentially be a follow-up or to that question but you really don't need to know 207 - in order to understand 210 to know 207 - in order to understand 210 to know 207 - in order to understand 210 and actually I'm going to do a different solution compared to my last video so you can search for that video if you're interested in so let's read the task so we have to take in courses in total maybe - either to graduate or get a maybe - either to graduate or get a maybe - either to graduate or get a certificate or something and I guess just for the convenience that the course are labeled from 0 to M minus 1 and as with real life courses they have prerequisites so for example if we want to take for 0 we first have to take course 1 and this kind of prerequisites relationship is expressed as pairs of numbers so the core is indicated by the first number in the pair as depends on the finishing of the course described by the indicated by the second integer in the pair and as input in our question we're going to be given the two things the total of courses that's the end and also the list of a prerequisite pairs so we have a edge list inputs to us so if we treat the courses of nodes this input is basically edge list and yeah the question is asking us to determine is it feasible for us to finish all the courses and if we can do so it's asking for a one of the possible orders we take the courses so that's the question so you're just going to talk about the feasibility very briefly first when it's when is it gonna be impossible for us to finish all the courses the only case is that there is a cycle so of course there will depends on course one the course one depends on course zero therefore you couldn't really finish any one of those so that's the only case where it's impossible to finish part of course otherwise we can I just try to finish as many finish all the prerequisites for a class and then that course will be available to us so we can take that for any course in this system in this program as long as there is no cycle we can eventually finish all of them so that can lead to potentially multiple different orders but as long as there is no cycle we can at least define a final order so two things that just briefly touched by my description about how to reasoning through here is that the code has to be able to handle two things one is to detect cycles that's the indication for if there are is impossible or not the other thing is we want the correct order which is basically just taking all the available course and that's currently available to us and but keeping an eye on the course that to have prerequisites once we finish the prerequisites for one particular course that has some prerequisites the course become available to us as well so that values to a very simple bffs search kind of a solution so I'm just going to show the graph here as well as real college courses the courses can you know how levels usually the level is usually the level of course it depends on you have a prerequisite about so here I have three different level of course and you can see that course 201 approve revisit 100 - yeah you approve revisit 100 - yeah you approve revisit 100 - yeah you know maybe 101 is linear algebra 102 is probability series and 201 can be maybe machine learning 301 might be deep learning sale so you have this kind of a layered on leveled course assistants and if we do have cycles 101 depends on - 1 2 or depends on 101 then depends on - 1 2 or depends on 101 then depends on - 1 2 or depends on 101 then there's no way that we can finish this otherwise the strategy is going to be a level by level you know the BFS search so the way we do that is to first find out all the courses that we can take so those courses without any prerequisite and then just they're gonna take the main sequence whatever we've finished our course the thing that we want to do is to look at the course that depends on it so we can follow this a prerequisite kind of you know the follow up links so we can convert this from the convert the edge list into this kind of format at all the edges and looking for the course that depends on the one that we have just a finished and since that we have already taken that we can decrement the number of prerequisites that course has so in this example once we finish 101 we're going to decrement this contour by this pre records number of a prerequisite by one and mark 101 has taken the second course we take it's going to be one or two so we will move this from this can take so as you can see that were popping from the left it's going to be a cue move that - taken and going to be a cue move that - taken and going to be a cue move that - taken and the same time we're going to decrement the count for the number of prerequisites for pause - or what so prerequisites for pause - or what so prerequisites for pause - or what so once this counter you know number for pro requisites reduced to zero that's the first time we're going to append this to the back of the queue so that's just the simply meaning that after we finish all those prerequisites we can now take 2:01 I'm just going to keep resuming 2:01 I'm just going to keep resuming 2:01 I'm just going to keep resuming this process keep continuing this process take the first available course and decrement the count for the course that depends on it and when they come when we finish we satisfied all the prerequisites requirements for one of the courts we push it back to the queue and basically just going to repeat this process until we run out of finish all the course that's the time when the queue will become empty after we finish 2:05 we can decrement the counter for 2:05 we can decrement the counter for 2:05 we can decrement the counter for the number of pre-recorded prerequisites the number of pre-recorded prerequisites the number of pre-recorded prerequisites for 301 and push it up at level two the queue immediately after that we're going to finish it and this is the terminal course and after we move that onto taken or pretty much you know finished all the courses and also come up with in order to actually take in a lot of course in a sequence so the so this is pretty much an animation about how we kind of do it BFS search to solve this to do this we need two things one is the out edge so instead of the course depends on which one is going to be the course it's a prerequisite for another course so we're going to convert the edge list into this kind of convert that the edge list into a GCSE list which is going to be the course and it's a follow-up course and it's a follow-up course and it's a follow-up question courses in that kind of format so that we can follow the links to decrement the counter for that so the contrary here and the number of prerequisites is basically the in degrees for every node so we need two things when this edge list outer edges and the other thing is the in degrees and with that we're just going to do the BFF search the order that we put the course on to this data structure this container is going to be the it's going to be the order we take all the courses so if there are a kind of a cycle so if there are cycle that means since like let me just try to illustrate why this solution also guards against the cycles so if there are cycles that the for example the course is free to move one is dependence we over by maybe screwed up someone designed a curriculum the screwed up this dependency then after we finished 101 and one or two the course 201 will still have one course it has a prerequisite so this tool one would never be moved to taken so the lens of this taken will be less than n so in the end after we that was the BFS search if the resulting array has a lens that's less than and that means we still have course we couldn't finish because of this cycle dependency so that pretty much summarizes a how we going to solve to 210 but using this BFS search I think this is called Kai's origin for topological orderings but you don't you really don't need that it's pretty natural to think about this as a relate to this department to real life college you know curriculums you have different levels of course and just try to think about it naturally how you're going to choose your courses to fulfill your degree requirement you're going to do the lower level course first and look at keep an eye on what you can potentially take in the next semester once you finish and all the prerequisite from one of the course you can add that course into your consideration about the course you're going to take next so it's a very natural intuition about applying the FS search on this problem so with that analysis I'm just gonna cut this thing up so before we actually curl let's resumed habit that I kind of forgot in the past months to analyze the time and space analysis for the time and that was time for the time complexity basically the thing we want to do is to convert the edge list into not Angeles your edge list can convert the edge list into the outer edges so from the pairs of numbers into from 101 I go leads to 201 it potentially leads to some other courses so if you have errors of that so it's going to be a list of lists and that takes the time corresponding to the number of edges and it takes up the space of corresponding to the number of edges the second thing is to come to the in degree for every node we can do that in a same time as we convert the edge list for doing that the time is going to be equal to the number of edges the space is going to be pretty much a notating every node with the number so it's going to be taking the number of the space is going to be the same with number of nodes so that's the processing it's going to be linear with respect to the number of edges and taking up a space that's V Plus E and once we have that we can do BFS search so to do BFS search we're going to visit every node exactly one time so move that from can take to taken and so that the time complexity is basically the number of nodes plus number of edges yeah so that's that was that I can start code so we're going to do this is going to do out edges so it's gonna be a dictionary or array it should be fine because we have this end we notice in ahead of time and the second thing is in degrees so that's the number of Records the course we haven't finished yet for every course so let's also use a list here so we're going to be 0 for every course in the beginning then we're gonna process the do some processing of the graph so the dependency is that for the actual course and its prerequisite so of course prerequisites let's be more readable we're gonna do two things one is to populate this outer edges so the prerequisite we'll be adding this courses that is a follow up of course and then we incremented the degree in degree counter for the course by one so this cause have one more of course that we identified as a prerequisite so this is the graph processing so that's that then the thing is now this to do BFS search feasibility as well as earlier so we do two things at the same time so we gotta have a queue that's the courses we can take in the beginning so that's for cars and the number of prerequisites we enumerate over the in degrees so we're going to come up with the course number and the number of prerequisites we're gonna filter that to include only those course we can take right away so the course that has the zero four represents so that's going to be let's be a little more readable so if the course has no prerequisites so we're going to start with those as that in the beginning and I think I need a queue attack for this list the pop for left is too expensive and then it's gonna be the BFF search so it's going to be of course equal to popping from first available from the left let's have something like taken which is back as well do we need it to be a deck let's look at the graph I don't need to be a deck it can just be a staff so we push on to the end of it so whenever we pop up course off the thing we're going to do is to add that to taken and then once we're taking it we look at the chords that depends on it and decrement account for that so we got a decrement the count if the course is if we have finished or the prerequisite for this course that's the time we can move this next course onto the available course to us so that's that and in the end we just return to taken if it's if it has the same lines as the number of courses so we need to take otherwise we'll return what's required by the problem empty array yeah so that's this problem I think let me try to run this code it's working in this case let me try if it can detect the cycles okay 0 1 so we will never be able to finish either one of those courses it's returning after space empty array as well and one more course what depends on 0 depends on two maybe one depends on two as well so we can still finish it's just that we have to finish to first and then 0 then 1 so that looks ok so we should work yeah it's working so this is the BFS search to solve this question 210 and it's all its it can also be used to solve 207 as well all you need to do is to you know return this as a boolean so you will be able to solve this a feasibility problem if you're interested in checking about the DFS search solution to solve this bottom you can look at the video to 107 that and I had potentially I could put a link there I don't know if I will really do that but it's slightly more complicated it's more space efficient and it's also easily adaptable for to solve this question so let me actually just do that go ahead and do that so just copy the solution front two hundred oh seven maybe as a real interview settings you this question do come up as a follow up when you just need to multiply the prior solution and try to adapter to solve this new one yeah so the thing that we want to do is to also keep a vector sorry I'm sorry about the switch in the languages but here basically is that I'm going to have something that keep track of order where I take courses and it's push back and here I'm just gonna do if I do have cycles that means it's not possible I will return the empty list otherwise I want to do the reverse because in DFS search where you're pushing we append the course in the back order so instead of doing this 101 102 105 if we do DFS search get rid of this it's basically try to go as deep as possible and once we reach that end that means that course has to be taking in the last step so we push that on to the stack but in the end we have to reverse that so it's going to be to 301 201 and 101 102 205 and 105 something like that in the order so that we have to flip the order in the reverse order to get to the trouser so let's see if it works it's working okay yeah so that's uh that's the DFS surge solution if you're interested in knowing the detail the reasonings and some illustration about how this works you can check out my video about 207 but forth personally I do think that the BFS surge solution I showed here is more intuitively easy to understand even though it's more demanding because you requires the more processing slightly a little bit more processing to get the ink degrees but it's very intuitive to understand the BFS search solution to this topological sort problem now so that's it for today | Course Schedule II | course-schedule-ii | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** \[0,1\]
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\].
**Example 2:**
**Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\]
**Output:** \[0,2,1,3\]
**Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\].
**Example 3:**
**Input:** numCourses = 1, prerequisites = \[\]
**Output:** \[0\]
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* `ai != bi`
* All the pairs `[ai, bi]` are **distinct**. | This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS. | Depth-First Search,Breadth-First Search,Graph,Topological Sort | Medium | 207,269,310,444,630,1101,2220 |
438 | okay so today's second question is 438 find or anagram in a string so anagram is basically a string with its characters shuffled around randomly shuffled around so given a string s and then dung every string P what we need to do is find the starting indices of peas and grams in s so i guess s should be at least a longer than P otherwise we wouldn't be find a permutation of P and s the string consists of lowercase English letters only so that we don't need to worry about some world case letters I guess and the lens of both strings SMP will be reasonably short the orders of the opera doesn't matter as long as they are the correct in starting indices the example here we have c b a b lb a CD the string p is a pc so when you'll find ABC AC b bi c bc AC ABC ba in s and return their starting index so that's a cba starting with index 0 + so that's a cba starting with index 0 + so that's a cba starting with index 0 + bi c start with the index 6 the second example I have a bi be the string psab so anytime that we see a b or PA they are all valid anagram of a be here so there are three such substrings the index in this is a 0 1 & 2 so we're index in this is a 0 1 & 2 so we're index in this is a 0 1 & 2 so we're really quick and easy solution is to create all the permutations of p and just iterating over as ones checking the sub strings of the same size same lens as p the lens of p and checking whether that substring is in the set of permutation if it's a in there we just pen down starting indices to the output array after we doing this one pass will be done the problem is that the chicken is actually find it's a linear and that the lookups is going to be constant but the problem is going to be creating all the permutations for P so I think that's a factorial in terms of time and space complexity yeah absolutely that's not idea if the peatlands up is large if we somehow know that p is relatively short like a 3/4 I guess it's doable and short like a 3/4 I guess it's doable and short like a 3/4 I guess it's doable and it won't be fast but since there's no guarantee how long P is we only know that it's not larger than this 20 solving something so yeah so you could be in a very time-consuming to could be in a very time-consuming to could be in a very time-consuming to creating all the permutations but that's the volatile solution at least valid the first solution then we begin to realize that to actually determine whether CBA is a permutation of ABC all we need to do is basically looking at the frequency count for each characters so we have 1a 1b 1c in the requirements here and CBA has 1 C 1 py so the matches are each other then it must be a permutation of P in the stream P here so this will reduce the so instead of checking whether this substring a seeing a in the set of all the permutations we only we compare the frequency count of the characters which they require the frequency count so the chicken will become this and we not only need to create a permutation of P so just in terms of this solution in time in terms of time and space complexity we will need a store the frequency count for the characters in P and the frequency count of the sub strings in s so these is since we are only working with lowercase C lowercase English letters it's a maximum to be order of 26 so we can argue that the spaces for this to hashmaps is going to be constant and the time complexity is order of the length of P to create that hash map for P and for s it's a little bit complicated so if at each location we create a frequency counter from scratch then because we have an S location length of s location to go through and for each of those locations we creating a hash map frequency count of out of NP length of P lens sub C sub strings from there so it will be these two lens multiplied together but that would be doing a lot of redundant work because when we look at the CBA and BAE we if we do that we calculated the frequency for B and a twice once for in each window so we don't actually need to do this all we have to do is to maintain a frequency count window and once we move to the next location we try to decrement the exiting character and increment to the frequency call for the new entering through character and yet another optimization we can do is to only keep track of the frequency count of the characters in the that's required that's in P because anything that's not in P we don't need to worry about that frequency count so with all this the time complexity for the you know moving window freaks account checking marching method it's gonna be linear with respect to this two strings lines added up and together and the space complexity is constant so it's not analysis let's code this question now so the first thing we do is to handle the edge case about the spring ass is actually shorter than P so in that case we couldn't find any permutation of PS in that case we return the empty list with no index that indices in it so the lens of P is something that we grab here so make the code a bit cleaner the required frequency count and we create this out of the string P so with the counter we basically just counting the number of occurrence for each characters in P and we get in our first a window by the first sub-sub stringing s that's the first sub-sub stringing s that's the first sub-sub stringing s that's the same lens as P it's another counter here but the content in here is actually the characters that appears in P so because anything that's not the NP we don't need to worry about so that's the first n characters in s as long as that it's a required character do this you do the initialization early on then we do our very simple we're raring doing our initial comparison but it is to frequency count is actually the same if that's the case we append zero to the solution here so much type of today after the very initial window we just try to numerate the characters after that one by one and trying to update the window so this character here is the entering one and the exiting one is I - and again one and the exiting one is I - and again one and the exiting one is I - and again we do this checking here so that if it's like characters like II it's not in ABC we don't need to do anything to the window comparison we'll just copy this mouse is drifting today the location is going to be a minus n plus one so looking at the here yeah so the location we're gonna get this second six here there's gonna be seven and eight actually 8 so 8 minus 3 and plus 1 is 6 yep so that's the that's a little bit mass here to make sure that we get the starting index rather than the ending index so this will be the code for this question let me see if we have any problems the required frequency the initial window that's the characters that's in frequency the first 10 letters that's in the frequency required frequency and then we try to expand the window not react Spanish shift of the window one location at the time we update the window is there an incoming one and try to decrement the frequency for the exiting character after we updating the window we do this checking again and make sure that we actually add the starting index for that window if it's a anagram for the required P here in the end we'll turn the solution it looks good to me so now let's try to submit this okay it's working but a little slow so but based on the analysis this should be you know linear in time and constantly in space | Find All Anagrams in a String | find-all-anagrams-in-a-string | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters. | null | Hash Table,String,Sliding Window | Medium | 242,567 |
160 | all right this lead code question is called intersection of two linked lists it says write a program to find the node at which the intersection of two singly linked lists begins for example the following two linked lists so here we have one and here we have another they begin to intersect at node c1 then they give us another example this is one linked list this is another one and it's pretty clear that they intersect at this node another example first linked list second one they intersect right here we don't have to read all this now but you can read it on your own later here's an edge case we have one linked list and a second one and they don't intersect anywhere and then it says if the two linked lists have no intersections at all like we just saw return null and the linked lists must retain their original structure after the function returns you may assume there are no cycles anywhere in the entire linked structure and your code should preferably run an O of n time which ours will and use only o of one memory which applies to our solution also all right so if the length of these two linked lists were the same this would be pretty easy right all we'd have to do is start them off at the same place this will be P 1 and this will be P 2 and you would just compare if they're the same node or are they the same node at this point no they're not so you just move each of them up one are they the same note at this point yes they are so they do intersect but the problem comes in when the linked lists are different lengths so let's say instead of this first linked list being a X Y it's C D ax Y now what we're going to see is that when you start them off at the same place they're gonna end at different times so if you look at P 2 is 2 nodes ahead of P 1 so it's gonna get to the end of the linked list and only 2 steps but P 1 is gonna take 1 2 3 4 steps to get to the end so how can we make them point to the same nodes at the same time the way we're gonna do this is when P 2 finishes its linked list it will now start over at the beginning of the first linked list and vice versa when P 1 finishes the end of its linked list it will then reset to the beginning of the second linked list I'll show you what I mean so just P 1 equal P 2 no because see doesn't equal B so we advance them each by one alright are they equal now no so we'll advance them both by 1 again are they the same no notice where P 2 was and where it's going to be this whole time P 2 has been traversing the second linked list but at this step since it's gotten to the end of its linked list we're going to put it at the beginning of the first linked list all right so we've moved this up are they the same now no move them up again are they the same now No so pay attention to p1 now because it's about to get to the end of its length list remember when it gets to the end of its linked list it has to be reset to the head of the other linked list so p1 even though it's been traversing the first linked list this whole time now will put it to the head of the second linked list and will advance p2 alright now let's take a step back where are we p2 and p1 are successfully on the same node almost like what we had before when it was just like this so now all we have to do is keep advancing them forward and see if they end up on the same node we advanced p2 by 1 and we advance p1 by 1 and look at that they did intersect so using this technique we're able to negate the fact that the linked list are 2 different lengths and get them to be comparing the same node at the same time alright let's get to the code what lead code has given us is a function called get intersection node which accepts head a and head B head a is the first link list and head B is the second linked list so the first thing we can do is if either of these linked lists is null then obviously there is no intersection point so we can just return null at that point so if head a is null or head B is null we'll just return null and remember we need pointers pointing to each linked list so we'll say let pointer 1 equals head a and let pointer to equal head B okay now we need a while loop that's going to loop over every node in each linked list so we'll say while pointer one doesn't equal pointer to this is where our logic would go but let's say they are equal we can just return either pointer they're on the same node so either pointer would work alright so let's just jump back into the while loop all right so at this point pointer one is here and pointer 2 is here all right so we know they're not equal so we can just advance them so we'll say pointer 1 equals pointer 1 dot next and pointer 2 equals pointer Chui next that would look like this printer 2 will now be on X the pointer 1 will now be on deep alright so it would go to the next loop are they the same no so we'd events again and it would go to the next while loop and no it advanced again but notice where the second pointer is it's actually pointing at null so now we have to cover this case in our while loop will say if pointer one is null we'll just need to reassign it to the head of the other node so pointer 1 equals head of B and similarly if pointer 2 is null we will just need to reassign it to the head of a alright so now when that while loop starts P 2 will be reassigned to the head of the first linked list and then we'll advance P 1 as usual are they the same no so we'll advance them again but now notice that P 1 is on null so we'll reassign it to the second linked list in advance P 2 now if we notice they're at the same point in their respective linked lists so now when you advance them we'll be doing a fair comparison so are they on the same node yes they are so we'll add an if statement for that one if pointer 1 is the same as pointer to what do we need to do we'll just return pointer 1 again we can return either one because they're pointing to the same node but we'll just return pointer 1 all right so let's run the code all right before I hit submit I just want to quickly go over how this code works when there is no intersection so I'll just quickly do that let's say this is p1 this is p2 it checks if they're the same no they're not are they the same now no they're not p2 is at null so now this gets reset to here this gets put to the next node which is null because of that it gets reset to the head of the second linked list and this gets moved up okay so now they're at the same point in the nodes so we'll advance this are they the same no advance this in advance this now notice that they're both pointing to null if we look at line 26 it says if pointer 1 and pointer 2 are both the same we return pointer 1 well pointer 1 is pointing to null so that would be our answer looks good and will submit all right our solution was faster than about 77% of other JavaScript about 77% of other JavaScript about 77% of other JavaScript submissions as usual decode and written explanation are linked down below if you liked the video please give it a like and subscribe to the channel see you next time | Intersection of Two Linked Lists | intersection-of-two-linked-lists | Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory? | null | Hash Table,Linked List,Two Pointers | Easy | 599 |
1,992 | welcome back everyone we're going to be solving leeco in 1992 find all groups of Farmland so we're given a zero indexed M by n binary Matrix called land where zero represents a hectare of forested land and a one represents a hectare of farmland to keep the land organized there are designated rectangular areas of hectares that consist entirely of Farmland these rectangular areas are called groups no two groups are adjacent meaning farmland and one group is not four directionally adjacent to another Farmland in a different group land can root can be represented by a coordinate system where the top left corner of land is 0 in the bottom right corner is M minus 1 n minus 1. we need to find the coordinates of the top left and bottom right corner of each group of farmland and a group of Farmland with the top left corner at r1c1 and the bottom right corner at R2 C2 is represented by a four length array of r1c1 R2 C2 they want us to return a 2d array containing the four length arrays described above for each group of Farmland in the land Matrix if there are no groups of Farmland we can just return an empty array okay so there's a lot to digest uh let's take a look at example one right they give us this grid here and we can see that there are two groups of farmland uh the first group being this singular uh land uh the singular group here in the top left corner and then this group of four ones in the bottom right corner so what we want to do is we want to iterate through our grid and whenever we run into a one right we're gonna start a breath first search and when we finish our breadth first search we are going to take the first coordinate that we came across which in this case would be zero and then we're going to take the last coordinate we came across in our breadth first search in this case for the top left corner it's still going to be zero we're going to take those row column Pairs and then append them to an array and then take that array and append it to a resulting output array so if we take a look at this group here right we'd get this row column pair of one right add it to our array we'd add all these other ones but that this would be the last one that we add to our array then we would just take the row column pair 1 and the row column pair of 2 add it to our output array and uh just return so like I said we're going to run breath first search so we'll say from uh collections import the DQ we are going to set up a q to be that DQ and we will also have a visited set and a resulting output okay now we need to iterate through every row column pair within our grid so we'll say 4 Row in range length of land and four column in range length of land zero what are we going to check we're going to check okay well if land of that row compare is equal to one and the row column pair is not in our visited set then we know we need to run breath first search so we can say Q that append the row column pair we're also going to initialize a farm object equal to an empty array right so whenever we run breadth first search we're going to take all these row column pairs that are ones add them onto our queue and continue our breath first okay now we can run our breath first so we'll say wow the length of our Q is not equal to zero we are going to grab the row column pair with Q to pop left the first thing we're going to do is add that pair to our visited set so we will say visited dot add the row column pair and we will also add that row column pair to our farm object so we'll say Farm dot append the row column pair now we need to check all of the adjacent squares so we need to if we're at the top left corner here we need to check the uh Square here so down one row but in the same column we also need to check if there is a row above us in the same column and we need to check in the same Row one column to the right and one column to the left so we can do that by saying okay well if uh rho is greater than or equal to zero and less than the length of our land actually this should be a row plus one right we need to check the adjacent squares not the current ones and uh the same thing for our column so our column has to be greater than or equal to zero and less than the length of our land zero we also need to check and make sure that this square is a one so we'll say and land of row plus one column is equal to one we also want to check and see if this row column pair is within our visited set so we'll say and row plus one a column in visited this should be not invisited and not and visited okay what do we want to do this is saying okay well the current square that we're at it is within our matrix it's inbounds right it's not off of our grid and it is a one and we have not come across the square before so what should we do well we need to append that row column pair to our queue and we should add that row column pair to our visited set so say visited dot add row plus one column now we need to do the same thing for the previous row the next column and the previous column so we're going to do this three more times so we'll copy this paste this here and we will grab all these and turn them to minuses so we can check the previous row now we want to check the next column so let's grab all of this we will delete that and now we want to add plus one to all of the C's so we'll say c all right now that's going to check the current row at the next column so we'll copy this and now we need to check the previous column at the current row so we will get all these and turn them to minuses okay after we have finished checking all of our adjacent squares appending them to our cues appending them to our farmlands right we've exited this while loop that means we have finished our breath first search so what should we do that means this Farm object is full of all of the row column pairs that have a one so it's a group of Farmland we have a group of Farmland what do we need to take well first we need to check is this a group of Farmland is it of length one so we'll say if the length of farm is equal to one if it is that means we're just going to append the row column pair to our resulting output array four times so we'll say res dot append the row column pair Farm zero one and do zero again zero and farm zero one all right that's for the case if we only have a single Square as our group of land now if we have more than a single Square right we're guaranteed that it's going to be if we take a look at the constraints the groups of Farmland are rectangular in shape so we know when we have this Farm object if it's greater than length one we can just do this uh res dot append but to get the first row column pair right the upper left hand corner it's always going to be 0 and 0 1. then all we have to do is grab the bottom right corner of our land and that is always going to be the very last row column pair we add on to our farm array so how do we get the very last item well we can just say Farm of negative one and the first element zero and then Farm negative one of one to grab that second element and that'll give us our row column pair for every uh group of land that is not one so after this after we exit all this we've done all this work we've finished the breadth first search and we've appended everything to our output array we can just return the resulting output array so let's run this and it does pass all three test cases so we'll submit perfect it does run so time and space complexity for this problem is going to be for both time and space it's going to be R times C right where we are traversing every row and column within our grid or our land array all right that'll do it for Lee code 1992. | Find All Groups of Farmland | sort-linked-list-already-sorted-using-absolute-values | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. | Linked List,Two Pointers,Sorting | Medium | 148 |
190 | Today we will solve the next problem of Blind 75, whose name is Reverse Bits. So first of all let's see its problem statement. Problem statement has given this reverse beat journey and we have to reverse its bits. Okay, so like this is an example of how. Let's take some small example. Yes, look like this, so if I listen to this number, sign interior, if I reverse the position of the bits of sign interior, if any, my position is i and my total length of d number is called this n. So my reverse position of it will be N-I, it will be correct, so N-I, it will be correct, so N-I, it will be correct, so if you look at it, if we reverse it in this, then this will become its final position, so what we have to do is we have to reverse it, one think, it will remain the same because here. But if you reverse the position of one and one, that is, the whole, only then it will become 10. We are a simple implementation because he has also told us that ours is that, so we know that if we build our one unsinged interior. So what do I have to do when I start, just go and set it at the N - I position in the number that I am trying to build set it at the N - I position in the number that I am trying to build set it at the N - I position in the number that I am trying to build and my N I know is always fixed which is 31 because the induction will start from zero, right. Let's try to write its code, meaning this question is not very difficult, I just have to go and set the bits of the numbers at n - or positions. Okay, so first of all, this is my result, which I want to start building. I will do it ok | 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 |
438 | Hello hi guys in this video we will question find all gram sunscreen gram hota agar subscribe meaning as I tell you babes page 232 koi aisi jesse sub character like video this has been done with this you will come only this and want and anything else would be dig IG TC Chandra is also there so I also got Shehzada still three two one two in the third house ok that's how many sub lions of one sandesh leo are there with other workers like it means so it is old source below Is that pattern system can be this source this meeting 119 tell this pattern in this so many union with first team first dealership which became soft of these boundaries I got you same bean one and same happened once more ABC and BSC with BSE Made in the hand of both during pregnancy, from there we have to write the starting index twice and how many times this has happened, then for this or else you can subscribe two from 60662 sub scanner. Okay, so this is Meghnad Chief Yagya and Thanda. There is a jhal, there are one or two in it, and this one, tell me how many, subscribe and there is one bar, now make the figure of the first four inside it, we will play the first four chords, it is romantic, the release one will be acquired, and okay, the first four. First make it, recognize it, then check the preparedness of the first one. If not, what will you do? If not, then what will you do? BBC One, good brother, this scene with Shivam is giving a b c and b c. People in Agra print this and share it with their friends like how much is there in the account and d1 Now if both of them have not started laughing then LYF is one thing, you too are completely heartbroken and One on 1431 282 is not a single customer, one square 140 one, you released tea and one more thing is you released your AC and gained only C, were staying there if you don't subscribe to 111111111111111 otherwise you would have slept inside it by doing so. Friends, if there is time, then it will be made now, it will be immersed in the slide of four, its map will be made and for four, inside all the patterns, what a great irony, the map will keep going and one pattern will be made. Okay, so let's create a ruckus on the first point. Absolutely. Zero oil day pattern laut loop whether I will make it of woman or patan, I don't have to do anything pattern, we need 125 runs laut is going on, so cotton is fortnite in front formation so cotton is fortnite in front formation so cotton is fortnite in front formation and in default sequence we will use quiet, we will use ghagra one. The frequency will increase so that the frequency is given in the exam. Now what do we have to do, Princess? The length of the pattern is not different from the option source, although the length of the pattern is not different from the line of the pattern, the thought must have come before Mr. Vaibhav and it was a cartoon film. Played that we will do this pattern source and this thinking is longer than Patan and picked up the cigarette and got into the thinking then we have made it in frequency like if we take 21 again then cover my till bigger mustard this ABC AIDS patient and this We had a baby BLC Palace Mudra Crush before this, subscribe my channel, so now what will we do, we have defeated that village here and earlier by the same length as you from here so that if it does not become bigger than 24 then 2 T20 Make a match, now see what should I do, Jaitley said, this is above, let's acquire this pattern on the lock link, we have worked from taglines for telling till small, we have come to the boil, hence students for telling, till we reach its end, then we these people Don't do it, now here I will do the Titan map and source equal at this time, if it is through, then we will print the system before and after returning, after which all our English is fitted, it is okay, what will I do to you, which ones? Unit less quantity of composition of C. If these two are equal then comment. Now wind, you subscribe to this leaf. Subscribe to the channel. Found an old C, which is not found to make one, then he will put it in front and lips will make it as much fat as milk powder. The character behind, see this, friends, if you are acquiring this then it will be for four Pichola because if the window keeps you commenting four then it will be released aapki bindi doggie that it has been schooled on this wire in this app, so we are running the route from here and If you stop from here, then when you release this wire, the neck of the pattern behind it, then when you do this, it will be released and B Jain, then it will be deleted and seven will be printed, Gemini Medical Store, then one square, one big subway game. And there was a brave lead, this one must be from Bhilwara, so you got it again, you got it in 2008, you got this ladder twice, appoint a tiger, subscribe, if you subscribe, please reduce it if it is too much, don't worry, you will be in front of this map. .com is a job vacancy - will be in front of this map. .com is a job vacancy - will be in front of this map. .com is a job vacancy - Wow, you should keep in mind that it will be in the last place, otherwise you have to do it outside the last use, here also you did not have to understand this, please explain it at this time, but first write the big compare function, okay compare. There are plus 2 house maps inside the function, one is till the time, both are the same in this disgusting affair, put the root in the key set at the same time and see if the other one has the same previous one inside it, I write it in the comparer, hmm pimple a public Traffic bullion that you foot that house map character vs teacher that one is information and don't hand first and move away from chapter vs Jai Hind guarantee when thinking you have Taken 3 that one's key put on the set and that chapter ch4 situated showroom do I milked this part of the map, so it's okay in time, so now I have to check, this chapter should be in the pattern, and if it is my own in any 1968, then I will deposit the pattern map daughter, now it thinks that the character is in the group. If you are not worried, then if it is not the source, I am not of the sequence that is inside you, then return and return means that I have made the penis a big source, I have contacted both of them for it and I have crossed all the limits, it is okay, my work will be done. I like it and take it to invite you. If it is ok then it will be visible again. I request Ajay to like it. This question is very easy for me, so once we do it, first of all we make it in sequence, then we know that 23318 were made, no, ok, then in the first difficulty, the one who made the cover, 221 limits are fixed, it is cleared till the court, we keep the one who came here, we made titans, I give interest 085768, we did our work here and made 200. That's all in the episode, source here, subscribe as soon as possible, we will take quarter like this, we will keep the answer as twenty to your friend, then answer plus is equal to two, let's put the location that you are not printed with I plus point 80, there is zero in it. To be specific, I made the unit president remember that yes, IJ is the starting point, if neither you nor me are out, then in the last game here too, Ajay will have to be given a pick and I will probably do it for 1 minute. I appointed this whole look subscribing to the channel I call legitimate complaints so I can say that like it okay it will also come here that I'm s letter song I take you this new code here so that you can understand What changes have been made, I put it in this and if it comes to Chakli size, then we should do the trick. In this issue, send your computer and it is there and it is the picture before 4. For this we have set in a video. Done where you do it and 4 p.m. The method of Show Me Clear 119 is 2131, see what will happen in 2017, I was requesting you, and if you do one more thing, you will become a great, by doing this, you increased the fare, by doing this, you clashed, so now whatever frequency I have lying with you, then this is Because this is a cloth, it ends just at the back and as much as you are pregnant, so many Gurjars have been corrected in it and also it is limited twice, so these two pieces are not equal, so this time the comparison is equal, neither friend will have to break the account nor the answer. Yagya of the camera, where it has come now, we will repair it, the treatment will be huge, we will open it and release it, on this is this, it has become two and Bieber leaves hai, it is also done, and Sarai Bara Denge I area but I have gone here. So what you have is the last one, this is the one behind you, this is the ref of you, so this 2017 is again equal with this, so we will create our account, we will compare it, this one is the last one, we will give you this, we will create my account dear answer. Did the account Dr to and I - 06 - account Dr to and I - 06 - account Dr to and I - 06 - was above the strong location so there or after that referred to someone that went here then you present it that this is the tube, this time also it is the same, compared this time Then the account was created, on the other hand, subscribe inside the answer, now we will do it and then you have made this, now we have gone here, so you lassie, this big BSC, which is now something, what will happen next, so here this time too, something or the other Then here I have subscribed to that and you have left the group. I went here, it was time for the office chicken. Now let's come to you. If these two pieces are equal for a beautiful look, then I am not like this but if it was that. People must put it is necessary to appoint a question on the print line of a doubt account and system dot print line is straight be a function of string, you will have to print it till then goodbye Randhir and subscribe were added to the Confluence which Let's see A I did not get the length because there is a function in the function ring Link Dawood fixed tomorrow morning keep submitting the time that you will understand tractor 1956 that is why a lot of missions come on the village so you have to understand this means | Find All Anagrams in a String | find-all-anagrams-in-a-string | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters. | null | Hash Table,String,Sliding Window | Medium | 242,567 |
1,870 | Hello friends, today we are going to solve another new problem of rate court which is 1870. Let us first understand its question. Here we have been given an award which presents that for moving my office from home. How much time does it take and we have to change trains in sequence to reach the office, so for this we calculate how many kilometers each train goes, it means that the first train goes 1 kilometer and the second train goes 1 kilometer. It goes 3 kilometers, similarly the last train means the third train can go up to 2 kilometers, the important thing here is that ours is inferior, it can be on floating point, meaning it will be very decimal like 2.13 ok and similar. Whatever train is there, its departure time will be in the interior only, which means if your first train right time is 1.5 hours, your first train right time is 1.5 hours, your first train right time is 1.5 hours, then you will have to wait extra 0.5 hours. then you will have to wait extra 0.5 hours. We have to find the minimum speed so that we We will reach in the office time and then we will all be able to travel in the train. There is a Taurus here, I must have told everyone, still I will write once if we know how much distance we have to cover, it is okay and we We know how much time it takes to cover that distance. If we divide it like this then we will get the speed. Okay, if we calculate and check, then we will return this which will be my minimum speed, meaning that It is taking one hour to reach the office. Okay, it means that if we go at one speed and go at inferior speed for one kilometer, then we will reach the office in 6 hours. So, the answer to this question will be the output. Whatever will happen is fine, we have been told that the range of speed will be from one to 10, how much will it be if we power it, so six of us here will take 6 hours to reach the office which is mine. Whatever timing will happen, there should always be a wait. If you set a ceiling on it, then you will be there. Then the last one will be okay, so my answer will be here, now if we add all three like this, then it will be equal to me, that too will not be mine, there will be no ceiling. We will come out with the last one because I don't have any train ahead of it for which I have to wait, hence we will not come up with its ceiling, so now if we simplify it then 0.7 if we simplify it then 0.7 if we simplify it then 0.7 OK, then if we add it here, its ceiling was Mine was one, then the value that we got from here was also one, this was its ceiling, we are not removing its last ceiling, so ours is 2.7, so ours is 2.7, so ours is 2.7, so this and mine is from the sound, so it means three, my minimum speed. It will happen that if we walk, we will reach the office on time, we will also travel by train, there is no use of life beyond this because then it will be more than three and if we have to get out here then please subscribe and We are reducing the channel, we have binary. If you are a little familiar with binary search, then this is going to be a very easy solution. Here we simply take some variables, take one left which is Let's start, let's take the right, this will mean that I will keep the mean speed which is minus one in the initial, if no result is returned in the solution, then we will return -1, we will do the same, inside that we will remove After that, we will have only two options or the speed will be the same in the medical lift, otherwise it will be right in the soil, we will check the speed only if we take this and it will happen. This means that my solution will be It will be on the left only, there is no use of life in the right, so what we will do is update it. My speed will be minimum. If we update it, then how will I not be able to reach it back. If I am going at that speed, then how can I make it my What will happen is that whatever is written will be updated, this means that I definitely need more speed. Now let us see how this function which we have created here reduces the time record. This is also very simple as we said. We will use the formula to calculate the speed, I will give the time, which I will double type, okay, the result will be A in protein point, here we will run distance, dot will be length and I will do plus, then how much time will be obtained. I will write here that I am late, distance of how much time is going to be taken, it will be known that I had taken it in my mind, but what will we do, we will walk while adding time, we will remove the ceiling of everyone here, number one has been discussed. Already here, let's enter the condition, if the one I have got is equal to this length - equal to this length - equal to this length - 1, then how do I do it, what should I do, the veterinary operator is doing it here, how do I do it means we have reached the last one, so there But don't do anything, keep it like this otherwise seal it, just keep the time simple, from here to here the mean speed will come which I was updating here every time, now you must have understood it well | 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,493 | hey everyone welcome back today we are going to solve problem number 1493 longest sub array of once after deleting one element first we will see the explanation of the problem statement in the logic on the core now let's dive into the solution so in this problem we are given a nums array which has zeros and ones so the goal of the problem is to find the longest sub array of ones after deleting one element here right we can delete any element either it can be 1 or 0 right so in the given sub array which element is good to delete that is what we are going to find here so if I did it 0 in the sub array we are going to have Phi ones in the sub array whereas if I try to delete 1 in the sub array we are going to have only four ones in the sub array right so what we are going to do here is that we are going to give a priority to delete 0 in this sub array right rather than one if I don't have 0 in the sub array we will exclude one but if we have 0 we are going to delete a zero right so we are going to solve this problem using sliding window approach right so now we will see how we are going to do this so here we are going to have left and right pointers which will be pointing to the zeroth index then we are going to have a variable number of zeros which will be initialized as 1. so here one represents that we need to delete a 0 in the summary right we need to delete that 1 0 in the sub array so we are going to keep track of that here right so we are going to consider the first element as my sub array so here our pointer is pointing to a zero right here we have 0 in the sub array so when the r pointer is pointing to 0 we delete that 0 by reducing one in my number of zeros right so here we are going to reduce it by 1. so here we will be getting 0. so here the number of zeros to be deleted is 0 right so which indicates that we have already deleted a 0 in the summary right that is what it represents here if it is 1 we can delete a 0 in the suburb if it is 0 we have already deleted a 0 in the summary so since it is 0 here we have already deleted a zero that is this 0 right so now we will move our right pointer so now this is our sub array so here the r pointer is not pointing to a zero but in the sub array we have already deleted a zero so it is a valid summary right so this 0 has been deleted in the previous iteration that is why we reduced 1 here so we just extend our summary here so now our pointer will point to this one again in this sub array we have deleted this one so again we have to expand our sliding window so the r pointer will point to the third index so again in this sub array we have deleted this 0 so we keep on expanding the window right so now the r pointer is pointing to a zero since the r pointer is pointing to a zero we need to reduce the number of zeros by one so here we are going to get Negative 1. so now I will be writing another condition so when the number of zeros is negative which means we are trying to delete two zeros which is not valid right so we try to delete this zero but we have already deleted this zero right previously so it is not possible to delete two zeros at the same time so now we need to adjust this window right so since the left pointer is pointing to zero we have to increase the number of zeros by one so here we are going to get 0 negative 1 plus 1 is going to be 0 which means we have balanced this summary now we will move our left pointer by 1 so the left pointer will point to the first index so now we have completely balanced the sub array by deleting the zero now right so we have deleted an element 0 in this sub array since we have deleted an element previously we are excluding that and we are deleting the current zero that is what we are trying to do here so now I will move our R pointer so here in this sub array we have already deleted and 0 so we don't have to delete an element further so then we have to again increase the window in the sub array again we have deleted this 0 now again we need to expand our window so here the r pointer will point to 0 again when the r pointer is pointing to 0 we need to reduce the number of zeros by one so here the negative value in the number of zeros represent that we are trying to delete two zeros in the sub array so when this happens we need to check whether the left pointer is pointing to zero or not here it is not 0 so we cannot balance the sub array right we just move our left pointer then we need to move our pointer then we need to check whether this element is 0 or not here it is not 0 so we don't have to reduce the number of zeros by one then we need to check whether the sub array is balanced or not so here in this sub array we have deleted two zeros which is not valid so we need to move our left pointer by one so now we have done with the input array now we need to take difference between the r pointer index and the left pointer index so here 8 minus 3 is going to be 5 so 5 will be the longest sub array of once after deleting one element right so the time complexity will be order of N and space will be constant space that's all the logic is now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially the number of zeros will be 1 and the left pointer will point to zeroth index then in the for Loop we will move our right pointer so initially if the right pointer is pointing to 0 so we are going to get 1 as my Boolean value and I will reduce that one in the number of zeros then we need to check if the number of zeros is less than zero or not that is if it is negative we need to adjust the sub array right and we need to update the number of zeros if the left pointer is pointing to 0 then we need to update the number of zeros if the left pointer is pointing towards zero element we need to increase the number of zeros by one then we need to move our left pointer to right then finally we need to return the difference between the right and left pointer that's all the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys | Longest Subarray of 1's After Deleting One Element | frog-position-after-t-seconds | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's.
**Example 2:**
**Input:** nums = \[0,1,1,1,0,1,1,0,1\]
**Output:** 5
**Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\].
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** 2
**Explanation:** You must delete one element.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. | Tree,Depth-First Search,Breadth-First Search,Graph | Hard | null |
1,015 | hey everybody this is larry this is day 30 of the december legal dairy challenge two more days till the end of the year uh let me know what you think how you did how you do uh hit the like button hit the subscribe button drop me a discord let me know what you think about today's problem smallest integer divisible by k what does that mean given the positive integer k you have to find the length of the smallest positive integer n such that n is divisible by k and n only contains digit one okay um yeah what is the bounce on cake balance is okay so yeah um yeah so me i think the idea here and this is a problem that uh done a long time ago but um yeah the idea is that you're giving a k um i don't want to talk about this because so the thing is that there is a lot of number theory in about this i mean not maybe a lot but at least like if you're unfamiliar with it's kind of hard to kind of come about um the idea is that and there are kind of a lot of places that you can't draw from into how to think about this problem for example there is some uh thing where you know uh if you have some x and then you do some function f x on it um you know there is some cycle so you will always get an answer eventually um and you can also uh i mean there is more kind of math and proofs around it but um but the small the quickest one i think is the pigeon pigeonhole principle right um meaning that it is either um not possible meaning that for whatever reason everything repeats uh and what i mean by that is that you know like this cannot happen here but for example you can imagine at least with this function where you times it by 10 and add one um to get an extra one right um and but yeah it's right it's not possible because you have uh a loop meaning that okay like x mod k as you go to some number and then that same number repeats without ever going to zero right so uh either that or that you hit every possible uh number in the mod k so that at most you're doing k loops that's basically the idea about it and of course the first thing i would say even though i said a lot about it already so maybe it's not the first but one of the first i would say is that of course another way to phrase it is that you have some x mod k is equal to zero right uh where x is of the form uh i don't know how to express this but like you know one right and of course the easiest way to and as we talked about um we can try the first k digits if you will uh of the form 1 um and of course you can do that with given a mod we just have to make sure that everything is mod zero right because obviously if you keep going then it even tells you it will not fit in a 64-bit end in python that's not 64-bit end in python that's not 64-bit end in python that's not technically an issue but if you have a digit of or if you have a number of 10 to the fifth digits um it does slow things down so it might actually time limit exceeded i'm not going to try it because it's not you know the point anyway but even if it's technically correct it might timeout right where in other languages it may just you know overflow or under full or something like that so yeah um so then the idea is that okay let's try one digit right and then uh and then two digits and then three digit and so forth right and of course um we're trying to get the smallest so there is the um the natural progression meaning that you go from smallest to biggest uh it's going to be fine and then of course you can kind of see this very easily that uh it you know to add a digit you i guess there are two ways to kind of see it one is to add it in the beginning like add the digit to the left or the other way is to add it to the right after multiplying by 10 right shift and that um and that's the technique that we're going to use today and let's get started uh so basically let's just say we have digits is equal to say 1 the current number is one and then while um current mod k is not zero we again we shift and add um and then we mod it by k because um because this is some a property of modular math which is that um you think these operations you know uh just to kind of go over very quickly like a times b mod k um is to go to a mod k times b mod k right um something like that and also of course um the same for addition right so you can do this here not just for right for pretend i have a good parent over here but uh but yeah someone like that right so these are some properties that um i don't know i wouldn't say you have to memorize it but it does come up a bit if you do competitive programming for interviewing maybe not as much but still um so these are things that you know you just have to kind of learn because these are identities for module math um but yeah and then of course uh increment by one and then at the very end you're pretty much done uh we give it a uh test some cases test a big case which is 10 to the fifth and yeah oh i would say one thing i did not test is whether there's a loop and you could kind of um test that in a bit um but yeah and also i guess this can be just current is not greater than zero because we already might okay here but we do seems to have a issue maybe i have a typo somewhere and i am i've been bad with typos lately it's not the data i missed about the problem okay i guess technically i could write this but oh okay so there is a thing where that's not possible so i was thinking of another function where that's always the case but we did already talk about this with what we said about pigeonhole so we just have to test for this that's not that bad um and the idea is that if you have already seen a state before um and you know uh you could consider or the numbers over um i want to break into equivalence classes but i don't really think i'm going to go that deeply into that right now but the idea is that you know like dysfunction or dysfunction maybe more specifically this function right as we kind of talked about before this function um for every like for example um i don't know for example let's say this number is two right um and then how do i want to explain this sorry give me a second um my point is just that whatever this number is let's say you have some x let's say you have some a and then f a you know this is equal to f of a right if later on uh we see a again this is still going to be the same thing um so this is not going to change so that means that if you have seen the same thing before then you should be done because um you're basically done because you're gonna keep on repeating forever right so that's basically the idea and i should have known this actually i wasn't paying attention sorry friends because i was focusing on the explanation a little bit um but yeah uh and in this case you could you know maybe use a set um that's something that i would do a lot um another thing that you can do is just have a boolean value of like a boolean array of length k because you know that every um every uh every number mod k is going to be less than k um i actually for this one i preferred um a set um it really depends on the problem but i think with this one uh well i would also say this is uh elite code special in that i think in if i do things in like code for us or something where every test case is by itself um it doesn't really matter because you have the time for it right where on lead code which is a little bit awkward and a little bit better um i worry that this would actually take too much time in the long run um just because you know this technically it takes of k no matter what um or lower bound of k right or uh omega of k and not um not just you know uh up about or not just a uh complexity of k um and you know uh saving time here and there kind of adds up and that's kind of the thing but yeah um and then scene dot current uh yeah so then here we can write this and then maybe we can write if oops if kern is equal to zero we just return digits uh yeah and then here we return negative one um so then we kind of change the condition a little bit while c uh welcome not in scene and i guess technically then in this case we have to add this here um it's a little bit awkward because i think that do while loop is probably cleaner here but um that's a little bit weird okay i do have a mistake though i do want oh um i guess i'm off by one because i add one to the digit beforehand now because that's kind of why i wrote this here but i guess that's a little bit awkward um i guess this can only happen when k is you go to one um so we can kind of remove that i suppose uh it's a little bit awkward because like i said it should be do while loop so they are going to be like weird cases where um where this is happening uh but yeah that's uh let's also you know play around with a little bit more than uh i'm just banging on the keyboard really there's no significance to these numbers uh let's kind of see how that shakes out uh let's see and it looks good so let's give it a submit uh this has probably been a long explanation than i intended but yeah but we have a 639 day streak um and yeah one more day till another year i guess maybe not another year but first four year of daily leap code videos uh let me know what you think um yeah like i said this is going to take at most k times because of the pigeonhole principle so this means that this will only be of k space um well let me see what i did last year um i guess i pretty much did the same last year uh the only yeah okay i actually explained it oh i talked about the relationship as well i guess but yeah let me know what you think um and if today's explanation is not that great um check out last year's explanation maybe i don't know maybe that's better i'm still in panama so my whatever is a little bit weird um right that's all i have to i don't snake it anyway um hit the like button hit the subscribe button join me and discord one more day till the end of the year stay good stay healthy good mental health hope you have a great week and hope everybody had a good next year i'll see you later bye i have to press the button | Smallest Integer Divisible by K | smallest-integer-divisible-by-k | Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`.
Return _the **length** of_ `n`. If there is no such `n`, return -1.
**Note:** `n` may not fit in a 64-bit signed integer.
**Example 1:**
**Input:** k = 1
**Output:** 1
**Explanation:** The smallest answer is n = 1, which has length 1.
**Example 2:**
**Input:** k = 2
**Output:** -1
**Explanation:** There is no such positive integer n divisible by 2.
**Example 3:**
**Input:** k = 3
**Output:** 3
**Explanation:** The smallest answer is n = 111, which has length 3.
**Constraints:**
* `1 <= k <= 105` | null | null | Medium | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.