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 |
---|---|---|---|---|---|---|---|---|
272 |
hey what's up guys this is chung here so uh today uh let's take a look at this problem number 272 closest binary search tree value number two so you're given like a non-empty binary so you're given like a non-empty binary so you're given like a non-empty binary search tree okay so remember this is a binary search tree so for binary search tree everything on the left side is smaller than the root node and everything on the right side and the right subtree is greater than that than the root and the target value okay so and then it asks you to find the k values in the bst that's our closest to the target okay for example this one the target is 3.714286 3.714286 3.714286 and they ask you to find the closest two elements that's in the from the binary search rate in this case is four and three okay so uh i mean a common way of doing this is like you know since we need to find the closest one right so the common ways that we just use a two stack or like a cube whatever you call it basically you know so for the first stack we have like uh we have the like the numbers that's it's a smaller than the target in this case is one two and three okay and for the second stack okay we uh we store all the uh all the numbers that's greater than a target but we store it in a reverse way okay or what we doesn't really matter we just store it because here we're gonna store it in the so basically we have five and a four here i mean we can either store it in a reverse way where it doesn't really matter because as long as when we read it from a different from a reverse direction so let's say we have these two stacks right so now all we need to do is we just need to like select the top case uh element among all those two stacks yeah pretty straightforward right so um because that will be the uh basically we're gonna uh select with this two stacks here we're gonna try to compare the top two uh elements top one element and which we compare it with the absolute value between this value uh and the target value when we select we which one is smaller and if that is smaller one and then we just pop these things out and then we continue comparing with the second one here until we have got until we got case elements here cool so uh let me try to uh code these things real quick here i mean so to do that right i mean we have to uh um we have to basically uh we have to loop through i mean traverse that the tree twice you know the first time we need to uh get uh the smaller number and the second time we're gonna get the bigger number okay so uh let's see we have a small smaller okay and here and then we have a bigger of this okay so um we need to do a dfs basically right so uh dfs smaller okay sorry smaller and then we have a we have node here if not root right we simply uh return on here okay and then we do a dfs note left okay and then with the current with current one since you know we're getting we're going to the very left first because that's gonna be our smallest number here okay and for the smallest number we're gonna insert it into the uh basically if the root the node.value basically if the root the node.value basically if the root the node.value it's is equal smaller than the target and then we just add it which is a smaller dot append to with the node.value okay so we're to with the node.value okay so we're to with the node.value okay so we're doing like a smaller here uh equal smaller or equal here because you know if the target is the if the target is this happens to be the same as one of the node here i mean we're gonna move we're gonna put that node into the smaller but uh stack here so we which means when we dfs the bigger ones we're going to use the greater not the equal because we don't want to duplicate that same node into two to stack here now this is like the f uh right okay now i can just simply copy these things here right so that's for the smaller and now we have a bigger here bigger okay same thing here but instead i'm going to do this right i mean smaller start bigger okay so um i mean here i mean we can store it we can append it to the end you know but if we append to the end that we have to uh it's fine yeah i think it's fine we can just append to the end so because we are still we are also going to the left one is basically the smallest one on the left this on the bottom so it's four and five uh let's do that you know let's just keep them same but remember when we read the value from this the bigger ones we need to read from the first one okay so and yeah so now just do a dfs smaller and with the root okay and then df as bigger with the root okay now let's populate our answer here right so the answer is a list and we have while k is greater than zero okay uh basically you know if not uh smaller right if smaller is empty then we simply do answer that append from the bigger one okay so the bigger one is like uh pop zero right remember we are popping from the left okay that's why we do a pop zero uh else if not bigger okay if it's not bigger the same thing append smaller dot pop for smaller we can pop from the top right because it's storing like this one two three okay uh else if okay if both of them have a values then we just uh need to compare right if abs uh smaller dot minus one right that's the miner's target is smaller okay smaller than abs of the bigger one is the zero it's the first one right remember that okay minus target so this thing uh it means that the smaller one the top one or smaller one is closer to the target so we do a start append smaller dot pop okay else in the end we just do it the other one we just do this bigger one okay yeah and then in the end we simply return the answer here cool yeah i think this should just work let's try to run the code yeah oh sorry dfs here bigger okay ah sorry note that oh yeah vow here not the value uh okay some typos here okay a few more typos here append figure append node 41 pop from empty list if not smaller huh this is weird um yeah this is yeah because it's weird says the k smarter it says k is smaller than the total nodes here so if smaller is not it's empty and then i append the bigger ones bigger dot pop zero okay let me check that i know so uh i forgot to decrease the k here of course run the code all right cool so this time it works let's try to submit it yeah so it passed all right i mean so this one is pretty i think it's straightforward right i mean the uh time complexity right i mean the uh the dfs and the df is bigger and smaller it's just like uh of n here this is all off in here because we are like basically we're storing uh we're traversing everything right from the root note here from the tree here and here it's just like a k here right so that's the k so basically that's going to be a two o of n plus o of k here okay so um maybe a few thoughts on this follow-up here few thoughts on this follow-up here few thoughts on this follow-up here and as you guys can see we have a uh on plus okay time complexity here and the follow-up is assuming and the follow-up is assuming and the follow-up is assuming that the bst is balanced could you solve it in less than o and runtime so which means that uh can you solve it by not traversing the whole trade here so what i'm thinking is that you know since it's a balance you know uh we can still we still can we're still gonna keep like smaller and bigger uh bigger like a note here a little stack here but instead of traversing our everything we're just traversing from the top you know from the top to here since it's a balanced right balance is like this i mean balance is not like completely the same maybe the left and right one the height is not bigger the height difference is bit not bigger it's uh at most one okay so i'm thinking if that's the case we can traverse from top down here and if this one is the uh it's smaller than target we just put it into the smaller one and if it's bigger one and then the bigger one right and then we go to the left and then if this one's uh sorry let me think here so i mean if this one if the current node is smaller than the target and then we go to right and then we compare with this one if it's smaller or bigger so basically we always go to the opposite directions and after that we'll have like a smaller and bigger ones that are storing part of our answers here right and then we can miss this one with this and then the time to get to pre-populate the smaller to get to pre-populate the smaller to get to pre-populate the smaller and the bigger one will be like the log n right uh login time and then later on here in the while loop here we just need to uh basically we have an initial state of our case value here and then we're trying to expand basically we're trying to expand that's uh the numbers we're trying to expand that this list here right i mean if this at least even smaller and bigger one does not fit it's even smaller than k we'll just try to expand that but to do that in order to store the value here we need to store the uh the node itself so that later on when the uh whatever you when we have used one of the values here we can just uh we can just get another values another value by doing the by getting the predecessor or the success the successor from the current node so in that case i mean the time complexity will be a log n plus k sorry log n plus k here i mean i didn't implement that one but if you guys are interested you can just try to implement that by yourself okay cool guys i think that's it for this problem yeah thank you so much for watching the videos guys stay tuned see you guys soon bye
|
Closest Binary Search Tree Value II
|
closest-binary-search-tree-value-ii
|
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**.
You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`.
**Example 1:**
**Input:** root = \[4,2,5,1,3\], target = 3.714286, k = 2
**Output:** \[4,3\]
**Example 2:**
**Input:** root = \[1\], target = 0.000000, k = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`.
* `0 <= Node.val <= 109`
* `-109 <= target <= 109`
**Follow up:** Assume that the BST is balanced. Could you solve it in less than `O(n)` runtime (where `n = total nodes`)?
|
Consider implement these two helper functions:
getPredecessor(N), which returns the next smaller node to N.
getSuccessor(N), which returns the next larger node to N. Try to assume that each node has a parent pointer, it makes the problem much easier. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. You would need two stacks to track the path in finding predecessor and successor node separately.
|
Two Pointers,Stack,Tree,Depth-First Search,Binary Search Tree,Heap (Priority Queue),Binary Tree
|
Hard
|
94,270
|
139 |
In this video we will discuss the problem of word break. In this problem you are given a string and you are given a trick. You have to return if you can segment S in which dictionary word and if you cannot then You have to return from the result, like the example given here is lead code and we have dictionary's lead and tax, so we can segment it, our let is present in the dictionary, our four is also present in the dictionary, so we can easily segment it. If we can do it, then we have to look at dictionary and cat, if not, then we have to do if we can do even one partition in which our entire string is formed, then we have to return true. If we ca n't do even one, then we have to return true. If we talk about this then what can we do, let us try the green possibility like this is my present i.e. this is my present i.e. this is my present i.e. this is my present, check for this whether I can also divide my dictionary into pieces or not similarly. CATS This is a region of mine, the child is string A and Di O G. I can divide it, I can't, like this, if I can divide the whole team into its own pieces, then what does it mean, you return. If I can't do it then I have to call, how can we do this? So, let's run the look from here to here. In this, we should consider the green sting. If anyone is our present, then what should we do? They say this. Our present has so much nutrition. Repeat this process for the number of portions. Like for my portion I from here to N till here. Check again for so many portions. Can I divide after seeing it in nutrition or If I can't then how will our question look like for this problem, we will start with zero, we will see that C is this is also cat, this is present, then what will I say, C is my present, that is, what is tu plus next index, open the function. Do this in which you check that the string from three to my child, can we divide it into pieces with the words of the dictionary or can we not or could we not do so, then what we did yesterday from this index to the last. We have to check till one, beyond this I don't have any present, so from my starting, string questions will be formed, one, then what will become of true plus third index, check one month's CATS till here, children from true and four index. Check for student done then what will happen in our recession three 3 Our here is what will happen in seven or else check like this that whenever mine goes out of bounds how to return it in 1 we can divide it So what do we do, we will follow this branch, we have checked us till here, question of seven, what should we say, dog, yes, it is present, then it is fueled, it comes from here, then we have a return here, so if we use this equation. Even if we go to ' if we use this equation. Even if we go to ' if we use this equation. Even if we go to ' A', our 'True A' is given, so in this way our A', our 'True A' is given, so in this way our A', our 'True A' is given, so in this way our question will be 'K', once we see a failure, question will be 'K', once we see a failure, question will be 'K', once we see a failure, our answer will appear, what have we done now, we have removed one lamp from here, before us it says 'cats' and 'two'. Now before us it says 'cats' and 'two'. Now before us it says 'cats' and 'two'. Now we have done CATS and OG, we have removed it. Now let us see how our Krishna will reduce it and what will happen in it. What will happen for the cautionary? This is my present for this. OG, this is not our present at all, otherwise what should we return. We will give water, if the water returns from here, it will get water here and here also it will turn from four, in this way it will turn from four, it will turn from phone and if water will come here, then we will divide it by 4. We cannot do this if all the branches are burning it, that is, we are not dividing it into any one branch, then we have to burn it, so in this way we will do more, no, what do we have to look at to optimize it, i.e. If our problem is repeated, i.e. If our problem is repeated, i.e. If our problem is repeated, all the problems will be repeated, then we can apply DP. Basically, how will DP be applied? What index should we pass in Ramakrishna? So we will make an index of the size that if we have already calculated the answer from some index, like my location. If we have already calculated water for intake here, then when we want to do it again, we stand off calculating, if we turn straight from straight to four, then how will our membership be? We will note down the DP or really the size of our string. On each index, we have already calculated from there to and or not. Apart from this, we have one more part left, we were seeing how to check whether CAT is present in our dictionary or not. What will happen after storing it? Whenever we have to check any string whether it is present in our dictionary or not, then simply whatever will be the size of our string for which we will check, in that time we will be able to check whether it is present in our dictionary or not. For the same, it will take as much time as the size of our string, so we can do any of these three to check whether our Sarita is present in the dictionary or not. I have to map it. So I will do yours, you can price it, your time complex will also come, so now let us look at the code of this problem, the rule will present that this is in our dictionary, that will present this is not in our dictionary, so we will do a loop on this dictionary. By putting each word in our map, we will see that this word is present in us, then what we had to do the recess yesterday, which question will we do tomorrow, 0 is the index, there will be something else in the dictionary from our starting characters, what does it mean that We have already calculated its value, there is no need to calculate it again, only by returning it you can see how our convention will do. First of all, our base condition, if we reach the end of the string, what does it mean? What happened is that we got a division, now turn the rule, what do we do after that, let us see whether we have already done the calculation in DP, we have already kept it in the calculation of the approval result, so what will we do for that? That if there is no minus one on the P of index, then the value on it will be zero, the value for water will be for the purpose of our calculation, whether rye or water came here, now they will return what we have just done earlier. You must have calculated, if we have not calculated then what we had to do was to look from the index passed to the rest of the string and check all of them whether that is also present or not, so we started from the index to We put a loop till these and what did we do in it, we got our string and kept on pushing, so what we had to do was to check for the child string, we have calculated that this is present in our dictionary, that plus one, that we gas. Will pass our string dictionary and degree. This child is also for the string. Check whether that dictionary is also present or not. If this function of mine returns true, this dictionary does what it means that I can partition it. So what do I have to return? You have to return that, what will we do before returning our dictionary? After doing that, what do we have to return at that time and if we return it then the structure will be like this, our base condition will be there, then we will DP. We will check in then we will try the possibility of saree. We started from our triangular index at each center. What should we do? We are putting a loop till this point. Basically N - 1 then N - 2 can go like this N - 1 then N - 2 can go like this N - 1 then N - 2 can go like this i.e. Overall, what will be our time, how much will be our stage in DP, we have only one changing variable, our index is changing, what will we do to get our total, if we put a loop, what will happen to our time and the value of each state. How much time will it take us to calculate of n So now our triangular will be n² If we do not do that of DP, now we have the difficulty in which it is reduced and in square and what will be our space complexity, then our requested state will be one One will be used for our DP and one will be ordered for us. If we want, we can represent our space complexity in whatever their particular size is. For now, if I take the size of all of them, take all of them and take one of them, their size will also be one unloading. I'll take one for our DP and one for our ex if we talk ruffly
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
268 |
hello everyone welcome back and today we are looking at question 268 which is missing number so we are given an array nums containing n distinct numbers in the range 0 to n inclusive now we want to return the only number in the range that does not appear in our nums array for instance if we pick n to be 3 this means that our range would be from zero to three inclusive right from zero to an inclusive n is three our range would be from zero to three inclusive now this means that our range would be zero one 2 and 3. so we notice that if n equals 3 our range will contain n plus 1 numbers right if n equals 3 because we are starting from 0 and 3 is inclusive we would have 0 1 2 3 which are four numbers now our nums array they are saying that nums would only contain n numbers so if n equals three our nums array would only contain three numbers so we will pick any three numbers from the range to fill our numbers array right so the example one is saying okay let's pick three let's pick zero and let's pick one now we can see that nums only has n numbers in this case n equals three so okay if the range is n plus one and the num is contained on the n we can see that the range has one extra element that is missing from nums and this is the number we are trying to find okay so how can we find the missing number well let's see if this is the range we can add all the numbers in the range and let's call that some um range sum so this is range sum and let's call this one the actual sum so this is the actual um sum okay now if we add all these numbers and we in the range and we add all the numbers in the numbers array and we subtract the two we can clearly see that zero will cancel out with the other zero the ones will cancel out threes will cancel out we will be left with the two so we can see that okay if we have zero plus one plus two plus three and we have um three plus zero plus one now if we subtract these two we can see that zero will cancel out with a zero one will cancel out with the one three will cancel out with the three two minus zero equals two and this is the missing number and this is the problem that's it so let's try to cut this solution quickly and then i will show you a quick modification for how to calculate the range sum to make this um to make our approach even faster so let's have a look we will have two sums we will have the range sun and we will have the actual sum so the range sum will start from zero we can initialize it to zero and we can have the actual sum also initialized to be zero so actual um sum equals zero now um what is the length of our numbers array well we said our nums array would contain only n numbers and in the constraints we can clearly see that the nums.length which is the length of the nums.length which is the length of the nums.length which is the length of our array is n so instead of i'm typing numbers that length each time let's just say in n equals nums dot length okay good so now let's try to find the sum of the numbers in our array which is straightforward so for int um num inside of num we need to add all these numbers to the um actual sum so actual sum plus the um good and now we need to calculate the sum of our range so we will have a for loop for that so for int i equals zero i is less than um n but now wait if we say i is less than n we will say zero plus one plus two and we will miss the three the question is saying that the range is from zero to an inclusive so we need to include the n which means i is less than or equal to n and i plus okay so now what we do we need to do well we can say the range sum plus um the plus i we need to add each number to our range sum and that's it at the end just return the range sum minus the actual sum and we would get the answer so that's it for this approach this for loop runs in big o of n time so the time complexity is big o of 2 n which can be of course reduced to big o of n but we can use something different to calculate the range sum so let's see how this goes so first remember this approach is big o of 2 n which can be reduced to big o of n so now let's see how can we uh modify this one to calculate the range sum in constant time big o of one so let's have a look so we can see that the range is zero one two and three now when we are talking about the sum of the first natural numbers we always need to think about gauss's formula now what is gauss's formula well let's let me write it first so we have gauss's formula now when we when you hear this term always think about the sum of the first n natural numbers so first question what is the natural number well the natural numbers donated like this are the numbers from 1 2 3 4 dot up to infinity these are the natural numbers now if you want the sum of the first n natural numbers gauss is saying this sum is equal to n times n plus 1 divided by 2. let's see an example let's say n equals 4 we want this sum of the first four numbers now if we would have this for loop that will go through all these numbers we will have okay 1 plus two is three plus three is six plus four is ten we use the for loop for that with time complexity big o of n now let's check gauss's formula since we need the sum of the first four natural numbers we would have four times four plus one is five divided by two four times five is twenty divided by two is ten we got the same answer but gauss's formula give us big o of one time right so now let's modify our code we don't need this for loop no need for it and now the range sum instead of having it initialized to zero we will say oh by gauss's formula we can say n times n plus one divided by two and that's it so now let's try to run the code okay and now let's submit as you can see faster than 100 so we have one for loop to calculate the sum of our nums array which is big o of n time now by gauss's formula we can calculate the sum of our range in big o of one time constant time so the time complexity of this big o of n the previous approach was big o of two n which got reduced to big o of n this one is big o of n right from the start so this approach is faster now let me say that this question can be solved in bit manipulation and on my channel i have already made two videos that goes into great detail into bit manipulation i will put on the links for those videos in the description and if you watch those videos this question would be walk in the park to do it in bit manipulation with that being said i hope you guys enjoyed the video best of luck to you and i will see you on the next one
|
Missing Number
|
missing-number
|
Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._
**Example 1:**
**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.
**Example 3:**
**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `0 <= nums[i] <= n`
* All the numbers of `nums` are **unique**.
**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?
| null |
Array,Hash Table,Math,Bit Manipulation,Sorting
|
Easy
|
41,136,287,770,2107
|
895 |
hey everybody this is larry this is day 19 of the leeco daily challenge only 10 days to go now 11 days to go somewhere like that 12 days to go hit the like button hit the subscribe button join me in the discord let me know what you um let me know what let me know how you're doing in general hope y'all having a great weekend uh and all this other stuff uh yeah uh let's get started maximum frequency stack 8.95 okay let's see what do we stack 8.95 okay let's see what do we stack 8.95 okay let's see what do we want stack i want to pop the most frequency frequent element from the stack okay what does that mean so you push okay now pop five um so what does that mean we move if there's a tie from closest to the top okay so five and then now seven is too closest to top okay okay so this is a data structure problem obviously as you can kind of see about this um you know i mean they kind of give you a hint and that is a frequency stack so you probably want to use a stack at some point and then the idea is that we have 2 times 10 to the fourth course so obviously if we just do a linear type thing every time uh then it's going to be too slow because that becomes quadratic right so we're trying to think about how to um you know try to figure out properties of these problems so that you um so that after each operation there's an invariant that you can take advantage of right so let's see um does happen that he makes sense let's say i am okay oh i think one thing that i just noticed and i did not um huh yeah one thing i just noticed is that there's no regular pop right so um so this pop is always removing the most frequent thing so there's no you don't have to support an actual stack pop and that actually makes it slightly easier and you can kind of lie and cheat about the implementation right because now you don't actually have to care about pop then now you can optimize specifically to remove this operation and this operation only right let's push you can think about it if um yeah okay so i think that's the key observation which is actually kind of dubious in that case why do you call it a stack it's a little bit confusing i mean i guess there's the top of the thing type worker but it's still a little bit awkward um okay so i think in this case in this case we can treat yeah i think we can use the heap is what's going on here i'm trying to think about uh we could treat and the um my thought process is just trying to figure out whether for example in this case we have um you know three fives right do we have to make sure all the fives are in sync and i think probably not but we can still kind of do it just to kind of be careful um because it's just a lot of bookkeeping and just tracking um where everything goes and that'll keep it okay i think um yeah i think that should be good so okay so the first thing i'm going to do is just have a heap like we said the heap go um and then we also keep track of maybe like a counter type thing the counter being like just a number that you know the next time you push on the stack because one thing that i would say is that um you know like you could encode this function uh this push operation as like you know the zero index one index two three four five right dot that makes sense um and then let's say you pop right let's say you got rid of this five and then now you add another number two right um of course you can get rid of the five and then make this position five but it also doesn't change anything to just make this six because this because no there is an invariant about stack that um you know if you pop then this is the number that comes in later will always be on top of all the numbers that comes before it no matter how you do it right unless it already got popped but you don't have to care about that operation anymore so then now having this counter here will allow us to figure out what the top of the stack is right and let's say pop then now we have uh if there's a type of the top i guess there's no typewriter from the courses so that means that we want a tie break by the counter which is the closest from the top to the stack um and then uh well the account counter and then maybe x just for the number um and that i think should get us uh the way there um i think we also maybe i did think about this but i forgot but uh but maybe like um a look-up counter look-up counter look-up counter right so we can have just like a just how many like a frequency map i guess is what i want to do which allow us to figure out um collections that can do so that um so then let us just figure out like okay so i could keep track of how many things there are um and then now sub.heap so we want to push and then now sub.heap so we want to push and then now sub.heap so we want to push this to the heap and keeping in mind that in python it's a min heap so if you're not using python use your favorite language stuff and like i said we're gonna have count which is self dot frequency of value uh the counter with yourself that counter and then x which is the value right and then now on pop we will have cam counter x as you go to he oh i think i messed up something real quick um because this is mean heap i said it was mean heap right but then i treated like a max heap so that's not quite right because we want the most frequent ones then so we have to um we have to sort by the other way and we also want the top of the stack which is the max number so uh so we want to do it this way okay um yeah and uh so we don't actually do we care about count nope we don't care about counting to either really so yeah i think not maybe i'm wrong because then now after we pop we remove the frequency that makes sense and that's pretty much oh uh yeah and that's pretty much it i think right because what else do we need yeah so then now the next time we push with that number we have so that's the only thing that is that we don't um we don't want to mess up this counting to be consistent i think that should be good so okay so let's give it a spin i don't um i don't know how confident i'm on this one but at least in terms of complexity this is okay um and even this is not a great um this is not a great like in uh test case right so we will have to see whether that is good enough all right oh that's did i pop no i popped an extra one okay um yeah i don't know if that does this input this example is representative enough i guess to give me that much confidence i mean obviously it's still nice to have it correct if it's not correct and you'll just be like well obviously you just won't but yeah so let's give it a submit apparently i've done it twice before yes 718 days streak um oh yeah i didn't go over the complexion have i so this one i mean this there's just two heap operations right and a couple of uh frequency table lookup which is a hash table lookup so this should be obvious hopefully which is that this is log n where n is the number of item and this is also obviously log n where n is the number of items um or max items on the stack or something like that you want to call it that yeah i mean the hardest part is just noticing that pop it or there's no traditional pop because very often these kind of things they have you know this weird function but also the traditional pop which makes it like harder to maintain um let me think if we are given a regular pop function to add on top would that be good enough i mean i think we would still be okay it's just a lot more bookkeeping in that like you have to keep track of what was removed so then you have to when you do this pop um and you have to see if it's removed then you have to do it again and so forth um because now you have two sources that can get desynced and you would just do it the way i would do it is having a lazy propagation type thing i think so um so it's not that bad uh or that much worse it's just more annoying um cool i think that's all i have for this one uh let me know what you think let me know how you did let me know what complexity you end up with uh that's what i have though but stay good stay healthy take your mental health i'll see you later bye
|
Maximum Frequency Stack
|
shortest-path-to-get-all-keys
|
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the `FreqStack` class:
* `FreqStack()` constructs an empty frequency stack.
* `void push(int val)` pushes an integer `val` onto the top of the stack.
* `int pop()` removes and returns the most frequent element in the stack.
* If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
**Example 1:**
**Input**
\[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\]
\[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, null, null, null, 5, 7, 5, 4\]
**Explanation**
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is \[5\]
freqStack.push(7); // The stack is \[5,7\]
freqStack.push(5); // The stack is \[5,7,5\]
freqStack.push(7); // The stack is \[5,7,5,7\]
freqStack.push(4); // The stack is \[5,7,5,7,4\]
freqStack.push(5); // The stack is \[5,7,5,7,4,5\]
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\].
freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\].
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\].
freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\].
**Constraints:**
* `0 <= val <= 109`
* At most `2 * 104` calls will be made to `push` and `pop`.
* It is guaranteed that there will be at least one element in the stack before calling `pop`.
| null |
Bit Manipulation,Breadth-First Search
|
Hard
| null |
443 |
hello everyone let's solve the problem string compression given an array of characters compress it using the following algorithm begin with an empty string s for each consecutive repeating characters if the group's length is 1 appendic 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 note that group lens that are 10 or longer will be split into multiple characters in cars 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 okay let's say this is our given string okay what are we supposed to do we are supposed to compress it how first we have an A how many times have we got a two times right two consecutive times next we have B how many times two times then we have C how many times three times so this is our compressed string all right had it been the case that we have only one character of a particular character then our answer would be something like a B to C a is occurring one times right so in that case we want append the 1 into our answer string it would just be a okay we have been asked to not use any extra space right so for now let's not focus in that let's focus on how we can build this string okay so let's do that let's try to build our algorithm okay initially we keep a pointer here let's say I and we keep another pointer let's say J okay let's say this is our this is going to be our string okay what we are going to do we are initially going to put this a okay now we are going to move j as long as we are able to see this same character or we can say we are going to move j until and unless we don't see a different character so let's move j e j move again okay we finally see that we have a different character okay so J is finally here all right and J has covered this distance right how are we going to get this distance if we do a j minus I we are going to get this distance or the length right so in this case what is the distance or what is this length it is 0 1 2 3 minus 0 equals to 0 that is 3 a has occurred three times so we append this 3 here okay fine our work for the first character is done now what we are going to do now we are going to move this I to our new character okay and we are going to carry out the same operation in this new character move j until and unless we have a new character okay we have a new character J minus I is 0 1 2 3 4 and 5 minus 3 that is 2 okay initially we append this B and then we append this length to our string fine you move I to our new character okay then do the same thing move j move out of bounds okay J is here out of bounds and I is here we append see first then we append this distance what is this distance this definitely going to be a four right so we append 4 and this is going to be our answer string let us quickly code this approach then we will try to optimize it okay we are going to build our string right so for that purpose let's use a string Builder not a string because string Builders are more efficient and mutable right string Builder and I equals to zero this is the I okay now while I's in bounds of our given character array okay let's have our J right this J which was initially here okay now while J is also in bounds cars.length cars.length cars.length and cash at I is equal to cash at J that means as long as we are getting the same character or until and unless we encounter a new character we are going to move j that okay now when we finally encounter a new character this while loop will break okay fine now what we are supposed to do we are supposed to append our character into the string Builder what is it cars of I right now what is the task is to get the count or the length this length J will be here I will be here J minus I right let's call it length J minus I okay if our length is greater than 1. if it's one we don't need to append that one right only if it's greater than 1 then string Builder dot append length okay we appended this a then we appended this length done then what are we supposed to do we are supposed to move up the I point there right when we are here and we are done with all these work we will then move our I2 here right for our new iteration on our new character okay now in the question we have been given we have to modify the input array as well right what do we mean by that this is our input array right let's copy it this is our input array right and this is our compressed string okay not this one A3 B2 c d what are we supposed to do we are supposed to change it something like this A3 this becomes a b 2 okay then see three we are supposed to modify it this way the rest of the string we can let it remain as it is doesn't matter okay so let's do that as well for int ENT I is already defined right let's uh re-initialize it to zero I less than re-initialize it to zero I less than re-initialize it to zero I less than string Builder dot length I plus right we are going to iterate till the length of our compressed string rate okay cares of I is going to be string Builder dot carat I right is going to be stringbuilder.karati is going to be stringbuilder.karati is going to be stringbuilder.karati right here this will be here right at the end our input error is modified now let's simply return our compressed strings length okay let's try to run it works great if we talk about the time and space the time is going to be a bigger of n let's say n is the size of our given input array and let's say an M plus m is let's see the size of our compressed string right and definitely our space is going to be a bigger of M because we are building the string Builder right now how do we get rid of this extra space how can we get rid of it let's get rid of it we don't need it okay also we are not going to append right let's get rid of it we are going to definitely going to need this length we are not going to append anything okay now you are supposed to play with whatever we have okay we will try to update our given input array on the go how are we going to do that let's say this is our given input string right okay let's keep a pointer here let's say k okay and what we will do we will definitely iterate over this using our I and J right okay let's iterate we move J2 here okay then we update the input array with the character at ith position here in I we have an a right we update this position with an A okay it's already an a it doesn't matter but we will see afterwards we update this position with an a that is the character at ith position right at the position which was being pointed by our K right now after updation we move our K to the next position okay now our string has been updated with the character now we need to update it with the length so what is the length is J minus I what is J minus I it's three you will update this position with the 3 and we will move K forward okay and after we are done we will move this one as well and we will bring it to here okay let's continue this okay move j a comes here okay put at kth position put whichever character is present at the ith position so we put a b here okay fine K moves here now what is the length is 2 right so at kth position we update it the length now fine work is done let's move I to our new character okay let's continue let's move j finally comes here okay this K was supposed to be moved here okay it comes here now let's update the position kth position with the character present at the ith position that means this B becomes a C right and K moves ahead again and now we will update this position with the length right what is the length is J minus I that is 4 so in this place we have a 4 okay now since J has moved out and then we will update I right I to J I will also move out of bounds then our iteration is finished our input array would be modified to something like this A3 B 2 C c we don't care about this area okay now the thing is in some cases the length of our character consecutive characters can be greater than them right see in this example our compressed string is going to be a not one we won't include one but B how many B is one two three four five six seven eight nine ten eleven twelve this is going to be our compressed string okay so how can we update this right in this case we can't just directly put a 12 here right it's not going to be character in that case we will in general convert our length to a string okay and after we do this we are going to iterate on the string okay first we will go here then we will go here so what exactly are we going to do we first update a to a okay it remains as it is then oh then we have a b we keep b as it is okay then we have a 12 right our K would be here okay now we will iterate on this string okay what we will do we will first put one here okay move k move our pointer to the next digit that is 2 then we will put 2 here okay and then I would be updated to J right J and I would be here right so in that case we have moved out of bounds so this is our modified string okay and we are supposed to return the length right what will be the length will be this K right because after each iteration K would be moving forward right so at the end K would come here in this case K wood after updating this area this index K would be here so we will simply return K that is the length so now let's apply this idea here okay what we are supposed to do we are supposed to update okay let's initialize the pointer here let's call it idx equals to zero this will point to our this input array okay cash of idx b equals to care of cares of I right c k would be equal to the character present in I right and our and this pointer will move ahead okay now we take out the length Okay we take out the length if this length is greater than 1. okay then we are supposed to do something what we will convert this length to a string let's call it s is going to be Jing value of our length okay fine we will iterate over the length string rate s dot 2 carat array cares of idx would be equals to C that is it right and after updation at after each updation we will move our idx to next positions right okay after everything is done we will just like the previous approach we will move our I pointer to our J that is move our I to the new character fine and after that we won't need this right and we will return idx okay after it updates the last possible digit of our compressed string this idx will still move one position ahead right so it will be the length of our compressed string so we will return this let's run it let's submit pull what will be the time complexity will be but we go off n because we are iterating on the cash array right okay and the space complexity is going to be constant we haven't used any extra space right so this is pretty much about this problem if you like this video do hit the like button share this video And subscribe to my channel and I will see you in the next video bye
|
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
|
17 |
Hello friends, welcome to the new video, question number 17 lead letter combination of phone number is a medium level question, backtracking question is a friend's question, this question has been asked from many companies, big names are Amazon, Microsoft, Google, Facebook, Uber app, Pal. Oracle let's start the question the input I have given you is spring and in it between dj2 to 9 like ok find all possible combination number means this means if your number is two three then our hatred looks like so You must have seen that the character on two is B N C. The character on three is that if you type * and thi then type * and thi then type * and thi then what can be a possible letter combination. If you take this instead of two and if you put this in its place then A and D are possible. There can be a combination. Well, if you type two, then you learn the place of two and then you take its place. This can also be a possible combination. You have to generate all the possible combinations and this is what this question is about. You start from everyday. Let's discuss what approach we can use in this and what approach can be. If you see my backtracking players then you must be understanding that I have given numbers, I will represent them in a two-three layer graph, then I will apply represent them in a two-three layer graph, then I will apply represent them in a two-three layer graph, then I will apply some difference, then I will just write some more records and then If we generate some combinations then in this video we are going to do something different, we will solve it in such a creative approach so that you can understand at this point what is the door, where is the door, what is the constipation door and also its complexity in the last of this video. If we start Discus Bhind, then before starting, I would like to write some extra code first, like it has been said, to save all the combinations in your neck list, we can quickly create a list. Okay, we will name it Result and create a new list. Let's take it, okay, so one of ours is done and let's take Facebook at the beginning, if no digit time is given in it, its length is ours, then you will return the list. Okay, and I would like to tell my diagram only in numbers and what is there in the numbers. -If the character numbers and what is there in the numbers. -If the character numbers and what is there in the numbers. -If the character is not given in the description, then basically I have to develop it, so I write this little extra in the beginning and I will do this, a little skirt is less, okay, we will start the money, now you will understand, it is very easy. First let's make a secret, what we are going to do is, if there is Mittu in our map, then first we will save Tu and the character in place of Tu can be A, B or C. Okay, in this way you will have to save all the things. This is okay and there can be also okay 6 this will be seven and eight okay so A B C D E F G H I J here J K L M N O P Q R S Okay this way your Nokia phone You will see such characters are found in this tube, this person is okay and let's change the number quickly, okay, from the pipe, this will be one from here, this will be nine here, now coming to the approach, let's start the process number. You have given us 2030, okay, so you will see, now we will represent it in such a graph so that you can understand how the combinations are being generated and at the same time I will also share it so that you will also know how. All the data is saved, so we are going to represent it in a graph like this, but what is ours, then you will see that it is ABRC, okay, this is our this and DOC, there were 3 characters, so it has to be set like this because we have to generate it somewhere. We will check because if we are going to use it then we will take data structure for it Delhi And why are we going to take it because on its front also you can remove ads, on the back side you can do it is quite flexible, it is called Thing Deck in short. It is written that I had searched on Google, 'Tyother Delhi' I had searched on Google, 'Tyother Delhi' I had searched on Google, 'Tyother Delhi' and why is it called like this, it will be easy for me too by saying 118 U again and again, if it is called Saturday then I will say in the beginning there is nothing in the back and then I will say ka This and BRC have been added, okay, you will add while watching live and will also keep seeing the numbers in the same way, okay, the left side is the number, it is visible here in the diagram and from here, he is seeing everything, you will be able to visualize it and it will be very relaxing. From the understanding or what are you going to do, now I have to reach dad, so how will I reach this because now I have to add on, okay, I will make it a little far away myself, it will be easy, okay, something like this Let's do this by reaching to me and that I have to add, what is the next letter, the next number is three, on that we have dear reference, so I added that traffic is like this basically when I became a daddy, well, basically this video of mine was uploaded. This was my sum and this became my app. Okay, because by using one, I had modified it and generated three more. A little help from the present day will help. Okay, so what are we going to do in the track? Now our The date has come to this position, okay, this was the first time, now you see, the rough first level has come to the second level, so the date is starting again, okay, so you write something like this, start eat, it started in the first level. NDA was the AAP commission at the second level. It was the beginning and the end. So, what I told you is that you are updating your deck after seeing it is done, you are not making any changes, so now what is in your date, your deck has all three. Save DERC and you modified one and generated three, so what I mean to tell you is that this is my deck, you will see that there was my A, B and C in the deck, so I said, I have edited, added this, but I have removed this one from the back and one from the front and do the modification of this one, okay, so this is the back, Praveen, I have removed this one and I have made these three, now in the medical, these are the three children left, save the daughter, okay, now. What are you going to do, now what are you going to remove the army from your deck this time? This time you had previously removed it from your friend and dead in this manner, this time remove it from the front also, okay let's remove it from the heaven also and now we will remove it from the front. Use it. Now you have found it. If you also have it, then what did you make by using B. Bleeding being and benefit are fine. Let's make it here also. If it is clearly visible then it will be understood. And it is difficult by using quora. So much has been done. We will repeat this. Let's do something new, I understood, okay what to do this time you have to remove the C from the front, we will remove the C from the friend, we had also removed this and on this track, we will remove the C, okay, I had removed it earlier, but still. Here you are extracting C, what will happen after extracting it, so DCF is fine, so let's do it quickly, directly ESES code, it will be very easy if you understand this, there is no use of doing direct, it is important to understand what step is happening. So you saw this is our end war became one now we have one of the perfect one level this was ours finally you will get it okay if you want and I will do it then let's get it ready and take the vitamins here in the bag Let's see, okay, what to do this time, the phone will become a little bigger, but let's strike, write two or three lines, I will start it, I am okay, it has started, what do we do now we are going to do it. First of all, remove Reddy from the phone, remove the ad from here too, okay, the ad has been removed, if the phone number was good then it should be given as 'For' characters, so should be given as 'For' characters, so should be given as 'For' characters, so what did we do, we removed Reddy, okay so What did you add in Adelaide? What did you add in G Reddy? The couple is that I have added my couple in AP, so you have understood what is going on, basically, if I tell in the chart, it is running once, in the beginning, the first look, then you are seeing that it is running three times, okay. And if you go into detail then this note bar will work, okay, the more you explain, the fan will become bigger and finally, when this final product will be in one guide, all these will be of three characters, these are updated by removing the broken ones, okay. So something is happening in this way and everyone will come, everyone must have understood, now let's come to the code, how will we do the code, play with a little loop, let's start with the big one, come to the code, then make Delhi and New, okay and Its time will be our string, okay, you will create it in this way, okay, now what am I going to do in it, basically, I keep naming it, okay, what will we do in it, will we add more MP Spring in it, why? Will we add what was happening when then I will test it and I said then and BRC is being added so we need something behind it too, so we will add Anti A behind it and remove this behind it in MT. Then we will remove this also, then we will add C in MT and remove C, next time we will remove this and make A great, add egg, let's do something like this, so basically I have started this entry. I was thinking that I need something to complete, okay, so this is done, now the first powder loop, you must know that these numbers are being processed one by one, okay, so this one will not be affected, let's enjoy it first okay. We will go by tapping, we will go slowly, we will understand, this is our digit, let's copy it, so I digit start third length, okay I plus, so what are we going to do now we are going to do this, first of all we will take our if this two three four Okay, so I want the first two digit. Okay, so I take out the first two digits. In this, everything is given in the string. Okay, there is no difference. You have given everything in the string. So how will you remove the other digits? Dot substring. If we use the function, till zero seven position means I plus one, then first two will come out. If the loop will move further then three will come out, then it will move forward and four will come out. Okay, this is why we wrote it, okay now let's write only two. If it is clear, then you will understand a little, we will do one step and will keep understanding, now what are we going to do next, we need Chotu's tube, our ABRC, we need our ABRC, we had controlled it, we had stored it in the map, so I will take it out from you, okay. We were naming it from map, it will be included, okay, I am removing it from you, so will I do it, you put your date here or if it is ours, then we will put this basically to, we had saved it in Delhi. Here you got the set ABNC ok now what are you going to do you saw I am fine I had added and removed so it was running above it was running three times these guys were running so like this Why do the industries say sorry, we are going to talk, so its side is fine, so it takes one side, whatever side it is, earlier we had put this entry system, it will work on one side, okay, so what is its size going to be, aa dot. Let's do the size, initially its size will be one, okay, and later on, the size that started coming will be free, there will be no size, it will keep on going on and our boy will keep getting added to one, okay, so what are we going to do by using its size. We will have to run a loot, okay, I will take this to jail, okay, Jhajjar Ricardo NZ Plus, okay, now what will you basically do inside this, first of all I have taken out the element from the front in the back, so let's take a string and In Dead, we remove it first, give it its full name, okay, how will we remove the rough, okay, don't poll first, we will remove it further, okay, we will remove it first, so we have removed it, basically it is saying that the anti will come out later, whether your desired one comes out or not. If you get B then initially you will get MT, okay now what you have to do in this MP is to add to it, you have to do B.Ed in it, you have to add C to it, okay then whatever B.Ed in it, you have to add C to it, okay then whatever B.Ed in it, you have to add C to it, okay then whatever happens to you later, initially it is going to be something like this. So now ABC we have to process, where was this ours, this was our from map, from my voice tag, so now we have to use that to run fruit, which is our half, then we will be able to add ABC, we have to debit ours. So, I write this that Bigg Boss Dr. K.S. from , the length is fine Dr. K.S. from , the length is fine Dr. K.S. from , the length is fine or the plus is fine. Now how to add the village inside it, so inside this we first make the tempering. Okay, and we will have to wait a little bit, then we will have to add it. I will name it as 'Attemp' add it. I will name it as 'Attemp' add it. I will name it as 'Attemp' and how will we have to add it, what will we do after leaving my husband and we are making it and finally then we will add it, so we are making it by adding something like this, then how will we write it, first we will write it, we will worship that. Also, we had folded it from the front, now we will use it, let's use this doctorate function and we are going to do A, if you want to put it first, then first this is our, add ABC in the from map, then add dot caret, you have to put it first, okay Radhe-Radhe you. You will do that, okay Radhe-Radhe you. You will do that, okay Radhe-Radhe you. You will do that, okay zero will come first and it will be connected, okay, so basically it is connected to thirty plus, now you have to put this code in one also, okay, we had seen that they were putting it in the bag also, so you put it in the deck, don't tag it. It is easy to enter and whatever string you have created in it, add it to the date and here one problem is that I can create the character, so basically neither one nor the other can do this to you, if it is converted into a string, then I have done something a little bit. Conversion is done, okay, this is the format written, this will convert the character into a ring, everything is our string, okay, if we type a little data, then the work is done and this is just a little code and if you understand it a little. Again, what is going to happen next time, okay next time, initially yours was two, then you saw this two, it turned out to be ABC, okay then in MP, your this and helplessness are getting added here, okay here and next time. You will come out free, next time there will be a stone, so this is the one which came in our three, okay and this time you guys, this time, you have this is this time, first of all, this flower is in your deck. It will be Apple, then what is this and here you will add this I, you will also add MS Word, you will decide, then in this you will add Typing Chinese, you will add this I, and this bean you will also store it in your deck, something like this It will continue like this and our work I think is lost okay but the return we had to do was to return in the list so finally what will we do let's empty our debit okay that dot this period till it is not empty We will keep extracting and adding it in our result, I have given the name of the result, I copy it, I am the result of 8th and what is there to extract it from dead, Delhi and that to extract it, the work will be done with the help of I thing pole or this oil can be done. Okay, so let's write on WhatsApp and the person doing this will add all this to us and finally you return your result, whatever it is, it will return here. Let's compile this code and a little complexity will have to be discussed. So I make it smaller, remove all this and compile it as accepted and once submitted, let's see if some air comes, fix it, submit it and our code is basically this, understand a little how much complexity it will have. And to understand the complexity, let us once see how much output is being generated in how many inputs. If house is MT string then we have one digit or if we have two digits then how many combinations are being generated. Once we color it Now see, there is no combination in the testing, okay, and basically we had three combinations in one digit and we have nomination in two digits, so some observation can be done from this, okay, so basically what is there? We have said that you will see that if MP is a district then we will say that here there is zero combination, if your digit is one then you will see how many three combinations were taking place and if the digit is two then you will see that basically nominations were taking place in it, your digit will be two, three, four. So you will see that our 2017 combination will be generated in it, so why can we disturb it, so if we make some formula for it, then I can say, okay, I am rolling the power, okay and here I write that 3G is sacred, write it here. It was that power of two is okay and let's write here that this is three to the power of three. Okay, so our formula is developing in this manner, so finally we can say that as much as our complexity is, I am seeing it in this manner. If the length of my spring is the same then I can rightly say that if the length of the spring is Mary N, whatever length it is N then I will say that some combinations are being generated in this manner. Basically one more operation will have to be done in this that if you had seen that if our break was what was ABC was three but our what was develop, if I say that some of our five characters and here our five tractors have changed in complexity, then it is okay. If we assume that the number of characters can be finalized in such a way that the length of yours and the number of characters given to you, then it will be something like this. See you in the next video with the next question. You can support this channel, you can subscribe to this channel by going to the about section of my channel and you can access the office Google Speak To in which you will get all the solution interview daughters list whose video I have made in a category wise and whatever is related to this channel. There is news, you can see what video is going to come next and whatever is happening in the office, you can see it in Google Sheet. Thank you very much.
|
Letter Combinations of a Phone Number
|
letter-combinations-of-a-phone-number
|
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`.
| null |
Hash Table,String,Backtracking
|
Medium
|
22,39,401
|
204 |
you guys this is easier as we can go in this video I'm going to take a look at 2:04 cam crimes it's easy one but 2:04 cam crimes it's easy one but 2:04 cam crimes it's easy one but there's a lot of hints here if you have time you can look at it carefully about how to include through the approach and yeah let's forget so for the naive solution to determine to check if a number I is PI we walk divided I with all numbers from 0 to square root all right and we get the result if this integer then it's not the prime so it will cost us actually square root and for the number and there will be n numbers so generally you should be something called this right how could you improve it well factor to its prime and then we could say the for a stop prime already know we could really you know because time is 2 times 2 is 4 and then 2 times 3 is 6 so 6 is not a prime yes so when we get a number prime we could get a prime then we could filter out a lot of non prime numbers right cool that's reminds us we could use the array in spry those new array initialized net of n and fill them with truth to put it through the first zero is not pi one is not now if we look through from start from chill and stop a square root so I times eyes for the class yeah if is fine I because it's true so please cry if he's not fine like for then all the multiplier for is really calculated by two right so we could continue then if it is a prime then we mark in new numbers so we start from j.crew loose i JY we start i because if j.crew loose i JY we start i because if j.crew loose i JY we start i because if just one of the i it's already marked get a start from i and i times just for the end c++ then we mark them all as i times J plus the force right yeah and actually the technical here could be yeah it doesn't matter so this is the false okay and after this four two pistol then we get we already know all numbers less than and whether they are prime or not right number less than and right we create an array should actually feel with less than and then 0 1 the indexing stack actually the N minus 1 cool that's cool so actually we just returned reduce this is prime zero f is five pounds plus one increment it and it returned the cap is fine cool yeah this is the certain to fail really okay fall to set it folds and then start from - mm-hmm if it is not then start from - mm-hmm if it is not then start from - mm-hmm if it is not fine let me continue and we start with I and J plus oh yes right and we update I times J Possible's cool and then is five will reduce count certain zero this by the type of you that's it that's this solution let's try to analyze the time and space complexity space is obviously we use the linear space right but for time it's a very deep topic I recommend you we it's actually cannot be derived easily I think there's a lot of math here very interesting please take a look at the link attached just at the description it generally is co set to be au in la mmm pretty complicated yeah it's pretty more that's all for this one happy helps the next time
|
Count Primes
|
count-primes
|
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106`
|
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
|
Array,Math,Enumeration,Number Theory
|
Medium
|
263,264,279
|
19 |
hey everyone welcome back let's write some more neat code today let's solve remove nth node from the end of a list so we're given a linked list and all we need to do is remove the nth node from the end of the list and then return the new list so that's pretty straightforward right so in this case we got five nodes we just want to remove the n equals two so meaning the second node from the end of the list right so this is the first from the end of the list this is the second so we remove this and then we return this list which now has four elements remaining so what's the easiest way to solve this well they say from the end of the list that's inconvenient if it was from the beginning of the list it'd be super straightforward right n equals 2 remove this node how can we make that even easier i mean what if these pointers were reversed can't we just reverse this linked list start from here and then remove the second node and then we're done that's definitely a possible solution but it requires reversing the linked list which we don't actually have to do and i'm going to show you the easier way to do it so let's say n equals 2 again so we want to remove this node so how can we identify that this is the second node from the end of the list like a lot of linked list questions we can use two pointers but how are we gonna make use of our two pointers so what if i had two pointers right a left pointer and a right pointer the left pointer is at the beginning of the list and the right pointer is shifted by n equals two so our right pointer is gonna be shifted one and then it's gonna be shifted again and our right pointer is gonna be over here so now we're just gonna keep shifting our pointers until this right pointer is at the end of the list and watch what happens when we do that so we're just going to be shifting each pointer by one and this is going to make sure that the space between these pointers is exactly equal to n which is two right so now we're going to shift by one again making sure that the gap between them is still two now we're going to shift one last time because right is almost at the end so now our right pointer is at null right it's at the end of the list it can't go any farther and our left pointer is exactly at the node that we want to delete and the reason is because remember the offset between these two is n making sure that we have the node we want to delete now there's only one problem we have access to the node that we want to delete but we want to delete it how do we delete it the only thing we have to do is take this pointer cross it out and then reassign it over here right once we've done that we've gotten rid of this node so the problem is we're at this node when really we want to be at this node if we want to delete this node and this can actually be solved by another pretty common technique the dummy node right so we're going to actually have another node that we insert at the beginning of this list that we don't really use and the main thing that's going to happen is instead of our left pointer being initialized here we're actually going to initialize it at the dummy node so left is really going to be initialized here and our right pointer though is still going to be initialized over here so in reality when our right pointer reaches the end of the list we will have a left pointer at 3 and then we can update its pointer removing this node that we want to remove and to return the new linked list all we have to do is take our dummy pointer and say return dummy dot next which is going to be this node and since this is a 2.0 technique this is a 2.0 technique this is a 2.0 technique the time complexity is going to be big o of n so just like in the drawing the first thing we really want to do is create a dummy node we don't really care what the value of this node is but i'll just say zero but we want to make sure that the next pointer of this node is set to the head of the list because we're inserting it at the beginning next we can initialize our left pointer to dummy and we want our right pointer to be head plus two right or head plus n whatever n happens to be so we need a loop to do that right we can't just do that with a calculation so we can initially say right is equal to head and while n is greater than zero and right is not null we want to keep shifting right so shift right by one and decrement n by one because once n equals zero that means we've shifted by the amount that we wanted to shift by and the last thing we want to do is keep shifting both of our pointers now we're shifting left and right and we're going to keep going until right equals until right reaches the end of the list so we can shift our left pointer and we can shift our right pointer now last but not least we actually want to delete the node and remember all we need to do to delete is update the left node's next pointer and it's going to basically be shifted by one so left dot next is going to equal left dot next so for example if my left node was at my left pointer was at this node its next pointer is at 2 but i want to set its next pointer to 2's next pointer so basically what i'm doing is this and we know that dummy.next is at the head of our list dummy.next is at the head of our list dummy.next is at the head of our list which is what we want to return the updated list so we can just return dummy.next we don't want to include dummy.next we don't want to include dummy.next we don't want to include our dummy node in the output we never wanted to add a node to the list we just wanted to remove a node so our solution works beautifully we could have just reversed the list but we definitely did not need to do that i hope this was helpful don't forget to like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Remove Nth Node From End of List
|
remove-nth-node-from-end-of-list
|
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`
**Follow up:** Could you do this in one pass?
|
Maintain two pointers and update one with a delay of n steps.
|
Linked List,Two Pointers
|
Medium
|
528,1618,2216
|
451 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is sort characters by frequency so in this question we given a string s and we have to sort it in decreasing order based on the frequency of the characters and the frequency of a character is defined by the number of times that character repeats in the string given to us and our final task is to return the sorted strings if there are multiple answers we can return any one of them so let's take a look at these examples and see how we can solve this question so let's take the first example we are given the string as called treat and we need to sorted in decreasing order based on the frequency of characters so this question deals with frequency of characters so as you can see here e appears two times R appears once and T appears once directly there is a keyword that we can sort the output based on the frequency of characters so we can write a comparator which will sort the input based on the frequency of the characters present inside it and after sorting the two Es will come in the beginning then there is a r and then there is a t two e can come in the beginning then there is a t and then there is a r both are accepted and that is the expected output here so this is a very simple approach you just sort the array based on the frequency of characters and then use a string Builder so the main catch of this question is that you have to use a string Builder to form your output and then convert the string Builder into a string because finally the return type is a string we have to use a string buildup because it takes o of one time to append characters into the string Builder but if you use a string to append it will take concatenation so for example if you if there is a character e and you want to add the character F to it so this will take o of n time because strings are immutable but if you use a string Builder it will take o of one time to upend into the string so let's take a look at the code for this approach so this is the input given to us let us take the first input that is tree and I'm using a map to compute our uh frequencies so let me create a map so the key is going to be a character so we going to store the characters and the value are going to be the integers which represents the frequency of the respective character so I'm iterating through the string from left to right first we pick T So CH is now T so we check if T is present inside the map no it's not present so it will go to the else block and it will add T and set its frequency to one in the next iteration we are at R we check if R is present inside the map no it's not present so again we go to the L statement add R into the map and set it frequency to one next character is e check if it is present inside the map no it's not present so else block will be executed add e and set its frequency to one the last element is e we'll check if e is present inside the map yes it is present so it will go and execute the statement so it will get its current character and increment its current frequency with one we are incrementing it here so e has now value two and now I create a list where I create a list of all the characters present inside the map this is a key set so we get list so I name this list as cast so I get T comma R comma e as the values present inside this Cas and now I'm sorting this C by using a comparator using lambdas so I'm comparing two objects inside the string and sorting it based on its frequency so I'm getting the frequency of the larger character first and comparing it with the frequency of the next character so after sorting this will become e has larger value so e will appear first then R will appear or t will appear so it depends on the insertion because in hashmap the order of insertion is not maintained so it is based on your R time and how your uh characters are present inside the hashmap because it does not always maintain the order of insertion you can test it using an ID so let's say e comma R comma t or it can also be e comma T comma R now I'm building the string Builder so string Builder is initially empty and now I'm iterating through the characters present first character CH is equal to E and I'm using a for Loop to repeat how many times e is appearing so from the map I'm getting the frequency of e so frequency of e is 2 so this Loop will run for two times so I will be equal to zero first and then I will be equal to 1 and as soon as it becomes it uh ends the loop and in each iteration we are adding e so first We'll add one e and I is equal to one in next iteration one more e will be added and we go to the next character is equal to T now we get the frequency of T is equal to 1 so only one t will be incremented and the next iteration we are at character R we get the frequency of R is one so only one R will be upended and finally we come outside the for Loop and we convert the string Builder into a string so e will be returned as the output which is expected here so the time complexity of this approach is of n log n where n is the length of the input given to us and the space complexity is of n because we're using a hash map to compute our output now let's take a look at approach two where you can rebuild the string instead of sorting the characters present inside the string so for that we're going to use bucket sort so in our first approach we sorted the input string so for sorting we're taking n o of n log and time and now you can observe that you can rebuild the input string without sorting so for that we need to get the frequency of every character and store it inside a map so we going to use bucket sort and rebuild the string so let me show you how bucket sort works and how we can use that to build our output so let's take the same string given to us so first let's build the hash map so like in approach one we need a map to check the frequency of every character so same again key will store the character value will be the frequency we start with T add it into the map we start with r add it into the map we take e add it into the map and E is already present inside the map so increment its value so e value will become two so this is the first step and the second step is to find the maximum frequency so that we need to know how many buckets we need to form so second step is to find Max frequency so max frequency is equal to 2 so now let's form the buckets so buckets are going to be lists and each bucket represent the frequency and one observation we have to make that a character's Max frequency cannot be more than the length of the character so this is the main observation so a character can occur max length of the input string time e will Max occur length of the time so we need to store a bucket starting from value one you can have this as the minimum input and this as the maximum input so we need a bucket so this will be an array and the value of the bucket is going to be the frequency of the characters the minan frequency and the max frequency Min frequency is going to be one right because a character if it is present inside the string it can minimum appear for one time it can't appear for zero if it is appearing for zero it won't be present inside the input so minim minimum once it can appear and maximum we already calculated so first we start with Min value which is present in the beginning and we create a max value bucket which is present in the end so in this case Max is equal to two and in this case Min is equal to 1 and each bucket is going to be a list of characters so this will represent the frequency so first we have to initialize the buckets so we start a for loop from where I will start from minimum value is one so we can always start from one because we didn't calculate so in this case Min is equal to 3 and Max is equal to 3 so instead of calculating Min we're going to start from I is equal to 1 and it will go until it is equal to Max so with this loop we're going to fill the step three and now we have to iterate through the keys present inside the map so that we get how many times that character is appearing so we start with the first character is T get its frequency it is one so add it in the value one bucket so T has the value one in the next iteration we take R get its value it value is one so add it inside the one bucket so R is also here the next iteration we are at T the value is two so add it into the two bucket and now we reach all the keys present inside the input map and now we have to form a string Builder so we are again using a string Builder because it will take off one time to append characters into the string Builder and now we iterate from right to left because we need to form our string Builder BAS based on decreasing value of frequency and max value is present in the end so we use a for loop from right to left and now we pick the character present inside the that bucket so how many characters were present it having only one character and the value of this bucket is equal to two so we have to multiply e two times so e should appear two times and now we go to the next bucket is having two characters we start with this character I multiply this character with the value of the bucket is one so R should appear one time next we go to another character inside the same bucket and we multiply that character into the bucket values time that is T will be appearing T into one time that is once and now we finished all the buckets because we uh iterated from right to left we start from Max and we iterate until one and now we have a string Builder we need to convert the string Builder into a string because the return type is a string so eer T will be returned as a string which is the expected output here now let's implement the same steps which I've shown you here for bucket sort we implement the first step Second Step third step and fourth step is to fill the buckets fifth step is to form the string Builder and sixth step is to convert the string Builder into a string so let's quickly code this up stepwise and while coding you will clearly get the idea how the uh logic is happening coming to the function given to us this is the function name and the return type is a string because we have to return a sorted string as the output and we are given the input s so let's do a base check that if this input string is empty or if the length of the string is equal to zero then we can return that as the output because we can't sort it because a null or an empty string is a sorted string so we can directly return it now let's declare a map so that we can find the frequency of the characters present inside this so the key is going to be character and the value is going to be an integer now let's iterate through the input string s by character using a 4 H Loop so we access the string character by character for that I have to convert this input string into a character array so I use the two car array method and now we have to insert this character into the map as it as its key so map dop put of the character so that is CH and the frequency I'm going to get the current frequency and use the get or default method to get the current frequency if there's no CH present inside the map we will return zero it will return zero or it will get its current frequency and increment it by one and now to implement bucket sort we need to find out how many buckets we need to place for that maximum frequency of a character so which character is appearing max amount of time for that let's use a variable Max and initialize it to the minimum possible value and now we keep updating the max variable using the mt. max function and compare it with the current Max or the current frequency of this character so map. getet of CH will give you the current frequency of that character and it will keep comparing itself with the max variable so this for Loop will give us the map filled with the character and its frequencies and also a Max frequency variable so better name this variable as Max frequency and now we need to initialize the buckets so I take a list and each list is going to contain a list of characters which are having the value of that bucket and this list is going to contain characters I'm going to name this list as buckets and this is going to be array list now we need to initialize a empty list for every bucket and how many buckets we need maximum Max frequency number of buckets so we use a for Loop which starts from zero and it goes until Max frequency and initialize a new array list for every bucket and this array list is going to contain characters and now we have to iterate through the keys of the map we created so for that I'll use a for each Loop where the keys are going to have characters so I declare a character and initialize this as a key I need a set of keys of all the keys present inside the input map so I use the map. key set method which will give the set of all the keys inside the map and now we need to get the current frequency so we will get that by finding out the frequency of this key so map. get of key and now we need to add that character into this bucket so buckets dot so we need to get the bucket value first so in which bucket you want to add that character so get the bucket value by using the frequency variable and add this uh key into the bucket and now we have the bucket value and for that bucket value we have the character present inside the bucket now we just need to build our output so we use a string Builder to build our output and now we have our buckets arranged in ascending to descending order start with the maximum value bucket which is at the rightmost index position because we need to arrange it based on decreasing value of the frequencies so the max bucket value is present at the rightmost position so iterate from right to left so I create a variable bucket value and iterate from the end of the list I get the end of the list index by buckets. size minus one and this bucket value variable will iterate until it reaches the value one because there won't be any bucket value of zero count because if a character is present inside a string it will minimum appear for one value and we decrement the bucket value variable by one each time so this is capital V and now we need to get the character to append it into the string Builder and where is that character present it is present inside the bucket so we'll use a for Loop to access all the characters inside the bracket from right to left so initially we start from the last bucket value so get the character so the character is present inside the bucket right so buckets Dot and which bucket you want to access and you want to access this values bucket and this will give us the character now we have the character present inside the variable CH and now we need to append it into the string Builder but we need to see how many times we need to append into the string Builder that will depend on the bucket value right so we need another loop so I use this variable called value which is initially zero and it will iterate for bucket value number of times so bucket Val and Val ++ because we need so bucket Val and Val ++ because we need so bucket Val and Val ++ because we need to increment our value so this for Loop is for knowing how many times we need to append this current character into the string Builder so for example two is appearing two times right so the bucket value is equal to two so this for Loop will run for two times and which character is present inside that bucket we are checking which character is present and storing it inside the variable CH so append that character into the string build up so s sp. upend of CH and now finally outside the for Loop this for Loop will construct a string Builder and we have to return a string so convert the string Builder into a string and return it as the output now let's try to run the code the test case are being accepted let's submit the code and a solution has been accepted so the time complexity of this approach is O of n where n is the length of the string s and the space complexity often because we're using a map and also a list of buckets to construct our output that's it guys thank you for watching and I'll see you in the next video
|
Sort Characters By Frequency
|
sort-characters-by-frequency
|
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.
Return _the sorted string_. If there are multiple answers, return _any of them_.
**Example 1:**
**Input:** s = "tree "
**Output:** "eert "
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer.
**Example 2:**
**Input:** s = "cccaaa "
**Output:** "aaaccc "
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers.
Note that "cacaca " is incorrect, as the same characters must be together.
**Example 3:**
**Input:** s = "Aabb "
**Output:** "bbAa "
**Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect.
Note that 'A' and 'a' are treated as two different characters.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s` consists of uppercase and lowercase English letters and digits.
| null |
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,387,1741
|
1,800 |
zero maximum ascending sub arrays up hope you guys subscribe to my channel also given already positive numbers and uh so basically in array numbers and uh basically uh ascending means that uh a sub array that means that satisfy this relation right so basically for oi so basically increasing right and uh cannot be the same this is called ascending array okay so and you need to return the sum of the maximum sum of the ascending sub array okay some array need not to be uh contiguous uh sorry as defined as a contiguous sub sequence oh so must be uh must be contiguous right okay so uh right so uh in this case that 10 20 36 is not 60 right about 5 10 50 65 okay so 65 is largest oh so contiguous okay so and uh 10 20 30 40 50 will be 150 for this one is 10 11 12 right ascending 33 and for this one and uh i don't know i mean in the first time i use a dp but i just figure out is contiguous okay so we may not need to use this winner may not use dp right but okay so let's define dpi but dpi to be the maximum contiguous uh sum and that's at i right so since it's contiguous so actually uh this is uh not it's very simple right but just something ends at i and always maximum sum okay so basically um is here right and the maximum sum okay maybe it's here okay so uh what's the relation with dpi plus one right so it's very simple if the nums of i plus 1 greater than numbers of i that means that i can add another term right so that means dpi plus 1 can be use a dpi plus nums i right so i can just add the term otherwise that i need to restart right so else so it also means that i need to restart so dpi plus one just returns just as it numbs i plus 1. okay so this is just dynamic programming equation and uh you can but since it's one dimension right so each time you need to return you can update a maximum right so you can initialize the answer to be the beginning right so answer can be uh the first element so let's say the answer initialized to be uh divided with dp 0 basically it's num 0. and the after each step that you can update uh you can update the answer right so dp i okay so finally you just return the ends okay so that's code uh so let's end the length of nums just for convenience dp divided zero times n and the dp0 initialized to be num zero and answer initialize to be num zero and then go to one to n if the this number is greater than previous one that means you can do the update otherwise you cannot do updates you need to restart and then you return and update your max unanswered okay so that's it uh probably this is not the best way right let's open solution okay so let's see you guys next video
|
Maximum Ascending Subarray Sum
|
concatenation-of-consecutive-binary-numbers
|
Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**.
**Example 1:**
**Input:** nums = \[10,20,30,5,10,50\]
**Output:** 65
**Explanation:** \[5,10,50\] is the ascending subarray with the maximum sum of 65.
**Example 2:**
**Input:** nums = \[10,20,30,40,50\]
**Output:** 150
**Explanation:** \[10,20,30,40,50\] is the ascending subarray with the maximum sum of 150.
**Example 3:**
**Input:** nums = \[12,17,15,13,10,11,12\]
**Output:** 33
**Explanation:** \[10,11,12\] is the ascending subarray with the maximum sum of 33.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
Express the nth number value in a recursion formula and think about how we can do a fast evaluation.
|
Math,Bit Manipulation,Simulation
|
Medium
| null |
1,092 |
Hello guys welcome back to decades in this video you will see the artist ko man super sequence problem user variation of the longest comment subscribe isse tis from list ko number 109 to and widening programming show latest reader problem statement no problem given two strings struts2 return The Short History of Meghvansh Subscribe Multiple Answers in Return Stringer Subscribe Number of Characters from Possible 10 Characters from Its Distinct Is Not Have No Definition of the Subscribe So Let's See What Will Be the Problem No Problem Will Bring to Front Who is the First One Is Finding the Length of the Hottest Woman Super Sequence Chand Second Problems Finding the Shortest Ko Man Super Sequence String OK Sudhir Va Most Commonly Asked Questions for this Type No The prerequisite for solving this problem is knowing all about longest subscribe and subscribe this Video uploaded in this Video You Can Replace You Already No Problem Veer The Super Subscribe The Subscribe To Good Number Of Cents A String Will Be Present As Subsequent Stringer Stree Acidic District Race 2 And Disinterested Rings Two Will Also Be Present Subscribe Solved Very Simple Type Of Subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe the Hoon To I Hope That You Already Know Water Sequence Real Image Sequence Means The Characters Will Be Arranged In Order Okay So You Can Directly Receiver IDBI Jin You all subscribe Gagarsi Chief only and in between the number of characters but subscribe leaders but not always a simple super subscribe to the Page if you liked The Video then subscribe to the S3 will also be a super sequence because if you take the subscribe after Distic S One In Distic Shree Leather Industry subscribe and Shoes District Race 2 and subscribe the Channel Please subscribe and subscribe the Channel And subscribe The Amazing Subscribe BJP Will Make Hair You Can Straight-Seedhe This is BJP Will Make Hair You Can Straight-Seedhe This is BJP Will Make Hair You Can Straight-Seedhe This is Common in Both Cases The Only One 100 Sincere Writing The common character is only for the length of the subscribe button subscribe first wwc2 from the best possible super cars subscribe and subscribe the Channel and subscribe well apse ok notification string S2 and subscribe the Channel Please subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe to goals quarter navagachiya one to the goals so they can take the example understand how to find the length of the subscribe and will be the chief subscribe button to the subscribe The Channel and subscribe the Channel After and Before Writing This Common Sea Only Once and Reduce the Length of the Super Sequence 1817 Will Not Considering Its Characters But Will Be Considered as Was Born in English subscribe to subscribe And subscribe The Amazing Friends Only One Thing To remember me to the meaning of the industry subscribe now you can see in this letter this is pe good night so friend like this thank you can see reduced rings railway vacancy this is a sworn in as president of the subscribe and subscribe ho navodaya common and For this reason only you can see the order of characters can be seen from left to right subscribe and subscribe the Channel and subscribe mein one limit is the number of common characters which causes effects and find the maximum number of man characters in which can reduce. Characters Only One Should Not Rise In This Distinct Maximum Number Of Characters Between Which Two Is The Problem Is The Longest Subscribe To Subscribe Longest Overlapping Number Of Characters From Left To Right The Longest Subscribe To The Channel That No One Sees No The Longest Of Mansab Sequence When They Can Include Dost Characters Only Ones Who Will Win This And You Only One So You New Stringer Female Lil Boosie And You Can Avoid You Can See 100 District 3050 This Is The Super Sequence No You Can See The District Magistrate Banned BSE Subscribe this is page subscribe if you like subscribe and subscribe the Channel Well actors only one rate for this will be giving is the shortest super sequence that is you will be able to find the subscribe not remember there first loss to find the length of the Super Hits You Can Find The Length Of The Character subscribe And subscribe The Amazing Celsius Latest Consider Only For You Quid You Consider One Common Character Day You Will Have To Introduce Character Only One And What Doesn't Consider The Characters with Tilak considering this will only one time watch your character is only from subscribe kare subscribe for watching this Video subscribe kare only plus phone number of characters when you are reading side by side but when you are considering all the common characters urine trading account characters Only one note are you all subscribe number of characters which are included in this app you will find the length of subscribe and subscribe the Channel Please subscribe and subscribe the length is 6 7 4 CS length will be equal to one plus and minus Celsius which will be No If You Calculate The Hottest Woman Super Sequence For Be Two Strings And Will Come On Guys Enjoy 66A Wife Bach Length 910 And First To Find The Length Of Noida Industries If You Didn't Subscribe To Subscribe The Channel What You Need To Know In The Thing To Remember Research Actually What Ever Character Is President & Character Is President & Character Is President & CEO S You Want To Include Only Ones In A Politician To Airtel Cervi 9 We Will Do It Will Sing In Celsius Chapter Okay So Dash Leti Thi They Will Get In Which Is The First Indian Warriors Boxing subscribe The Amazing Porn Will Do The Thing For Distinct Will Bring To Front Side Subscribe This Point To Point This Is Point To That Is In The World Also Including The Only Ones And They Have Included Will Increment And Interview OK So Both Will Be Prevented This Will Give The Process Will See You Again Travel With This Correct Will Be A That Nav Ten Current Character History Which Is The Famous Celsius Will Stop Will Do The Same With Two Will Keep Traveling To Avoid This Trek Subscribe Now He Did You For This Is The Character And Will Only Will Be The Only One Who Will Not Know The Current Affairs In This Is The Character subscribe to the Page if you liked The Video then subscribe to the Page Who Is The SMS This 110A Apni Se Aur Komal For this is a part of this will only be and will e will be appointed to be built in a way which will be subscribe The Channel and subscribe this Video subscribe sirvi ke din will have just copied this year and again will have copied this OTP button This is not present for this thank you all subscribe only be included in tours and travels from the point to 10 and travels and tours and all characters in between celsius chapters and everything is maintained or the most important thing you is to maintain The Order and Second Most Important Thing Is to Include All the Celsius Characters Shiva Will Not Rise in This Will Give the Hotspot Off Super Sequence Loot Died and Solving How to Find the Length of the Essay on How to Find the History of the Time Complexity and You will be nothing but this is the time of this problem table subscribe to subscribe our time complexity now let us look at the nerve-centre code for the subscribe nerve-centre code for the subscribe nerve-centre code for the subscribe string will be used for storing subscribe no one will be using pointers subscribe 2012 0 No longer will be scanning through all the elements from left to right the character of the day quick and will continue to add all the characters in order in these directions Answer String No will do the same with distic s to the sentence with the current and subscribe our Point To The Character Subscribe Now To The Character Subscribe And Will Be A Big Boobs Pe Will Keep Repeating All The Best To My Mother Characters And Will Be Left To Subscribe Buddha Leftover Characters Of One And Studd And Will Be Adding That Into Answer And Will Returns and Answers No Problem You Can See in More Claims subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page that I am finding heart spring fever 98100 first and the first column The Video then subscribe to the Page if you liked The Video then subscribe to the Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the subscribe Problem of Finding the Length of Address How to Find a String Events Problem and Comment Will Help You Soon S Possible Like Share And Subscribe Our Channel Don't Forget To Subscribe Thank You
|
Shortest Common Supersequence
|
maximum-difference-between-node-and-ancestor
|
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`.
**Example 1:**
**Input:** str1 = "abac ", str2 = "cab "
**Output:** "cabac "
**Explanation:**
str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ".
str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ".
The answer provided is the shortest such string that satisfies these properties.
**Example 2:**
**Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa "
**Output:** "aaaaaaaa "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of lowercase English letters.
|
For each subtree, find the minimum value and maximum value of its descendants.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
1,749 |
hey everybody this is larry this is me going over to two of the bi-weekly contest 45 maximum two of the bi-weekly contest 45 maximum two of the bi-weekly contest 45 maximum sum uh maximum absolute sum of any sub array so this one the prerequisite i would say for this problem is just kadene's algorithm and for that is just ignoring the maximum or sorry ignoring the absolute part of this problem uh just maximum sum of any sub array i think it's i mean it's definitely a lead code problem so if you struggle with this problem uh look for that problem and go through that problem and try to solve it itself uh the solution is it like the explanation for that problem is um it's kind of tricky to be honest uh if you're a beginner because it almost is some somewhat of a trivia of like either you know it or you don't because if you don't um it's really hard to come over with yourself i think to be honest um without like a little bit of help so definitely go through that problem and go um you know make sure you understand that and once you have that as a fundamental which i think to be honest a lot of people have stupid but that said again it is trivia so if you don't get it's okay to go back and like read up on it and learn it because there's really no easy way to do it to prove it on yourself especially during an interview right you think of it as a blessing that allows you to kind of explore the problem and once you have gotten contains algorithm and let me kind of just put it on screen well that's i actually labeled it during the contest correct uh contains algorithm uh once you kind of google that and kind of do more research and solve the code problems on it um then this problem is the difference between that problem and this problem is that you have to look at look up the absolute sum of any sub array which is just absolute value of the components um and for that for me it just becomes two problems right one is the regular usual cadence algorithm and then the second one is using contains algorithm but the negative version of it um you could also phrase it another way instead of getting the max you have the minimum because um the minimum would be the negative value which has the na the you know which when you absolute uh when you use the absolute function on it the minimum amount while you become the maximum value right so you could kind of think of it either um in either way but in those cases the implementation is a little bit uh or they're very similar uh this is just contains algorithm uh i actually know it off my head again because this is a little bit of a trivia you could kind of do proof to yourself but it i think it's really hard to kind of come up with if you don't already know it to be honest so definitely do your research on it and once you do that i just take the max of two values where i want contains on the input or contain on the negative version of the input where you know we just cast everything to the negative and then we get the max of that um and yeah and cadene is both um you can think of it as both greedy or dynamic programming depending on the proof so yeah um in terms of complexity this is going to be linear time because contains algorithm you could kind of look at it and reason that it is linear time right um because we just look at each element once uh for each version we contain and we use all of one extra space so this is going to be um you know for one core it's going to be constant space linear time and then the second chord is also the same um you can also debate that because um in that i actually don't um i think in this generator um if you make sure that this is a generator this actually does only all one extra space um but it i actually don't know necessarily how python parses this but if you're very careful about um you know or you could rewrite the function in a minor way to handle negative noun or handle to reverse it then you could get this to all one space as well and then o of n um running time because again you look at the array element once so for every element you'll get every element twice uh because you want it you run this algorithm twice and assuming that you just use a generator or something smart to make sure that um you don't create you know linear extra space by this um and in different languages you may have different things like changing things in place or something like that or using again a generator type thing um but yeah so the optimal would for this would be linear time uh constant space and that's optimal because that's just the lower bound right uh because you can't really do bet better than that um so yeah um that's all i have for this problem um you could watch me stop it live during the contest next but oh my computer was slow okay oh okay uh does it have to be at least one of it possibly empty okay you hey uh thanks for checking out the video uh let me know what you think about this problem any anything at all i hope you had a great contest and you know as i always say stay safe stay healthy um you know to good mental health and take care of yourself i'll see you next time bye
|
Maximum Absolute Sum of Any Subarray
|
sellers-with-no-sales
|
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`.
Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`.
Note that `abs(x)` is defined as follows:
* If `x` is a negative integer, then `abs(x) = -x`.
* If `x` is a non-negative integer, then `abs(x) = x`.
**Example 1:**
**Input:** nums = \[1,-3,2,3,-4\]
**Output:** 5
**Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5.
**Example 2:**
**Input:** nums = \[2,-5,1,-4,3,-2\]
**Output:** 8
**Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Database
|
Easy
|
1724
|
1,046 |
hello everyone welcome to the channel today's question is last stone weight if you are new to the channel please consider subscribing we sold a lot of interview questions on this channel that can definitely help you with your interview question says we have collection of stones each stone have a positive integer value each turn which choose the two heaviest stones and smash them together suppose the stones have weight x and y with x less than equal to y the result of this message if x is equal to y both stones are totally destroyed if x is not equal to y the stone of weight x is totally destroyed and the stone of weight y has new value y minus x at the end there is at most one stone left return the weight of this stone or zero if there are no stone left so we can solve this question using two ways either we can use array or we can use min head so we will go to pen and paper and we will see how we can solve this question through both ways after that i will show you the code for both of them let's move on to pen and paper so i have taken the example given in the question and the question says we need to take out the two heavier stones and we need to smash them so for this example 7 and 8 is the heaviest one so i will take out both of them and i will smash them and as 7 is not equal to 8 i will take out the difference of them which is 1. so my new area will be two four one and one now again i will take the two heaviest zones that is 2 and 4 2 is not equal to 4 so i will take out the difference which is 2 and i will insert 2 1 and 1. now again i will take out the heavy stone that is two and one and again i will smash them after smashing i will get one so our new array will be one and one so now i will take out the two heaviest zones that will be one and one i will smash them and one is equal to one so our answer will be zero so both stones are destroyed so we are just left with one in the array and at the end i will written one as the result so let's discuss the two ways we can solve this question one way is i will take array what i will do i will take out this array and i will sort it so after sorting it will be 1 2 four seven eight i will take out stone one equal to the last value which is eight and stone two as seven and as i will take them out i will gonna remove them and i will take out the difference of them and i will add it back to the array so again it will come to the this point we will keep taking out the two highest stones and i will keep taking out the difference of them and we will keep putting them back to the array and at the end if you are left with something in the array we will return it otherwise we will written the zero so this was the first way let's look at the second way will be we will use the min heap and how mean hip works let's take our example again 2 7 4 1 8 1 so min hip will keep the minimum value on the top and it will go like this down and down so every time if i will pop something it will give me the minimum value the second minimum value will be replaced by it so if i will take out one so if i take out one so my min hip will be this one two 4 7 8 something similar to this so how we can use min hip to solve this question so what we can do i will multiply every element in the array with -1 element in the array with -1 element in the array with -1 so after multiplying every element with minus 1 so our element will be equal to minus 2 minus 7 minus 4 minus 1 8 and minus 1 and now what i will do i will form the min heap minip will be equal to 8 minus 7 minus 4 minus 2 minus 1 and now i will take out the first element and i will keep doing this i will take out the minus 8 and minus 7 and i will take the absolute difference between them whatsoever will be the difference i will add it back to the main head and at the end if i am left with a single element i will return that single element as a result otherwise i will return 0. let's move on to coding part and let's see what is the code for this question let's see the code using array at line number 3 i am taking a while loop while the length of the array is greater than one at line number four i am sorting the array at line number five i am taking out the heaviest and the second heaviest zone and i am checking whether their value is equal or not if their value is equal then i am just removing them from the array else if their value is not equal then i am taking out the difference of them and i am putting it back in the array if you look at line number 8 i am just taking the difference and putting it back in the array and i am again modifying the array at the line number nine and if after doing this we are left with anything in the array i am returning the value at line number eleven else we will simply written zero so this was the solution using array let's check whether it works or not so here i have submitted my code and it got accepted so this was the code using array let's move on to the code using mnhape so this is the code using min heap at line number 3 i am just converting all the values of the array to their negative value and at line number four i am happifying the array so this is how we make heap in the python at line number five i am taking a while loop while the length of the array is greater than one at line number six i am taking out the first heaviest round and how i am doing that i am just popping out the value from the heap and i am taking their absolute value at line number 7 i am taking out the second heaviest zone at line number 8 i am checking whether their value is equal or not if their value is not equal i am taking their difference and i'm converting it back to the negative and i'm pushing it back to the heap and after doing this if i'm left with something in the array i'm returning that value otherwise i'm returning 0. so this was the code using heap so let's check whether it works or not so i have submitted my code and it got accepted so this was the code using mnhape if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
767 |
all right let's talk about reorganized strain so given the string as rearrange the character of s so that any two adjacent characters are not the same return any possible rearrangement of s or return the mp if not possible so the idea is a b right you're done epa and this can be done by a hashmap so key will be a character and the value will be the frequency of the character and then i use the priority queue to actually compare the uh the frequency for that character so i would just make sure that when i uh when i pull the right character and then append to the string so um i'm going to write the code right now and then you will just follow along character integer okay and then magically hashtag then i would just traverse the stream it's the srp jar array and then i'll just append left up put the this is just adding all of the character into the map so it is occurred in they did not inside the map i would just initialize initial character and then plus one which is the frequency so i have a priority queue and this is the getter but the pq is actually depends on the frequency uh for letter price occupier pi over pc so kb this depends on the network so the order is the biggest one goes first right and i do need to add all of the so i need to add all of the g all of a character into the priority queue and then uh that will generate a frequency i'm a little general order for the pq right so i know for mapped key sets right so i'm going to try uh traverse the so roughly 2.5 2.5 2.5 so if you say greater than zero which is incorrect because um maybe you have two three characters right so when you pull and so you uh every time you pull you have to pull twice right so this is better to use one and then at the end i was just making sure if the pq is empty or not right so at the end i'll just making sure the pq is empty enough so let's just back to the well loop so if the picot the size is greater than one then i need to pull right so iron trial current so p double and also the next equal to p to double so when i pull i need to decrement the frequency in the map right so i have to put current method current and the minus right and this is a little bit of fencing for the next and later on i need to add into the stream right so i need to because it you return stream right so i need to create a studio then i will just add a pen hd.pin append the current first then sp.n next later sp.n next later sp.n next later so i need to make sure if my um if my frequency is greater than zero if this if that's true then i need to add into the priority queue again because i pull the character out which is not in the pq anymore but if this frequencies account frequency count is still greater than i need to add that into the pq right so current is greater than zero i need to add the term back to the p2 also the next right okay after i need to use making sure is my pq empty if not let me i need to pull right okay without glass equal to p q dot so if this character frequency is greater than one this is invalid because you have um more character to repeat um for the string imagine is a b right you pull in b out right and then you append through a string then the size is actually one because you only remain character a right and then when i pull okay sorry when i break out the value i need to come to the stammer because pq is not empty because a is still in there right so the current string is actually a b right or b alright it doesn't matter actually is a b uh a b okay and i need to pull right so paul is actually uh he's actually character error i need to making sure if my count frequency comps is greater than one so if i get log it's greater than one you just return empty because you cannot actually generate about this rearrange stream for the for s right and if not let me just append a speed of 10 and then you need to return the string format for stringbuilder and this will be your solution and they just run it to see if i have any typo now okay i do priority new priority yeah i do like apple let's do it again all right let's pause the test and this is good right so let's talk about time and space compressive and they just go from the top to the bottom this is olivine right and priority queue you actually said uh um no matter what is it's going to be unlocked in right it can uh represent the number of uh of s right the number of categories so an oven for key only so all of them and this is actually all of them as well and for the put all of one append all the font get pulled for one and then you add it's actually unlocking right you when you add back into the piece you need to um compare the character inside the p cube so all of n times n log n which is a square log n right and this will be like uh one for gate for a pen and this is so the worst case i'm going to talk about worst case unsquared login because the value does need to add at the kerala in the pq so this will be a worst case for the time capacity right well the space complexity is actually all open right you just add every character and then the focus account into the map and this will be the solution so uh space is open time is on the unsquared logarithm and if there's any question leave a comment below and if you feel helpful subscribe like the video if you want it and i will see you next time bye
|
Reorganize String
|
prime-number-of-set-bits-in-binary-representation
|
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.
Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.
**Example 1:**
**Input:** s = "aab"
**Output:** "aba"
**Example 2:**
**Input:** s = "aaab"
**Output:** ""
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
|
Math,Bit Manipulation
|
Easy
|
191
|
1,463 |
Hello everyone welcome to my channel Quote Story with Mike So today we are going to do video number 88 of our dynamic programming playlist. I have heard that this is a very popular question and it is also a hard mark but we can make it very easily with three approaches. OK, we will take recursive memoization on 3D bottom up and then make the same on 2D bottom up. Lead code is 1463. Ok but I am pretty sure that I will make it very easy for you. This question has a very similar problem but that is the easy version, that is the minimum falling. Path Sam, this is already in my playlist, I will put the link in the description. If you look at it, you will get a good idea of what you have to get a good idea of what you have to get a good idea of what you have to do here. In this problem, it is ok. Google.nl is there, it is telling the count of cherries, Google.nl is there, it is telling the count of cherries, Google.nl is there, it is telling the count of cherries, ok. Now what happens after this is that there are two robots, one robot is sitting at 0, column-1, okay and return maximum robot is sitting at 0, column-1, okay and return maximum robot is sitting at 0, column-1, okay and return maximum number of cherries collection using both robots by following the rules below, okay how many maximum cherries is this. People will be able to collect its count, you have to send it, they have to follow the following rules that if any robot is standing on the platform then if it has to go to the next row because look, both of those robots are still in the starting row, see 0 Call My There is a robot here. So if they have to go down then they can go only in three ways either i p will be 1 because for both the row will increase right but if this He can choose that column, either he will go to J-1 He can choose that column, either he will go to J-1 He can choose that column, either he will go to J-1 column here or he will go below or he will go to the right column, this also has the same option that he can go either here or here. Okay one. Any robot passes through a cell it picks up all the cherries If it goes to a cell it will pick up all the cherries there and the cell becomes MT OK When both robots stay in the same cell only one takes the cherries This is an important point that if we think that somehow there was a cell here and this robot came here while moving and this robot also came here while moving, then see both the robots stood on this cell. So the cherries here will be counted only once, it will not happen that there were five cherries here, so he picked them up, we counted five, and if he picked them up, we counted five again, it will not happen that he is counted only once, and I Think, this is the most important part, okay, what after this, both robots cannot move outside of the grid at any moment. It is obvious that robots which are outside of the grid cannot move, both robots should reach the bottom row. In this grid, it is an important point that both the robots have to reach the bottom of the grid, that is, they have to reach the last row, they cannot stop in between, the maximum amount of cherries they can collect while going from top to bottom is You have to send the count. Okay, so let's look at this example. In this example, I will tell you how its answer is 24. Like suppose this robot one is here and robot two is here, so see robot one A went here, he said three. It picked up because it was sitting here, okay, after that it went down, it picked up a two, this is it picked up a one, and after that it will go left, here it will pick up a five, okay, and after that, see what will happen to this robot. Will pick it up And this robot will pick it up Okay, this robot will pick it up This robot will pick it up So let's see how many cherries are collected in total Let's see that of robot one 3+ collected in total Let's see that of robot one 3+ collected in total Let's see that of robot one 3+ 2+ 5 + 2 Let's see that of robot two 1+ 5 + 5 2+ 5 + 2 Let's see that of robot two 1+ 5 + 5 2+ 5 + 2 Let's see that of robot two 1+ 5 + 5 + 1 How much is the total is 24, ok, + 1 How much is the total is 24, ok, + 1 How much is the total is 24, ok, now look 5 2 7 2 9 3 12 5 one 6 5 11 one 12 24, the answer is 24, its ok, so I understand what is happening. It is here, isn't it? To a great extent, you must have remembered the Minimum Falling Path Sum which I had solved. I also have a video on it. So, let's see how we will solve it. We will understand it from within. First of all, let's see why Grady failed. If he will do it then see, first of all it is the human who checks Grady. Right, I had already understood in the first step why Grady is failing. Look, you will catch it in the first step itself. See how they accept that you are standing here, robot. Now look at the robot one, it has three options, one is this but is out of bounds, one is below and one is this, it also has three options, one is this and one is out of bounds, if it will not go here then you Tell yourself, if I say to Robot One, brother, go where Max is, that means I am saying, follow Greedy, follow Greedly, run away wherever Max Cherry is visible, then Robot One will run here, now let's follow Robot Two. When it comes here, the max is seen to be F and in forest, the max for the robot is five, so if it comes here too, then remember, if five comes twice, then this cell has to be counted only once. This one is the one which The cell came only once because Robot One went there and Robot Two also went there, so I will count it only once. Okay, after that the same thing will happen again that Robot One went to Max and went here. Let's assume. Robot 2 has gone here, okay, so you are seeing a disadvantage that you will not get the maximum answer, and understand why you will not get the maximum, you can see here, if I had sent Robot 1 here and Robot 2, If you send me here, see, this two also came to me, five also came to me, after that, robot two would take this, Robert one and this would take this, okay so see, take this and this would take this, okay so see, this two had missed ours. Out of greed, we sent Robot One here. We also sent Robot Two here. Unfortunately, we can count a cell only once. Okay, so Grady has failed here, Grady, so we are not going to apply at all. Come on, come on, this. We have cleared the matter first and it became good for us that we cannot apply Greedy. Well, as of now I do n't even know that it is okay, it is not Greedy, then what approach should we apply? This is what happens in the beginning. So if you don't know anything, then see for yourself, let's assume that there is robot one, which is obviously a robot, and it starts from 0, okay, so now see why this question has become tough, because there are two people, right here. If there are people, then let's go by the value, robot one which is at 0, okay, so now it has three options, either it will go here, or it will go down, or it will go here, okay and similarly, where is robot two at that time? It also has three options, either here or here. Now look at one thing, pay attention to one thing. If robot one follows this path is fine, so I erase the rest. Erased both of them. So robot two has these three options. Okay, so this is a possibility. If robot one had not gone here, he would have gone here, still robot two has these three possibilities. Here and here you are seeing this is a completely different confine, this is complete. There are different confines and this is also a completely different confine. You see, there are a lot of possibilities that if robot one goes here, then robot two will either go here, or here, robot one will go here, if robot one goes here, robot two then robot two will go here. Either it goes here or it can go here, okay let's remove it now and if robot one goes here then robot two also has the same three options again, so you noticed one thing, every possibility for robot one. For either here or for here, there are three possibilities here, three possibilities, isn't it clear till now, so see, now if we show all these possibilities separately, then how will Robot One be? This is if it goes here, look, I am talking about the first one, so look for this, robot two can go either here, or here, look, robot two can go either here, the second case is robot one went here. Robot 2 can go here either way. Third case: Robot 1 had 2 can go here either way. Third case: Robot 1 had 2 can go here either way. Third case: Robot 1 had gone here. Robot 2 can go here. So you see case three, Robot 1 has come from here only. In the case in which Robot 1 had gone here, now in the second case. It comes when the robot went down, it is just down, then robot one, if it went just down, then robot two has three options, either go here, or robot two also goes down, or robot two also goes to the right side, this is also Three possibilities have emerged. Now let's see, there are three possibilities. What happened in this is that Robot One had not gone here, so this time also Robot Two has three options, one is this robot and one was this robot had gone here for Robot Two. Robot and here I went to Robot too, I went to the right, so you see, a total of nine possibilities have come out, so let me tell you here, why I made this and showed it to you so that I can make you understand that there are so many options, okay now you one Pay attention, this was at 0 n. If we follow this path, then I will say, okay, follow this path, explore and come up with the best answer, send it to me, okay, whoever brings out the best answer. Yes, send it to me, then I will say, okay, you follow this path and bring the answer, then I will say, follow this path and go ahead and bring the answer, okay, I will say this only, go ahead, find the answer and bring it. Go find out the answer and bring it and so on. The answer will come from all the possibilities. The maximum answer will be the maximum of all. Out of all the nine cases shown above, the maximum answer will be my answer. It is a very simple thing. I told you that if it is r1 then it is okay, if it goes here then r2 can also happen, one case goes this way, either r2 goes this way, the second case is this, either r2 goes this way, the third case is this. So I stored the maximum answer that came from these three, now it was possible that r1 might not have gone there but would have gone here, still r2 has three possibilities, either here or here, these, which is the best answer among these three possibilities. If I store it then whatever best answer is coming in each case, I will store it, which will be the best answer in the ultimate last case, that will be my answer. It is clear till now, okay, so now one thing is very simple and clear clarity. We say ok, great, we will explore, there are many options, there are possibilities, so we will pass the grid. Let's assume robot one was standing at i j and let's assume robot two was standing at x y. Okay, so after this see what all the possibilities I have. Due to the value of i, if i is j, then it is obvious that the robot will go down, otherwise it will float, which means i will always be there because the robot has to go down, but there are three possibilities in the column that either it will do -1 in j. So that it goes to the left side, either it will do -1 in j. So that it goes to the left side, either it will do -1 in j. So that it goes to the left side, or it will do nothing in J, it will do zero minus of J, only J will remain, or it will Psv in J, so that it goes to the right side. There are three possibilities and for each of these three possibilities, let us assume that the robot is a robot. The position of one was that there are three paws for robot two. Now look, if robot two is in the So look here, just for this one decision, robot one has three decisions for robot two that it has to go to one row, that means it will go to the next row, let's check the column that it is either Will it go to I or will it go to Tova Pv Then what is the second thing that for this design robot one robot two again has three decisions there are three possibilities wa mine wa pv sorry wa andva pv Similarly for this here also three There is a possibility for robot two, so you are looking for each possibility for robot one, there are three possibilities for robot two, so what is the best way to write it? Look at the column that is there, it is being mentioned once, okay. Once the number is not there, nothing happens, it becomes zero. Okay, that means let's assume that once number is added, zero is added once, and one is added, then only one is obtained, then one is obtained, and one is obtained, then it is called for. Let's write in the loop, the simplest way is that what I will do is that brother, whatever the value is, I will start from manav and go with such value equal to my value, we will go till lesson equal to two, value plus is ok from -1. If we start then it will be -1, after that it will be from -1. If we start then it will be -1, after that it will be from -1. If we start then it will be -1, after that it will be plus, then it will be zero, after that it will be plus, then it will be one, okay -1 0 1, then be plus, then it will be one, okay -1 0 1, then be plus, then it will be one, okay -1 0 1, then okay, we will add in our column -101, okay, we will add in our column -101, okay, we will add in our column -101, right, we will add these three in J, right? -101 right, we will add these three in J, right? -101 right, we will add these three in J, right? -101 But for every possibility, there are three possibilities for the robot too, so let's take another variable for this is love, then for that we take Lt e -1 Lt e le then for that we take Lt e -1 Lt e le then for that we take Lt e -1 Lt e le = 1 Lt P p, it is clear till here. So now pay = 1 Lt P p, it is clear till here. So now pay = 1 Lt P p, it is clear till here. So now pay attention to one thing, this will reveal all the possibilities, wo n't it? This will be my robot for one, this will be my robot for two, all the possibilities will come out, see how j is there, j will love you, so what will come out j - 1 will come out when the come out j - 1 will come out when the come out j - 1 will come out when the value of well y is -1. Okay, similarly value of well y is -1. Okay, similarly value of well y is -1. Okay, similarly y is PS Latu, so see what is happening for every well one, every robot for one step of robot one, robot two has three possibilities, so total. A total of nine possibilities will come out, isn't it Mive 0 1 This robot is for one, for every minus and its robot two can make three moves, either that or human move, either zero or one, this -1 0 -1 01 So I wrote double for loop and -1 0 -1 01 So I wrote double for loop and -1 0 -1 01 So I wrote double for loop and removed all the combinations, till now it is clear, okay, so what I did, I took out new row, new column j + y1 did, I took out new row, new column j + y1 did, I took out new row, new column j + y1 and y + y2, okay, I write here and y + y2, okay, I write here and y + y2, okay, I write here new column for robot one new. Column for robot two is okay and b and us next new row will be same for both new row 1 = i + 1 new row 2 = x + 1 = i + 1 new row 2 = x + 1 = i + 1 new row 2 = x + 1 right meaning both its row was this so i It will be x p, okay so it is very simple, what do we have to do after this, just here, if we assume that you were currently on AJ and this was on XVA, then we will just check that both are on the same cell. No, it's okay, so I will add cherry equal to whatever value is in the grid of image j plus whatever value is in the grid of xva, added the cherry of both and here I will put a check or If it is the same sale, then it is obvious to add it only once. If you add it only once in the same sale, then I will put that check here. Okay, so I have added the cherry, after that I have added the current sale. Now I have as many as I have. There is a possibility of going down, I am exploring from here I am exploring this whole for loop, meaning I will again call the solve function that brother was grid and what was for robot one, new call one and new rowan robot two. What was the new call to and sent the new rotu, whatever maximum will come, we will take a variable, answer is equal to maximum of answer, comma solve plus in the last, I will just return whatever maximum will come in the answer, plus and the current cherry I Cherry was picked from the current sale. Okay, so now you pay attention to one thing, our simple function will be something like this is the grid, robot is one, that row is in column one and where were both in the beginning, where were they in 0 and which This is robot two, this is r1, this is r2, that row is in column two, this is zero on the starting row and n - 1 zero on the starting row and n - 1 zero on the starting row and n - 1 on the eighth column, okay till now it is cleared, after that we have to write recurs but now pay attention to one thing. Friend, do you need these four parameters ? If you pay attention, row ? If you pay attention, row ? If you pay attention, row one is going to be the same for both of them every time because look, robot one is here, this is my row number zero, robot two is here, the column is accepted. It is different, let us assume that the column is different, but every time if it increases by one step, then it is also increasing by one step. At the same time, it is increasing at the same time, so the row for both is increasing together. Okay, that means every time the row is increasing. The value of one will be equal to the value of row 2. It will never happen that this is here and this is somewhere here. It will not happen that you yourself see what you are doing every time you are row 1 and this, then always both. If the rows grow together, then the rows of both will always be the same, so there was no need to keep these two row variables, you just keep one row variable, okay, what I am saying is that here you keep only one row because the row will always be the same. B is the same for both the robots and make column one and column two and now notice one thing, our parameter was four which was the changing parameter, now it has become three. Okay, so you will remember little by little the number of parameters changing. DP array is used in the same amount of memorization, but of the same number of dimensions, but our parameter has now become three from four. Okay, so now we will have to take only a three-dimensional array for memorization. take only a three-dimensional array for memorization. take only a three-dimensional array for memorization. Okay, this is great, okay. Meaning, do we need four parameters, no, we need only three parameters, they ask this in the interview, if you had made it by taking four parameters, then definitely he would have said whether you need four parameters or not, otherwise you get relieved that yes brother, you will cry. It is the same for both, every time there is no row, keep the same table and what is ok, so what is there here, you remove this new row and this you simply remove it as new, remove it completely, it will become simple, what is this new column, new row? It would be simple, add a plus to the current row of mine and send it to new column one, new column two. That's fine, it has become very simple. If you look at it now, then you will have no problem in putting exactly the story we have heard in the code. If it should not come, then let's put the same story in the code and see whether this recursor is able to pass all our test cases or not. After that we will memorize it. Okay, so let's quickly approach the first one because it It was simple, I wrote a little recursion, we have also tried all the possibilities, what did I say, simple, I will call the solve function, okay and will pass the grid and the first robot and the second robot, both are zeros in th row, so row. So it will be common for both but yes, the first robot is on the row column and the second robot is sitting in the nth column. This was already told to you in the question. m = grid dot size is the number m = grid dot size is the number m = grid dot size is the number of rows n. = grid of 0 dot size a number of rows n. = grid of 0 dot size a number of rows n. = grid of 0 dot size a number of columns ok so this is in zero th row first robot a is on zero column second robot n is on my first column till now it is clear whatever function comes from solve I will return ok Now let's see the solve function, first of all we were passing it to the grid, okay so let's pass the grid, after that here I write row is common, okay after that c1, after that c2 is column one and column. In column two there is robot one. In column two there is robot two. Okay, now pay attention to one thing, I told you that we will count the cherries. Cherry is equal to two. First of all, look at this, brother, add it to the cell in which you are now. Do grade of a current row is right and current column is right and plus grade of current row and current column two is right so we have added all the cherries collected by both the robots but remember I said that if c1 If it is c2 then look if row is same then we just have to check that if both the columns are same that means both are standing in same cell or not both are standing in same cell then what we should have done is that one is in that cell Should have been taken only once? Either do it in such a way that one cell is taken which is robot one in which B is standing. If both the cells are different c1 is not equal to c2 then what does it mean that the other Cell will also have to be taken. Cherry plus equal to two grids of same row is the same. Will we add the one in column two also? Same cell can be taken only once, is n't this what was given in the question, okay this is very simple till now. It is understandable but we have taken the current cell. In the current cell, whatever cell these people were in, they have picked the cherry on top of where to go further down. Beyond that, we have options, hence we will have to write recurs. Do you have any options? I told you that for int i = 0 aa is sorry 0 not -1 that for int i = 0 aa is sorry 0 not -1 that for int i = 0 aa is sorry 0 not -1 aa < i 1 aa p for int j = -1 j is less aa < i 1 aa p for int j = -1 j is less aa < i 1 aa p for int j = -1 j is less equal to 1 j+ equal to 1 j+ equal to 1 j+ p ok. Remember, this was for robot one and this was for robot two. For each position of robot one, robot two has three possibilities for one step, that is why we have written double for loop. It is clear till now, never mind. No, you yourself know what the new row is going to be, what will be the right new row, brother, the current row is a plus and it is obvious that those people are going to go to the next row, but what about the new column one where the new robot one will go? The value will be here, I write new column one is na then what will happen see c1 plus is simple s that after that what will be new column two is c2 ps j is na is very simple so what will we do now answer one answer will be kept available That we will keep finding the maximum of all possible answers from each path. Answer is equal to maximum of answers. Ok, solve. We will call again grid co- grid co- grid co- neuro, after that new sew, after that new c2. It is very simple, I have not written anything fancy till now, I am very simple. It is written only as recursion, right then in the end you do not have to do anything. Return the amount of cherries you picked in the current cell and add the maximum amount of cherries you picked from the cell below that. The answer is always updated in the maximum. Here and return it might be looking quite simple till now, okay, now don't pay attention to one more thing, it is an obvious thing friend, if we assume that your column one and column two which you have calculated, if it goes out of bounds. So please check here that the new c1 should be greater than equal to 0 and the new c1 should be less than n. It is clear here and also for column two. Check that new a c2 should be >= also for column two. Check that new a c2 should be >= also for column two. Check that new a c2 should be >= 0 and n new c1 a c2 should be less than n so it is obvious that only then you can call, if there is no safe column then you will have to put the check, now you have written everything. You have finished it but you have not written the base case till now. Right, see for yourself, we have checked the safety of the column here itself. A time will come when all the robots will reach the last row and they will have to wait in the last row and till the last row. As much as they have collected in m, that's the end of your story. So if jo row is ha na, if it becomes greater than or equal to m, means it has come after the last row, means it is out of bounds na means last row. Finished the work of A and then reached outside, so it is out of bounds, isn't it greater than equal to two? If A is done, then what do we have to do, make the return zero because now it is obvious that all the days are over, so now some coins, some cherries. You are not going to get it, no, cherry edge, we are out of bounds, it is clear till now, a simple edge that and yes in m, let's define it outside, okay, let's run it, but we have not memorized the example test cases here, so pass. It should be done. Actually, after submitting, you will see that the time limit will give one seat because I have already checked. It is okay that this time limit was giving one seat. Let's see, after that we will memorize it. See, the time speed has become 19 tests only. If the cases are passed then it is fine, so let's see, three parameters are being changed to memoize it, so my DP array will be of three dimensions and let's see the size of the maximum index. What is the size of the grid? It is given as 70. So here I take 71 is not 71. The maximum value of both row and column can go up to 70, so I took one more. It is okay for safety, it is clear till now and before doing anything, I check it beforehand. I will say that if t of current row comma current c1 comma current c2 is not equal to -1 then brother return t of Roma c1 -1 then brother return t of Roma c1 -1 then brother return t of Roma c1 and if you make a tree diagram of this then you will definitely see that there are a lot of repeated sub problems right. There are a lot of overlapping sub problems and you will see them clearly and here we set the meme. Let's set my size off so if it is a repeating sub problem then definitely we should do a memo. Right, let's do a memo here. Let's pass example test cases. Once it is done, we will submit it and see if it gets passed. But after this we come to the bottom up approach which is quite good. We will copy and paste exactly the same code as usual. See if it is passed then now we People will copy and paste the same code and write its bottom of approach. Okay, before moving ahead, its time complaint is look. Ro * c1 * c2, complaint is look. Ro * c1 * c2, complaint is look. Ro * c1 * c2, we have taken this three dimension. So, at the most, we will take so many states. Let's assume that we have Ro. How many m are there and how many columns are there, n is for c1 and one more n for c2, we will visit the same number of states for each state but see here we are running a for loop, double for loop but what is its size? Its size is three because see -1 is row, it size is three because see -1 is row, it size is three because see -1 is row, it will work for one and its size is also three -1 0 will work for one and its size is also three -1 0 will work for one and its size is also three -1 0 and if it will work for w then 3 cos 3 i.e. and if it will work for w then 3 cos 3 i.e. and if it will work for w then 3 cos 3 i.e. this for loop will work only nine times, so here you will do * 9. So this is the time here you will do * 9. So this is the time here you will do * 9. So this is the time complexity, you can also remove the nine because it is constant, it is okay and you can see the clear cut space complexity, what is the o of m * a n * n because we had taken 3d er, * a n * n because we had taken 3d er, * a n * n because we had taken 3d er, right 3d, oh we had taken it, that is ours. Before coming to the space complaint bottom up, first make it clear to me that see how many variables are changing, that is, c1 and c2, three variables are changing, so it is obvious that to solve the bottom up also, naturally this is in your mind. You should understand that yes brother, three states are being taken, so I want three DPs, three sizes of DP, so I should take bottom up DP, okay, you must be understanding this much, it is clear that bottom up DP. If we write then this will be our DPR. Okay and after this we have to define the state. Okay, let's define the state. Now look, first tell me what is the question asked, that is the state, what is asked in the question, maximum cherry, when and how much can you lift. Yes, so here I will write the same that max cherries is collected by aa and r2 till which row is Roma sew for rv and Roma c2 for aa2 means this one will be row and this one will be c1 this one will be c2 so The maximum amount of money people can collect till this position is ok till now it is clear, now you answer my very simple question, see this example, I have taken two very important things, I will tell you here and that is a very important observation. First of all, look, obviously you know that both of them had started with zero throw. Okay, both of them had started with zero throw. And this guy The robot one was in the zero column and the robot two was in which column. If there are n columns then n mine was in the nth column. Okay, it is obvious that it was standing here. Robot one was here and robot two was here. But this is my row, it is clear till now, so now tell me one thing, understand the meaning of the state, what is being said in it, Maximum cherries collected by r1 and r2 till row c1 row c2, so now which one am I am c1 row c2 till row c1 row c2, so now which one am I am in row, I am on row number zero, so till row number zero, how much must they have collected till now, brother, the answer is very simple, take the count of all the cherries where both of them are standing, ok, very good, so I am simple. What will I do here, I will write here, okay brother, whatever is my t, its zero is the index and zero is sorry 00 in n-1 and what does 0 n-1 mean that 00 in n-1 and what does 0 n-1 mean that 00 in n-1 and what does 0 n-1 mean that this is row zero and robot one is zero in column P. The robot is standing in column two, okay, and till 00 n-1, how much has he and till 00 n-1, how much has he and till 00 n-1, how much has he collected, okay, since this is the first row, so yes, I will simply add whatever value is there in the grid, see what. I will add that, look, the grid was zero throw, okay, the column of one was zero plus what was the column of the second robot, grade was 0 n -1, right, the last column was what was the column of the second robot, grade was 0 n -1, right, the last column was what was the column of the second robot, grade was 0 n -1, right, the last column was clear, but one thing is very simple, base case means corner case. If we assume that there was only one column, then this is zero throw, first row is second row, third row is fourth row, here there is only one column, then according to the question, what will happen, robot one is also here, robot two is also standing here. Poor guy, in this case you will get into trouble, see in this case you have added its value twice because it is 0. Okay, it is accepted. Look, if the row number of the column is how many one, then it has become 1 minus 0. I have deleted it twice, so there is no problem here brother, just put a check here, if n is equal then add only once, it is ok, I will add it once, this is not a big deal, these are small checks. Which you will handle yourself, here I will put that if n = even then just that if n = even then just that if n = even then just add it once because yes start means when those people will be in the first row, if n is even then yes it is the same thing. I will add this cell once, I will not add it twice and if there is more than one, then it is okay, I will add this separately, I will add this too, okay, this was a very simple observation which I told you. Till now it must be clear to you, see one more small observation which is very simple and not a big thing, you will observe it yourself, now look at it, pay attention friend, one thing is very important and very simple thing, do you know what it was? Mann, you tell me one thing, let's go right now, don't cry, row number th, you want to pay attention to row number three, give me any row, I chose row number th, I chose it at random, now tell me row number th, which robot One is in row number three, how far can Maximum go? If Maximum wants to go, how far can it go? Let me tell you. See how the robot is one. It has to go to the maximum. In row number three, it has to go maximum to the right. How far can it go to the right? That's what I want to see. To go to the right side, it will run here. From here, it has three options, but it will run here because it has to go to the right side maximum and it will run from here too. Beyond this, robot one cannot go to row number three. Let me repeat, I want to tell you that in any row, robot one is the maximum column up to which it can go. Now, let me tell you row three and grab some other row, I will grab this row, okay. Now you tell me what is the maximum column in this row that robot one can go to, it will run here, if we assume that after this, if we assume that it ran here, then see which row it went to which column, it went till column number two only. Only it cannot go further than this, how will you take it, you too will not be able to take it has only these three options, so maximum it will catch here, it will go here, robot one also has three options from here, so maximum it will come here, and where else can it go? Can't go further here Yes, in row number three, he can come till here, Robot one in row number three, It is clear to you, You are ok, it was a very simple observation but it is a very important observation and there are many useful things if If you can tell these things in the interview, then if you tell then your image and impression will be very good on the interviewer. Okay, it is clear till now, okay, it is clear and if you ask the same question, brother, how far can the robot go to the maximum? It is obvious that the robot cannot go to the maximum right side. Poor fellow, if we check only the left side, how far can the robot go to the maximum left side. Let's check any row. Let's check row number two. Let's see how far it can go. He will go here, after this he will go here, so maximum he can go till here and let's assume right, check row number three, then in row number th and maximum he will be able to go till here, so you noticed something, but now you noticed. I must have guessed that for a given row number was three, Robot One knows that Max was able to go only till column number three, he will not be able to go beyond that, understand this, that is, if I talk about Robot One. So, how far can its column go? Max. As far as the row is, it can go only upto the value of the row, meaning, assuming that I am filling row number two, then robot one column number. It will be able to go only up to two, it will not be able to go beyond that and it is not possible. It is okay to go for that, so what does it mean that the robot is one, it can go only up to the maximum given row, its column is fine, this thing is clear to you, similarly. If you look at robot 2 also, see how far it can go maximum. Let's assume that we will calculate the number 3. It will go here and then here. Okay, then see how far it can go. Just find out how. Minus row is three, third row is n-3, okay how many columns were there in total, six columns were n-3, okay how many columns were there in total, six columns were n-3, okay how many columns were there in total, six columns were 63, move it to '0', that is, see, it will 63, move it to '0', that is, see, it will 63, move it to '0', that is, see, it will be able to go only till the maximum second column, that is, whatever row is there, move it to it, okay. Either take out n minus whatever row we are talking about, make it two, that is, the maximum column n of robot two can go only till this much, look at any row on the left side. Let us assume that for robot two, you have to take out Which column is robot two? Maximum number of rows it can go to in seconds. Okay, so simple. A number of columns minus which row is row number two. Do -1. minus which row is row number two. Do -1. minus which row is row number two. Do -1. How much is it? 6 - 2 -1 That's it. Let's see. How much is it? 6 - 2 -1 That's it. Let's see. How much is it? 6 - 2 -1 That's it. Let's see. It will go from here to here, it will be able to go from here to here, it cannot go beyond this, it can only go till the third column on the left side. Okay, so one thing, what relation have we got that where will be the maximum column of robot one on the right side? Whatever is the value of the row and the maximum column of robot two that can go to the left side, how much can it go to? 1 minus -1 is only so much that it can go to the left side -1 is only so much that it can go to the left side -1 is only so much that it can go to the left side because it is obvious that robot one can go to the right side. What is the maximum and robot two can go to the left side? How can the maximum robot go to the right? Here, it means that it will not be out of bounds, meaning at most robot two will be able to come here in any row, assuming row number is two, then here Will it be able to come till here, isn't it? It will be able to come only till here, okay, you must have understood this thing, now a very basic question is your DP, what is its dimension, how many fall loops will be required to fill it, everyone loudly. Tell me, three for loops will be required. Okay, so let's write three for loops, first for row, then for c1, then for c2. Even this may seem very simple to you, look at everything for row zero, I had already given the answer. Look, I had already removed row number zero, so I will look at row number one, okay, we will start from row equal to two, okay, row is not the number of days, it will go till row plus, till now everything must be clear. You are right, let's close this bracket. Now let's come to column one. Look, remember I told you that yes, for Robot One, where will Robot One start? Will it start from zero? What is the maximum it can go to? Whatever row is there, let us assume that if it is zero then it can go till zero column. Let us assume that if it is the first row then it can go only till the first column. It is max to max or not. It can go till here only, let us assume that it is second. If there is a row then at the most it can go till the second row till the second column, so we found a cool way that the column is starting from the first row, but at the most, till the column one which is there, how far can it go? Equal can go only till two rows, a good optimization, we got it here, okay, I made the column one plus, okay, this one is also cleared till now, we closed this bracket, this was very important, do you understand now? You must have guessed why I took it till the row here, it's okay, now yes, one more thing, please note that because of the value, if we had only one column, then look here, there is only one column in it, there is zero column, the rest are rows. 0 1 2 3 If there was only one column, then look here it gets messed up, you are going to remove row = 1 and look at remove row = 1 and look at remove row = 1 and look at column one which is equal to row two, you have made the value of row here one while the column is row. It is only in the case of one column that this code will explode, so here it means nothing, there is a very good way to save the simple thing, you can do it like this, if the value is too high here, then don't cry. If there was one then we would obviously need zero because the number of columns is the number of columns. If there is one then it is obvious that n -1 can be the maximum obvious that n -1 can be the maximum obvious that n -1 can be the maximum index, so what will I do here, simply which will be the smaller among these two. From minimum of either row or n -1 ok then minimum of either row or n -1 ok then minimum of either row or n -1 ok then see what will happen in this case the value of row is now one and n -1 see what is mine the value of n is now one and n -1 see what is mine the value of n is now one and n -1 see what is mine the value of n was one because there is only one column so n-1 should be 0 Look, this time my column one will become n-1 should be 0 Look, this time my column one will become n-1 should be 0 Look, this time my column one will become zero which is valid, if it was not there then I would have just taken row then row would be one here and my code would explode, that's why I used this trick here to avoid that base case. I am okay with that corner case and we have done this thing many times and we should also know this thing, right, so we have saved our column from this one corner case. Now let's see about column two. Okay, so look, remember I told you that column two means row two. We are talking about robot two, so robot two can go to the maximum left side in any row. How far can robot two go in any row? Let's also agree in row, if we talk about row number four, then look, it can go here and here, so I told you that my row can go till the middle, at the most it is clear till here, if you know this then here But what I said is that it can go either here or here, it cannot go further than this, it can go up to n - row - 1 in any row, didn't I tell can go up to n - row - 1 in any row, didn't I tell can go up to n - row - 1 in any row, didn't I tell you? I had told here, so here also I will do the same that this robot can go up to a maximum of n - row - 1, okay can go up to a maximum of n - row - 1, okay can go up to a maximum of n - row - 1, okay more and how far it can go on the right side, row c2 is < n. c2 + row c2 is < n. c2 + row c2 is < n. c2 + plus even till here you must be seeing everything clearly. Now look here also, here too, part of the corner may break and it's totally fine. If you are not able to catch the corner case after submitting, then If you find out the mistake then gradually you will be able to learn it. Look, if we assume that let's take the same case again that I have only one column, okay and some numbers of days are 0 1 2 3 4 5 okay, then as Let's go, now I am on row number three. If I am on row number three, then look at column two. How will it come out? n is the number of rows and is the number of columns. N is one. Minus which row am I on the third row? -1. Minus which row am I on the third row? -1. Minus which row am I on the third row? -1. Look, how much will it be? Gone 1 - 3 -2 Is it -3 Look, how much will it be? Gone 1 - 3 -2 Is it -3 Look, how much will it be? Gone 1 - 3 -2 Is it -3 then is -3 a valid column No -3 is then is -3 a valid column No -3 is then is -3 a valid column No -3 is not a valid column meaning a very negative value has gone Now it has gone to the left side It has gone to the column less than zero whereas only up to zero is a column Isn't it -1 column Isn't it -1 column Isn't it -1 column -2 column on the left side, it is a little out of bounds. column -2 column on the left side, it is a little out of bounds. column -2 column on the left side, it is a little out of bounds. Okay, so if the value is decreasing, look at the value, if the value has become less than zero, then you would want it to at least reach zero, more than that. No, it should not be less than that, otherwise it will become negative, otherwise remember in that case, we use max when it goes negative. When there is a fear of going negative, we use max. In this case, see what you will do with max off. If you go negative n minus row my then brother take zero row zero column it is zero, take zero row zero column it is ok till now it is clear so see what one thing did you learn from here that if you are getting more value like it is coming here. This is the one, so look, I have taken Min. You will remember the case here, I have taken Min and what was happening in this case is that my J was going negative. Look, I have taken Max, learn this thing. You will need a lot of things, if you are in further coding, then both of these were very important parts, this part and this part are quite good, we have made improvements here in our code, it is fine till now, these three for loops are clear. You must have understood, okay let's come to our last part, now let's see it is absolutely simple and the Minimum Falling Path Sum that I taught you in the Minimum Falling Path Sum was a little simple, what was in it was that the current cell is the value. Okay, so you had three ways to reach here, either you could come from here, or from here. Okay, so the maximum time taken to reach here in the previous row, sorry, the minimum time taken till here. The minimum time it took to reach here. I used to take the minimum time out of the three here. Minimum of. Let's say this is A, this is B, this is c, so a b c. The minimum of these is I used to put it here, okay, so what does it mean that first of all, I should have the answer of the previous question, first of all, I am calculating it in the DPR, just to calculate the next cell, I need to know the answer. I had three possibilities to come from above, it is okay but there is a little complication in going here, I told you that if I am currently finding the answer to the state of Roma and end c2, then you can see nine possibilities from here. You can go ahead in right row c1 c2, look here you have nine possibilities, c1 also has three possibilities and look for every seam there are three possibilities for c2, so it is obvious that when you have come to a cell, you have nine possibilities. Right, assuming there is a cell here, I told you above that there must have been nine possibilities of two double F's, from those nine possibilities you can come here right, there are many possibilities, from nine possibilities you can come here. This means that if you want to find out the answer of c1 c2, then remember the answer now, you can come from c1 - 1 or you can remember the answer now, you can come from c1 - 1 or you can remember the answer now, you can come from c1 - 1 or you can come from c1 in its just previous row or you can come from c1 + 1. Here in its or you can come from c1 + 1. Here in its or you can come from c1 + 1. Here in its just previous row, similarly for c2 also, if you assume in the previous row, this is the row, then the previous row would have been my row -1, this is the row, then the previous row would have been my row -1, this is the row, then the previous row would have been my row -1, there you would have come from c2 -1, either there you would have come from c2 -1, either there you would have come from c2 -1, either from c2 or c2. You must have come from + 1, from c2 or c2. You must have come from + 1, from c2 or c2. You must have come from + 1, these were the three possibilities, okay, so 3 cross 3 means there were nine possibilities, so when I come here, I will come here only with the maximum of all those possibilities, I will consider only those only. I will do it in the current cell, so that's what I am trying to tell you. Look, I could have written this for loop directly here, but to make you understand that brother, I am in the current cell, so it is obvious that I can come from nine possibilities. I am right there, from the previous row, it was necessary for us to understand those things, okay, that is why I told you these things, so now look, let's convert it into simple code, which I just told you is very simple, see this also. Please note that I told you that if you want to calculate the current cell, then tell me yes about all the possible columns in the previous row from where you would have come, here you will extract the maximum from them and then you will fill the answer here. If you want to do it then no problem, whatever is the maximum answer in the previous row, we will find it. Okay, so this is how I do it. The previous row is max, I will put it in this variable and we will find it from the previous row. So remember three nine. There were possibilities, that is, I will have to write a double for loop, for int previous, which could be my column, what could be the previous column, let me write c1, what could be current, which is my column c1, I can do -1 in it, ok my column c1, I can do -1 in it, ok my column c1, I can do -1 in it, ok till now. It is clear and how far can the previous c1 go, the lesson is equal to the current column can go up to the current column P, right because see the current column is c1, let us assume, then above it can come from here, either from c1 -1 or from c1 or from can come from here, either from c1 -1 or from c1 or from can come from here, either from c1 -1 or from c1 It can come from p, so I will check the previous row from c1 -1 c1 p to c1 + 1, check the previous row from c1 -1 c1 p to c1 + 1, check the previous row from c1 -1 c1 p to c1 + 1, right, the previous column 1 p plus is clear, till now it is clear, similarly, let's take out the int of previous column two also. B is equal to robot two columns currently c2 is c2 - 1 robot two columns currently c2 is c2 - 1 robot two columns currently c2 is c2 - 1 can come from previous column 2 < = c2 + 1 can come from previous column 2 < = c2 + 1 can come from previous column 2 < = c2 + 1 can go to previous column two plus till now you must have understood see it is the same thing friend you don't you Every line of code should be understood, only then you will be able to understand in depth how things are done. If it is clear till now, there were so many possibilities from the previous row, so I will update here, what was the max value in the previous row, what is mine? Max of previous row max comma Now look pay attention what is t of current row what is row I am looking at row my previous row comma previous c1 comma previous c2 you are looking at whatever max comes from all the possibilities I will put it here okay Till now you must be clear right now see as soon as I do this one will be finished, I have taken out all the possibilities from the previous column, sorry, from the previous row, to come in the current column, to come in c1, c2, okay. So now what will I do I simply now I have to remove okay t of the current row now I can easily remove c1 c2 e equal to see pay attention whatever my previous a row max my answer must have come okay t of the previous row So I got it, I have to find out till the current row, so in the current row, I am in this cell c1 c2, so I add its value, grid of row c1 plus grid of row c2 is clear till here, but here also you pay attention. It will happen that if c1 is not equal to c2 then only you are seeing the same cell here otherwise you will add it here, check that c1 is not equal to c2 then we have added the robot one to the grid in which There is robot two in the grid, I have added the cell in which and whatever was the maximum from the previous row, then look, I have taken out the maximum value to reach here, it is okay to reach row c1 c2, it is clear here and yes if c1 = = c2. So clear here and yes if c1 = = c2. So clear here and yes if c1 = = c2. So simply what you have to do is t of Roma c1 c2 will be equal to whatever max was in the previous row, I added it to it only once, add the current cell to Roma c1 or add c2 only. Add that cell only once. By now everything would have been clear to you. My entire for loop is over. Okay, so now pay attention to one thing. Now we have completed the entire 3D. Hey, you have completed it now. I did it with my logic, okay, once again I looked at the for loop, we had written everything after understanding it, row, column one, column two, three, for loop, I had to write because it was 3d, okay and Now it is obvious that there were nine possibilities to reach any current cell. It is okay to reach there, so we tried to reach through all the possibilities and whatever maximum value came out from all the possibilities in the previous row, that is okay and which The maximum value is taken out and to reach the current cell i.e. to reach row current cell i.e. to reach row current cell i.e. to reach row c1 c2 whatever maximum was obtained from the previous one is plus the value of the current cell and if the cells are different then if both the robots have the same cell then It will be added only once, till now everything will be clear, so it will be filled right, you will remember what we used to do in Minimum Falling Path Sum, that this last row means the entire DP, we used to fill it, this is the DP. Okay, so we had the state definition there too, what was the meaning of T of Ama, what is the minimum value required to reach here, minimum falling path of some cell, if you look at the answer, look at this cell. Look at this cell, we had to reach the last row. Right, the minimum value to reach this cell has been reached. The minimum value to reach this cell has been reached. Value has reached the minimum value to reach this cell. So remember, we had to reach this last row only. We used to choose the one with the lowest value in the last row. Here we used to choose the one with the minimum value in the last row. Ours is 3d, so here also we will do the same, which will be the last row? Understand for yourself, here the total number of days, we had m, then the last row with index m - 1 will be mine, it last row with index m - 1 will be mine, it last row with index m - 1 will be mine, it is okay. And if we look at it now, it is a 3D layer, so it is not right to say last row, it is the last layer, it is the whole, if I make it like a box, then something like this is formed. Look, pay attention, it will become something like this, okay, so last. We are removing the first layer because it is 3D, but because of not using our brain so much, it means there will be confusion, if you understand from the complete diagram, then I just know that yes, this is the last layer, no, this is the last layer and that. The layer itself is a dud, so I have to extract the minimum answer from it. Okay, so what will I do, since I have to check both of them, the whole last row is fixed, m - 1 is the last row, whatever fixed, m - 1 is the last row, whatever fixed, m - 1 is the last row, whatever minimum value is there in it. That's coming, if you want to remove it, then look, pay attention i = 0 aa lesson remove it, then look, pay attention i = 0 aa lesson remove it, then look, pay attention i = 0 aa lesson a i ps plus for j e 0 j i lesson a j plus remember d oh tha na so this was for row this was for column this also column If it is for row one, then my fix is, a row of mine is fine and after that, the two dimensions are for column one and column two, so column one is done, for column two it is fine, so our result. It will be final and out of all these, I will be the max of result comma. Look, the first dimension is fixed. We are talking about the first one because yes, I have to reach till the end, meaning I have to reach the last row only. At the end, I will reach the last row only. Robot guys ok and this would be I and this would be J take out the maximum value of all and return the result in the last ts it ok it was quite a long story but very in depth and we have covered a lot of things ok now one last thing Look here and you should have already figured it out. Look here also, here we are doing c1 -1, c1 are doing c1 -1, c1 are doing c1 -1, c1 are doing c2 -1, c2 are doing so there are c2 -1, c2 are doing so there are c2 -1, c2 are doing so there are a lot of chances that we will be out. Will go off bound. Let's say c1 is zero, then c1 will become -1. say c1 is zero, then c1 will become -1. say c1 is zero, then c1 will become -1. What will become -1 means it will go negative. So it is an What will become -1 means it will go negative. So it is an What will become -1 means it will go negative. So it is an obvious thing. To avoid that, I told you a little while ago that if it is going negative then here max. Put max of 0 c-1, okay, similarly do the same here, c-1, okay, similarly do the same here, c-1, okay, similarly do the same here, 0 c2 -1 and look here, c1 is PW, 0 c2 -1 and look here, c1 is PW, 0 c2 -1 and look here, c1 is PW, meaning it can go out of bounds too, right, so do min here, it is out of bounds, okay. So c1 Pv, if it goes out of bounds, then whatever is placed in the last column will remain till n-1, the then whatever is placed in the last column will remain till n-1, the then whatever is placed in the last column will remain till n-1, the last column will be n-1 only. Similarly, here last column will be n-1 only. Similarly, here last column will be n-1 only. Similarly, here also put minimum c2 pv n-1, this thing is also put minimum c2 pv n-1, this thing is also put minimum c2 pv n-1, this thing is important and there is a trick in it too. That brother, if it is going out of bounds in negative, then yes, you would like it, like let's assume that this is yours, it is a single column, it is okay, then if you do c1 -1, then yes, the negative will go, do c1 -1, then yes, the negative will go, do c1 -1, then yes, the negative will go, then why don't you move this row to this row. If you take the column then the same thing I did is max of 0 c1 -1 then zero of zero will come. Okay 0 c1 -1 then zero of zero will come. Okay 0 c1 -1 then zero of zero will come. Okay and if you do c1 then see it is going out of bounds so what better to do than this then minimum of c1 p 1 i.e. That n and n-1 is do than this then minimum of c1 p 1 i.e. That n and n-1 is do than this then minimum of c1 p 1 i.e. That n and n-1 is one column is 1 -1 0, if we one column is 1 -1 0, if we one column is 1 -1 0, if we take zero column then we will take this column and so look let's do min, till now it is clear, we have to do the same thing in both, just our work is complete. It's over, okay, so if you have understood the exact story, I would suggest you to pause the video and code yourself. After understanding what I told you, when I code, then there I will show you how to do this in 3D. You can convert it into 2D shape. It is a very simple observation. If you clear it from there also then let's quote it. So let's solve it from our bottom up. So yes, I told you that we are considering a 3D size shape. We are going to take, okay, for bottom DP, so t is taken and this is m row, n is column, okay and since we know the constant already, then let's take 71, okay, take 71 and all In the beginning I have filled with zero, okay till now it is clear, now here I define the state t of row comma c1 c2 what does it mean max cherries collected till where is current row c1 by robot one plus current row c2 by robot It is clear till now, okay if you understand this, then you already know the answer to the first row, in the first row, the robot one which is in the zero row is standing in the zero column and the robot which is two is standing in the eleventh column. Okay, so here I had said that whatever is the value of cherry in the grid of 0 g, we will add it to the grid of zero th column n is minus but yes we should have paid attention that if n is equal to one. If there is only one column then it means that Robot One and Robot Two are both standing in the same cell, in that case if it is equal to one then add it only once. Add only grade of 0 and if it is not so then add these. Add both of them, here it is, okay, it is clear till now let's come to our simple for loop int row equal row e lesson a row plus okay, after that look for int column 1 equal to 0 because column one robot. The left most column of one is zero, it is fine from where it started, it cannot go left from that, from zero it will never be able to go left because it is a negative index, it will not be able to go left from there, so left most, this is it. It can go right and how much right most it can go, I had told you that c1 is less than equal to, remember I had said that it can go as much as the value of row but I had done the minimum of n so that out. We can escape from off bound. You also understood that c1 pps is clear till now, okay now let's come to the rest for int c2 equal to maximum off. Look, remember I had told you earlier that n Minus row would have been limited but since it could have been out of bounds, I had earned a maximum of zero. Okay, c2 lesson n c2 p. This is also clear to you. So you understood these three for loops, right? Okay, now let's move ahead, what did I say that there is no possibility to reach the current cell, that means there is no possibility to reach from the cell just above, then I will find out the max of the previous row, okay and see all the possibilities. Yes, there is a previous call from above, what can happen? Currently, if A is currently standing at c1, then previously c1 can come from my, okay, previous call lesson is equal to c1, it can come from psv, right, it can come from above, only this much can come from previous. Call plus is ok till now it is cleared and after this what was told that the second robot is for int previous, its previous call is called one because it belongs to the first robot and here the previous call is called two. Yes, it is ok, it will come from c2 -1, previous call will go to 2 < = c2 + it will come from c2 -1, previous call will go to 2 < = c2 + it will come from c2 -1, previous call will go to 2 < = c2 + 1, it can come from previous call 2 + 1, it can come from previous call 2 + 1, it can come from previous call 2 + p, till now it is clear, I repeat again how the current came on c1 and c2. Could have come from c1 - 1 Could have come from robot one Could have come from c1 - 1 Could have come from robot one Could have come from c1 - 1 Could have come from robot one which is either could have come from c1 Could have been either from c1 + 1 Below f This is from the previous row + 1 Below f This is from the previous row + 1 Below f This is from the previous row I am looking at right and similarly for c2 also see the same It could have come from anywhere from c2 - 1 to c2 + 1 and yes, could have come from anywhere from c2 - 1 to c2 + 1 and yes, could have come from anywhere from c2 - 1 to c2 + 1 and yes, here to avoid out of bounds, I had taught you that if it is going negative then put max tax then zero is fine and if it is more than If you are going to have a value then put the minimum as the last value which can be the index number or the last of the column then put n-1. Similarly here also minimum of put n-1. Similarly here also minimum of put n-1. Similarly here also minimum of n-1 c2 p 1 and here max of 0 c2 -1 n-1 c2 p 1 and here max of 0 c2 -1 n-1 c2 p 1 and here max of 0 c2 -1 here. Okay, now we don't have to do anything, keep updating whatever was the maximum value in the previous row. Maximum previous row. Now look, pay attention, what was the maximum value in the previous row. t of row -1. Okay, previous call, one previous row -1. Okay, previous call, one previous row -1. Okay, previous call, one previous call. To as simple as that is what we had to learn, it became clear to us, okay, now after this I had told the check that now whose answer do I have to fill the answer of t of row, comma c1 c2, then I would have checked this. That is, if c1 is equal to c2 then I will just add t of row. Sorry, what will I add in the answer? Pay attention, this is equal to whatever the previous row max was, plus I will add only one cell in the current one. Roma Add c1 or row c2 and if both the columns are equal means both are standing in the same cell and if it is not so then I will add the cells of both row c1 also grade of Roma c2 also its value also Cherry I will add, okay, till now it is cleared, after that as soon as I come out of this for loop started here, this is this for this started here, this is this for loop. And the final for loop is this, so as soon as I come out, I get the result y Result it 0 for int a i 0 a i lesson a pps for int j = 0 j e < n j pps for int j = 0 j e < n j pps for int j = 0 j e < n j + result is equal to maximum of result + result is equal to maximum of result + result is equal to maximum of result Which dimension is the one with comma last? This is fixed. This last row is mine and column c is Aama j. Take out the maximum from the last one. The return result is fine, that is why I was saying minimum falling path. Do check it out, you will get the context from there, then apply that mind that we have solved this problem here also, okay submit, we should be able to pass all the ten cases, after that comes the third approach. But in which we will not make it with 3D DPR, we will make it with 2D DPR, okay look here, we have taken 3D DPR here, it can be done with 2D DPR also, now see why I am saying this, pay attention here whenever you see the previous row. If you had to find the answer, then you see, the value is just dependent on the previous row. To find the answer of the current row, see this. To find the answer of row c1 c2, only the previous row is needed. There is no need of any row before that, so why not? I take a DP, a simple node, I store the value of the previous row in it, okay, using it, I get the current row, okay, and when I go to the next row, I make this current row previous and you have done it a thousand times. This will happen, I will show it to you right now, so see the third approach, from here only you will understand, whenever you see this, look in your code, pay attention, this is the outlet for current flow, this is what you had to remove the current from, isn't it? My current state should not be said as row, current state is what I mean Roma c1 c2. Look at the answer to this, how were you extracting the previous state from the previous state. Meaning row is -1, rest of the previous column one column two is -1, rest of the previous column one column two is -1, rest of the previous column one column two is changing but row - So it will be very easy to changing but row - So it will be very easy to changing but row - So it will be very easy to get 1, if it is row then row -1 is 0 means I need information about just previous state. -1 is 0 means I need information about just previous state. -1 is 0 means I need information about just previous state. Okay, so in such a case, you always use one to store the previous state. You can take your data structure separately, that is, what I am saying here is that 71 is taken for three dimensions, you can take only two dimensions, it is okay, let's remove all this, take only two dimensions, it is okay and keep its name. Let's give and keep the trend, right? And now when I come here, I will have to find out the current state here, okay, so here I take the current vector, took the current vector, made it equal to zero, okay till now it is clear. And now look, pay attention, when I have to remove the previous key, look here, I have to do row-1, then nothing, I will do row-1, then nothing, I will do row-1, then nothing, I will directly use the previous here, that brother, this of the previous key, you say priv column one and priv column two. Find out the answer, this is it and after this, look here, I am extracting the current of this row, you see, I have defined the current, this is the current I have to extract, so see, this is not of two dimension, this is also not of three dimension, this is It is also of two dimension only. Okay, so here I made current c1 c2 and see in the previous section, this is also of two dimension only, it is clear till here, now after that look here, we had two dimension. There were three dimensions, just remove the third dimension from here, as simple as that is fine, now but pay attention to one thing here, what I said, when this current state is gone, then it should become the previous state for the next state, does n't it mean? When this for loop ends, double for loop, what it means is that now my previous state will be equal to the current state. This was an important step and in such a situation, you must have done optimization many times in your time. Okay, that's all here. There is a problem, what is that problem, I will tell you also, if you pay attention, here you cannot directly assign a definition of this type or not like this, which you define like this or not like this. Ca n't assign directly like this, that's why what should I do, I take the vector, it gets easily assigned to the vector, okay, either write a for loop and assign it to vector of int, its size is 71, vector of int. The value of all is 71, I made it zero in the beginning, I am fine, I named it Priv, let's remove it's fine, similarly, here too, the current one will be defined in the same way, it is not current, it is not there, now I feel. This will be solved now, but yes, pay attention to one more thing, yes, look here too, you should have made this change. Look, you are taking it in three dimensions. If you are okay, then make it previous and make it two dimensional. Okay, this thing is cleared and yes here in the last also we have used t, you should have taken it before, okay then see, run, you will pass and let me tell you that there are many such questions from bottom up in which current To get the answer of the state, the answer of the just previous state is required, like here also see the current state answer, meaning this one, to get the answer of this one, the answer of the just previous state was required, so of the current state, what did I just store in it? D Hey, it's okay. D Hey, I have stored it, then I have started assigning it to the current one, I have taken out the current one. Now for the next row, this will become the previous one which was just declared current and so on, we will keep updating it, okay. So you must have got a lot to learn, but I definitely want to assure you that such questions, first of all, think of the most basic solution, what was ours, recurs and memorization, because that is the first thing that comes to mind. That brother, there are three options, right, let's explore all the three places by hitting for loop, after that come to the bottom up, okay, and the reason why I was able to make the bottom up of this is because the same logic was applied in Minimum Falling Path Sum. If you watch that video, it is related to a great extent, both are fine, so let's see you guys in the next video, thank you.
|
Cherry Pickup II
|
the-k-weakest-rows-in-a-matrix
|
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100`
|
Sort the matrix row indexes by the number of soldiers and then row indexes.
|
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Easy
| null |
1,690 |
That A Hello Everyone Welcome To Day Level Tak Julie's Challenge And Aspiration To Give Seven In The Street In Three Years Of Clans Game Election Bob Unleashes You All Subscribe Problem And Solution Subscribe Different Problem Something New To Me How To Give A Valid Code Close 600 Is Try to Understand Rulers of the Question It Will Really Helps in Coming Up with Solution Questions Any Player Can Take Up Elements Only from Start and the End Not Intermediate Three Points Which Controls Sensitive Elements The You Get Score Request The Meaning of Elements Are Not The Element Brothers Element The Meaning Of Jewelry Before Playing Badminton Player Game And Yet Another Question Alerts Will Also Its President Who Found Out That You Will Always Looks Game Auspicious Just Zinc It And So They Decided To Minimize Its Difference Solve V Total Subscribe My Channel To that and drop stories brother to bit want the difference between 20 process minimum for balance want the difference between benefits maximum transformed into half inverter spider-man transformed into half inverter spider-man transformed into half inverter spider-man question and subscribe and walk through one of the example of versus in press of elements like 531 middle aged this That Thirty Plus Two Ispat Total Sometime Year 2015 And Friends Let's Game Of Possibilities Subscribe Settlement And Subscribe Element Subscribe - 230 Subscribe 90 That Bigg Boss 5 - Fish Tank And In Case That Bigg Boss 5 - Fish Tank And In Case That Bigg Boss 5 - Fish Tank And In Case Effects Of The Shift Leather Gloves Element Subscribe Element Fuel What Will Be The Meaning 5314 Subscribe Now To Subscribe 1451 And To End Not Come To Know What To Subscribe And Subscribe To That Bigg Boss Share The Total Points 3132 - 560 And In Case E Rickshaw The Force - 560 And In Case E Rickshaw The Force - 560 And In Case E Rickshaw The Force Element What Prompted To This Code Total Weet Wealth That If * Possibilities After Generated 153 Vansh Ifir That If * Possibilities After Generated 153 Vansh Ifir That If * Possibilities After Generated 153 Vansh Ifir Dadar 16314 Difficult Minutes Element And Combative Decade Ke Is Hai Aisi Mother Who Is Specifically Elements To Take Over 20 Countries Of Five Elements Are Something Like This 314 To And Total Time Ago 0 That All Should Nine Updates Chance Warden Here Tree Free and chicken previous to effect service three elements in what is the meaning of date of birth relative that is a specific less seven six subscribed element what should we do the meaning of date of birth 3141 total score of but that boat idea note judge witch Where To Go Without Them With Radio Producer With No In Next Month Element Similarly For No Problem Maximum Element Of The Best Option That Arab Girl Top Witch Will Cure All Possibilities We Don't Know The King Of The Left Element Will Give Maximum Difference And King Of The Title of Birth Maximum Difference Result of Which Will Destroy All Possibilities for Attempted to Different Tribes Statement of the Answer Given Some Are subscribe and subscribe the Channel Please subscribe My Meaning of Elements Subscribe to 200 Inverter Terms This is the Formula to Find the Solution List In Bathroom Viewer Cases Registered In The Only One Element India Are With Life And Left And Right Mode Turn On The Same Point What Ever Be Index Of These Elements And Difficult This Element 131 Maxims To Slot The Meaning Of Mission Given During More 2004 You Interested Only one limit Hindi is that Bigg Boss is coming back on this day of war Left that element is face brightness element is 102 elements in India How to write - 102 elements in India How to write - 102 elements in India How to write - fluid to acid and width elements select this element subscribe and subscribe the Channel Please subscribe and subscribe And subscribe The Amazing Is Clear Lemon Juice Zoom In This Experiment Is Under It's Not Aware Of Stop This Problem We Use To Make Competition For U A Hair Oil Calculator Length On The Number Of Toe Insert Devendra Arya Prosperous In Africa Sports Mode On The Satanic Verses Are Attributed To Him But Ones They Are Doing So Will Lead Role Play And Content - Doing So Will Lead Role Play And Content - Doing So Will Lead Role Play And Content - Subscribe To 22 Min Crafts For The Problem Lives In Writing This Method And How To That Is The First Parameter Sacrifice Left Us Index Of Current Are The Second Remedy Jara It Means Index Of The Current Increase 15014 Left One End - 1.1 200 Test Draw And Sum Different The Left One End - 1.1 200 Test Draw And Sum Different The Left One End - 1.1 200 Test Draw And Sum Different The Sum Of The Total Elements Later Into Consideration In The Current President - 1m Consideration In The Current President - 1m Consideration In The Current President - 1m My Voice Products GPRS Object Interview Starting and Memorization President Award Competition Office Prem States That When Report Corner's Tweet Talk About This My Life Is Equal To Right Down There Only One Element In Every Single Elements In Water Maximum 040 Pass And Width This Two Elements In The 11-Year And Width This Two Elements In The 11-Year And Width This Two Elements In The 11-Year Two Elements Are Right - Executive Two Elements Are Right - Executive Two Elements Are Right - Executive Volume Maximum Element 108 Pickup The Volume Maximum Solution Co Pickup The Maximum Element The Maximum Age Limit For Its Course All For Your Kind Of Drums Malik That And Let's Check Weather Bihar Computed The Current State In The Past And Not Being Rolled 40 - One And Inclusive Computers Simply 40 - One And Inclusive Computers Simply 40 - One And Inclusive Computers Simply Return The Volume And Ajay Bhai Slips Calculator Maximum Difference And Given By Not Maths If Possibilities Effigy Of Elements Of - Possibilities Effigy Of Elements Of - Possibilities Effigy Of Elements Of - Stones Value Of Development Index And Subscribe Maximum Volume Possible Element subscribe to the Page if you liked The Video then subscribe to the link for detail view Main Bor Phir Bhi Pickup Brightness Element Sum - Stones Brightness N Sum - Stones Brightness N to the Page if you liked The Video that Akshay What is the Time Complexity of this Approach Time Complexity of Mode of and Square that Bigg Boss Your Movie in Bottom Top-Down that Bigg Boss Your Movie in Bottom Top-Down that Bigg Boss Your Movie in Bottom Top-Down Fashion and Space Complexities Jagaan Mode of and Wealth that if you liked this Video And Under Solution ID Please Don't Forget To Like Share And Subscribe To My Channel Thanks For Watching And Proof Tune For More Updates On Ajay Ko
|
Stone Game VII
|
maximum-length-of-subarray-with-positive-product
|
Alice and Bob take turns playing a game, with **Alice starting first**.
There are `n` stones arranged in a row. On each player's turn, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score.
Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._
**Example 1:**
**Input:** stones = \[5,3,1,4,2\]
**Output:** 6
**Explanation:**
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = \[5,3,1,4\].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = \[3,1,4\].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = \[1,4\].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = \[4\].
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = \[\].
The score difference is 18 - 12 = 6.
**Example 2:**
**Input:** stones = \[7,90,5,1,100,10,10,2\]
**Output:** 122
**Constraints:**
* `n == stones.length`
* `2 <= n <= 1000`
* `1 <= stones[i] <= 1000`
|
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.
|
Array,Dynamic Programming,Greedy
|
Medium
| null |
236 |
Hey welcome back to another problem of lead code and today we're gonna solve a problem it's a common interview question and it's called lowest common ancestor of a binary tree so given a tree we need to just find not just an ancestor we need to find the lowest common ancestor okay so given a binary tree find the lowest common ancestor LCA of two given nodes in the tree according to the definition and all okay but that's in short it's like this so let's say if I give you two notes in this case let's say let's take this example P is fine and Cuba sport so in this case when you look at this tree you can tell that Phi is gonna be my lowest common ancestor that's the immediate node who's who is the parent of both these notes Phi and for example if I is here and for is here let's take another example of six and four so if I take six the parent is fine fair for here and the parent is two and that's not the parent of six so this is not my lowest common ancestor I go up level up so this is my car ancestor so six ancestor is five fours ancestor is also fine so in so that's the immediate ancestor so if you're here interested in not the ancestor we are interested in getting the lowest common ancestor that is the parent of the ancestor of both the descendants okay so you're gonna solve this problem using recursion and yeah so let's all wait so I'm gonna because I'm gonna solve this using recursion let's create a helper function so okay so because this is we're gonna solve this problem using recursion we need to make sure what are our base case going to be so our my base case is finding P and Q okay finding this P p-value and Q value if I don't find this p-value and Q value if I don't find this p-value and Q value if I don't find this value I keep going down my recursive call is gonna be like called again and again I again and I reach a point when there will be no notes to process if there are no notes to process I just return none that is gonna be my one base case okay so now think about another case what if I find the value P and Q what is that a traverse I go down these nodes these sub trees so I call a recursive call which calls this sub tree a recursive calls which calls this sub tree and I call these recursive calls and when you were solving the problem of these recursive call like in this case think about this as one tree don't think about this whole tree you just think about that call what's that call function it is doing what node what state it is in and when I'm here I'm only focused on this note what happens on this lovely left subtree and when I'm here on this subtree I'm only focusing on single note so sing to think about like this in a tree when you're solving is incursion think about what single node is going to do so this is one case when I don't have the my note is pointing to something none that means it's not actually a note then I just return the other case is that what if that note I'm in has the value of P or Q then I should suppose to return back and return it back right return that note so think about like this recursion is like go down call keep calling the recursion function calls and then reach a base case in this case it's going to be known as naught and then return back from okay so there's another base case that we need to solve here is what is a single node if it contains this value P or Q I just return that is the know what I'm interested in okay so if this is the node which I am interested in if it has a it is the P it has the value P or it has the value of Q I just returned that node now what if that node is not the note I'm looking for then I need to search that is I need to go down call another recursion call go to my left subtree and go to my right subtree so and then think when I go there think about it as what that subtree is gonna do it's gonna do the same thing what every node every subtree is gonna do okay so when I go to when I look at this whole tree this is my one big whole tree when I go to the left subtree I just focus on this left subtree what am I going to do in this left subtree when I go here focus on what I'm gonna do on this right subtree okay so I need to go now I need to go to the left subtree and get the results okay now I need to recursively go to the right sub-tree now I went to the left right sub-tree now I went to the left right sub-tree now I went to the left sub-tree I go to the right sub-tree and sub-tree I go to the right sub-tree and sub-tree I go to the right sub-tree and then return when I hit these values so these are gonna be my two cases either I don't find the value I'm gonna return none or I find the value the P or Q I returned that note so that's gonna happen so when if what if I go to the left sub-tree and I don't find the value left sub-tree and I don't find the value left sub-tree and I don't find the value P or Q I don't find it so then I don't care about it that's not the note I want then I just return my right subtree then just return me the right subtree now if I do the same thing for my if my rights of phase line the last subtree okay cool so go to the left subtree if it's none that means I did not find the P or Q then I'm not interested in that's subject I just return my right subtree okay now at some point my left subtree I am my right subtree is going to have both of them are gonna have an unknown value either it's gonna have P I'm not really interested in what it has either it has P or Q but it's not none it is not none so if it's not none that no sub has that is the node where descendants the left subtree and the right subtree has the descendants of P and Q so that should be supposed to be the least common ancestor the immediate ancestor so that is I just need to hear I just need to be done you know let's run this code I am cool so it worked and let's submit this problem cool it worked so this problem is very interesting because it's been asked in a lot of interview questions and I hope I and the time complexity okay so the time complexity here is Big O of n because you're walking and traversing through all the nodes and the space complexity is the recursion call that call stack that you're calling recursively calling each and every node so it's Big O of N and the time complexity is big often because you're going and walking to each and every now yeah so this how you solve the problem and I hope it helps and you enjoy it like and subscribe thanks for watching
|
Lowest Common Ancestor of a Binary Tree
|
lowest-common-ancestor-of-a-binary-tree
|
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
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 = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**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 tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,1190,1354,1780,1790,1816,2217
|
1,732 |
Hello hello welcome to my YouTube channel thank you will be doing problem pandey high school person again zinc whole life problem statement k 1000 likes subscribe and third tips subscribe with obscure length is net this is 2.5 violet anil 2012 net this is 2.5 violet anil 2012 net this is 2.5 violet anil 2012 point question exam hai the whole existence two Improve when he was born in butter will run chilli a 505 ki handi you yourself was girl house of this time sleep ideal in this problem institute specific evening available for android system that every person words fiction your specific company vihar to find fiction of the Elements Which Indicators I Am So I Only 10 - Pipeline Was A0 But Ministers Only 10 - Pipeline Was A0 But Ministers Only 10 - Pipeline Was A0 But Ministers Inducted In The Chief Justice Of India Friends Pacific K 400 And Video Please Subscribe And Subscribe The Near Time Khurram That Person Very Nice Baby YouTube Channel Subscribe Just Copy And Elements Like and Subscribe Here This Interviewer 6 And Definition Of Singh Bibi For Settlement With CEO Steve After Ministerial Graduated With Your Deposits Of Sorrow And Start Fix Sampariksha Means Previous Voters Who At This Point Has Been Appointed Chief Commissioner Of Everything Is That Show The Freedom Party's Delhi Waveriders improved the traffic jam due to acid burning etc. The young man who wanted to have stomach at the time of 220 Vansh A Man Kyo Zero Cut Su year old got serious injuries Class Gya I Mines and Water BCD A K In These are selected taking a position to reposition puja whatsapp subscribe aside this - - - - - your white cigarette this lineage challenged in midnight this is according to 10 problem expression tracking monster for snoopy images1 and this will be that these two quality Testing elements of game of management and mind busy setting volume someone is pure silk spoke to vinod on a phone but all like this a ki centric kismat chat ashok meet eating and arduino others g point job for like loot baje do ki i - one Plus ki i - one Plus ki i - one Plus That Lipstick All 80 Prayers Suit Key Of It - One And Is Vansh Currently So Ifin [ - One And Is Vansh Currently So Ifin [ - One And Is Vansh Currently So Ifin More - 5th More - 5th More - 5th 108 Intex Phone Chief 115 Right - Size 108 Intex Phone Chief 115 Right - Size 108 Intex Phone Chief 115 Right - Size Images Added This - 5th Limited To 80 Movies Only i20 202 i - Vansh Plus. gif I - Vanshika to 202 i - Vansh Plus. gif I - Vanshika to 202 i - Vansh Plus. gif I - Vanshika to us semolina white - 52 - One will give me this us semolina white - 52 - One will give me this us semolina white - 52 - One will give me this element one that and believe in the taste two minus one request me this element ya now sleep good night the mind is without fear - Ko mind is without fear - Ko mind is without fear - Ko Lakshmi Writer 420 - Science Pairing and Lakshmi Writer 420 - Science Pairing and Lakshmi Writer 420 - Science Pairing and early morning - 4a early morning - 4a early morning - 4a and strong statement will be that modern statement dubai army treatment festival so thing minus one is 225 river bank in two years - handed over getting is bank in two years - handed over getting is bank in two years - handed over getting is lineage sir hans civil hospital one is the answer script luti asmat luti ware Is Not Poking I Don't Mobile Size Breast Cancer School Part World Record Android Apps Scars 2036 Treatment Hair And Commitment Key I2 Or Should I Say And Zero 123 This Vivo To So Will Get Another One From Lucknow - 6 And Will Just Chill All This And Lucknow - 6 And Will Just Chill All This And Lucknow - 6 And Will Just Chill All This And Will Find Out In Maths Element Jai Hind Ishare Notice Maximum Why 31.11 Jai Hind Ishare Notice Maximum Why 31.11 Jai Hind Ishare Notice Maximum Why 31.11 Loot Ism Egg Subscribe And Elements Of Obscuritism In This Element Calculate Traffic Jam And Wali And Healthy 9 Tags Page 10 Of 154 Calculating Definition Superintendent Of Police Are You From Descendent Notification Per Points Network And Exit Traffic and Listen Shareholder Meeting Match Challenge Anil Evening E Myself With Which Were Caught in a Recent Report According to Cutting Chapter Reduce Mode Presenting Perfect Practice Questions Means Only Cigarette Submit Singh and Gas Loot Under Time His Life But In Lutyens 98100 for liking solution is special giver started in this fight Shastri Choudhary result cut fish cutting service quality
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
207 |
hello and welcome to another self study session today we're going to be looking at leeco number 207 course schedule so there are a total of num courses that need to be taken and it's labeled from zero to num courses minus one and so we're given an array of prerequisites where prerequisites of i is equal to the pair of a b and that indicates that we must take course b first if we want to take course a so for example the pair 0 1 indicates that to take course 0 we first have to take course 1. so our task is to return true if we can finish all courses otherwise we need to return false so how do we solve this problem well the lead code description there in the related topic section sort of gives us an idea of what we need to use to go about handling this sort of problem but what if we weren't given this list of related topics what do we do then well my approach is always to draw it out and so let's say we were given the data set with these particular pairs we can then derive the following graph and graph table and so we have here we have zero to one we see we have an edge zero to two and there's one to two and if we put this in a table we have all the courses here in the first column the second column the dependencies are the prerequisites and so zero has two prerequisites one course one and course two course one just has one prerequisite and course two has none it's empty so we know that because there are no edges leaving course two drawing this out alone can tell us how we can go about solving this problem so if we look at this graph table here graph map and we start with course zero and then we look at its dependencies we have one and two and so let's start with the first dependency if we go over to that course and then look at its dependency we have course two so then we now look at course two now course two has no dependencies so therefore of course we can complete course 2 and so that is going to return true and that true value is also going to be returned true for course 1 because it's just 2 right and then of course 1 returns true so this is true and since we've already solved for course two that's also true and all courses return true so therefore our result is also going to be true but what about for a different type of graph let's say we have just these two courses course zero and course one looking at course zero we look at its dependency it's only one so then we go over to course one looks look at its dependency but oh we're back to course zero we've already visited course zero and so we notice here a you know a cycle and so since this is just gonna go on and on then we will obviously return false but when we solve for this one what does that sound like that sounds a lot like dfs or depth per search and that's one of the ways we're gonna um use to solve this problem so what we're basically looking for with this particular problem is a cycle or no cycle and formally it's just known as a directed cyclic graph and that is just a directed graph with no directed cycles and that is it consists of vertices and edges so the vertices are you know these circles here and edges the lines or the arrows also called arcs with each edge directed from one vertex to the other such that the following those directions will never form a closed loop so this first graph here is a dag and the second graph here is not adapt because it has a closed loop and so more formally what we're going to use is a topological sort and that's just graph traversal in which every node v is visited only after all its dependencies are visited so a topological ordering is possible if and only if the graph has no directed cycles which we just discussed and so we're gonna solve this using two approaches dfs and kahn's algorithm so we kind of already um showed how the dfs algorithm would work earlier and that is the more natural way of solving this once you draw out the graph table it becomes pretty clear how to solve this and these steps that we take resembles strongly dfs approach so let's look at it and so we pretty much know what dfs is i'm not going to go through that but um let's go through the steps again so basically we want to build a table with each vertex the course and the respective prerequisite courses the dependencies and so for every course that's going to be like a loop and for each of its dependencies and another loop we recursively boil down to the end of the dependencies which will be our base case and the base case is any course that has no dependency right here and so we return true for such a base case if all courses can return true the result is true otherwise it means we have encountered a loop we keep track of loops by storing what we have already visited so here we're at in the code and i am going to show you three different methods this is the first way of solving it and we're going to clean up this code i'm going to show you how to clean up this code so here we have our method our two parameters we essentially don't need this line because the constraints in lead code mentions it's going to have at least one course the array of prerequisites but you know it's there um this is the object for the graph and here we're going to create our graph table and if it's empty if it's undefined for the particular post course because we have here with the prerequisite and our once we have completed that prerequisite then we can complete the um other course so it's a b and here we have the graph if it's undefined we set it to new an empty array and we do this for the pre as well because we can have disconnected graphs so we need to make sure we check for every vertex in the array or data set and we push our prerequisite to the array so that's a pretty obvious or result a variable or visited map or object or visited object or memo so we're going to be using recursion to solve this and typically with recursion if you've ever done any sort of recursive um method or studied any form of recursion you would have come across um using memoization or some sort of optimization technique and so that's what this is for and so here we have our recursive method and we know usually in recursion we return what we've stored in memo this is our base case so if it's empty we you know we return true and here we have if we've seen the path already we've already walked that path then we are in a loop and so otherwise we've not visited that path we now set it as true and here we go through every course and look at each of its dependencies and here we make our recursive call and once these recursive calls are returned we store something in memo and here is our initial our first recursive call so that's for every vertex and we need to loop for every vertex once again because we could have disconnected graphs and we simply return our result so if ever we have seen it we set our result to false and we return now this works just fine and we can just run okay so we've run this and we can see that for this particular data set which is an obvious cycle we expect false and we actually got a false um value so these are just the exact the string what we the data set what we expect and the actual return of the calling b method so this works just fine and actually when i submitted it to lead code we you know it got like uh seems to have it seems to fluctuate so got a memory usage of 54 and so i guess it doesn't really matter that much because it's the same code here it's like 266. i guess it depends on the test cases the code is using but anyhow i'm going to show you how to make this slightly better in this other approach let's set that and let's use this approach now and here we've done the same thing is the same thing we're building our graph however the difference this time is that whenever we set a visit we then delete it because when we're done checking it and once we have actually um completed that we just set it as empty because we know that this empty value is our base case for true and so the reason we do this we can optimize in this way rather than having this memo because we're not actually doing anything with these memo values it's just like a flag and so we can use this as our flag just set it to empty and therefore that eliminates our need for using an additional memo object and we are deleting the we're deleting that here as well so it's just slightly optimized it's the same approach and if we run it we're gonna get the same results but from lead code here we can see it uses less memory and on average it's less than 200 milliseconds so that's just a slightly optimized approach and we have another method so i'm not gonna run that we have another method and this is a lot more optimized the difference with this as you can see this is a lot shorter building our graph is a lot shorter we have used an array instead of an object for the graph and the reason for that is because our courses are numbers so an array in this case for this particular problem would give us better efficiency and so it's exactly the same except that we are using an array and we can run this it's do the same results so it's not gonna look like you know a difference but in late code we have 56 so it's much faster than what we had before as you can see a lot use a lot less memory as well so if that is important to you yeah you might want to consider these strategies based on the data set and so on use the appropriate um you know data structure so yeah and one thing i want to note about this first approach is this is the natural way of doing things i mean as we know for recursion we usually have some sort of memo and we tend to return what we have in memo and so doing this on a you know tight budget of time you know we follow the pattern that we already know and i'm just mentioning these this all to say that when we're pinned for time we do what we know and then we can optimize and so we are already used to this approach with recursion and then calling our function you know calling our recursive function and then setting that value and so on and so this has been i guess the quote unquote probably most naive way to solve this using dfs and then we can later optimize our solution so that's it for um the dfs approach and we're going to talk about the cans algorithm coming up next yep and yes so khan's algorithm works by choosing vertices in the same order as the eventual topological sort and so first we find a list of start nodes which have no incoming edges and insert them into a set s or a queue and at least one such node must exist in a non-empty non-empty non-empty acyclic graph and so if we're looking at this graph right here which i've changed the nodes node values to letters for so that we're not confused by the in-degree confused by the in-degree confused by the in-degree numbers yes if we're looking at this particular graph we'll see that there are no incoming edges to node a for b course b there's one incoming edge from a and core c there is there are two incoming edges from a and from b and so we need to find a list of start nodes and so initially we're gonna have a in the queue as a start node and so now we're looking at a so we're gonna pop a from the queue and put it in our result set oops see if we can write that a and now we're looking at the dependencies for a so we're looking at b and the in-degree value for b and the in-degree value for b and the in-degree value for b we're gonna reduce that it's gonna be zero and so since it's zero b is going to place on to the q we're gonna look at the in-degree value we're gonna look at the in-degree value we're gonna look at the in-degree value for c and it's going to be reduced to 1. and so since b is now in the queue we're going to pop it from the queue place it in our result and from b we have c right and when we look at c it has a value of one now it's going to be zero we want to put it in the queue and we're gonna pop c from the queue place it in the result and actually we're actually done so we can see that we've returned the all the courses so in the end the way to determine if this is good or not is to just compare the num courses length or value with this result length or um total all right how about now for a non or graph that has a loop or non dag graph okay so we start like usual with the start node would be a again in this case let's use a different color a and then we're gonna pop a from the cube add it to our result and we're gonna look at the dependencies for a which is c and we're gonna reduce that to one but then c it never turns to a zero and so our q is going to be empty and therefore we're gonna return this as a result and our result is not equal to our num course's length or total and so therefore the graph contains a loop and therefore we return false so that is how that works and we're going to look at the code for khan's algorithm so here we're at in the code for khan's algorithm we have our graph object or in degrees array of length of normal courses all pre-filled with zero values all pre-filled with zero values all pre-filled with zero values and that's because we're going to later calculate the in degrees for each vertex and remember the in degrees are the number of edges coming into a particular vertex or node and so this loop here just builds a wrap as we've done previously with the dfs version and after that we have a queue here this loop now that looks for the starter node so any course with an in-degree value of zero with an in-degree value of zero with an in-degree value of zero is then pushed onto the queue we have a order array or result set now while the queue has a length we want to dequeue the first item so we take the first item of out of the queue we push it on to our order or our result set then now we want to look at the course we want to look at the prerequisites for a particular course right here so we get the prerequisites then we decrement the in-degree value that is for each in-degree value that is for each in-degree value that is for each prerequisite of a particular course and now if the interview value ever becomes zero then we want to push that prerequisite to or push that course to the queue now this continues while the loop has a length once the loop is empty the queue is empty then we return we check the length of the order array against the number of courses and if they're equal it means that we can complete all courses and therefore our graph or is directed a cyclic rock right a dag and so if we run this let's try to run this and see to plug in and the same as what we calculated previously with the dfs approach and yes so we can see that this solution is a lot more optimized than a previous dfs solutions and so we've discussed two ways in which we can solve this particular course schedule problem and we've shown the evolution of the naive approach or slightly naive bfs approach with the memo object and we have shown how to clean that code up to optimize for based on you know the problem statement the input values we've used arrays for our dfs approach and we've seen improvement in the memory usage and also the speed or the efficiency and now we've just discussed khan's algorithm um it actually is the faster way of getting things done and i hope this self study session was helpful to you it certainly was helpful to me because i do like to dig into things and figure out how one would have come about a particular problem rather than just getting the algorithm in my face or getting the answer in my face i do prefer to know what is the natural way of solving it and how can i improve from my natural approach the natural human way of solving it and then from there we improve and that's what it's really about right i'm writing efficient code and code that scales for large or larger inputs um yeah and so anyhow thank you again for joining me and i'll see you next time take care
|
Course Schedule
|
course-schedule
|
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 `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists 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
|
210,261,310,630
|
84 |
Sir, in today's video, there is a very important question about finding the maximum area in histogram. I have given you a basic histogram and some graphs of this type and to tell you how to make this graph, who is the designer of maximum area, ticket is enough. The famous interviewer has increased a lot and the taste is welcome to all of them. Okay, so this question is so in which way, here you will keep one hour of this smartphone, so from here, 12th or height, this lens is okay from here to here, so that's why here. 12:00 Also and multiple dating 12:00 Also and multiple dating 12:00 Also and multiple dating assistant were becoming that look at them now okay inside the triangle on this 512 but favorite that your comes extend here sa aquarius horoscope 2014 f4 contra look inside this extra allotment of 333 but seema trisha It will not come out because of the shape being formed on the Samadhi, inside it you can also see that a table spoon of butter has been placed while grinding but you do not know that the rectangle which has the highest area is just this one, my tablet, this one is fine. Whose height is, whose link is as far as and its area is 12:00, hence quantitative, so its area is 12:00, hence quantitative, so its area is 12:00, hence quantitative, so you have to print equal and add a little weight, think how will you do it, okay, very good logic, it is going to sound like, we will use straight, I did it Mukesh so that we are doing it And you will see how there is a pattern in multiple questions on travel, that pattern is beneficial for you and text questions in today's video, Sonu, that too, by doing it slowly in front of you will start earning income, so this one. Viewing the height in the portion center is basically how far we can go for this particular height. Left or right side like here we show for height we can come till here, we can stay here, but right now you This is a smaller limit than and you can come here so * from the items that we can try this distance, so * from the items that we can try this distance, so * from the items that we can try this distance, okay 6 length we can try distance so 6 212 goes to single layer teen element area proof so this If we stay ahead of the method, then how much left to right side can we go, where this 3D is for free, we have not come a week ahead, there is a small limit of vegetables in the left side, from here to here, from here to this, here Okay here, so for three, we just add this distance from 3539, so in this way, you can sleep that each element will go to the fort and I will enjoy this element that if there is a height, then how many units will I discuss distance from it by submitting. I will give it to the side and that is my area coming out of this height, then by doing this I will tell all the people coming out of my hands about this and my purpose will come, then the shroud will be buried here, but how can we vote for whom, then the fund is very It is simple to code it, so every method is there, it is the root of our brain's loss, we complain that any element has been caught with full support to recall, I have to reverse the filter element within 10 days, the platform for the life of the star, so So we have created and this one and Rudra's will hold any element ego if we and for that I will create the left, for how long can we go left and for that increase the light that it ends in the right and left and right click. Let's consume Bloody Mary, we will run a loop, here I am job, I am getting a bigger element inside the left, a bigger limit than the current element, keep getting left, till then we are on the left - but let's getting left, till then we are on the left - but let's getting left, till then we are on the left - but let's listen, we will link to the sites with light, we will get it here. But we will go to the left and right intent, after that then we do not have to do anything. The area which is ours or right-left area which is ours or right-left area which is ours or right-left multiple is VIP and here you will - will make a small weight, and here you will - will make a small weight, and here you will - will make a small weight, I must have heard here, so in this way you people Maximum alien can come out and if we talk about its time collection, then you see for each one we have one more people inside which I am leaving on both sides from your left, okay so these above are two different ₹ 10, okay so these above are two different ₹ 10, okay so these above are two different ₹ 10, this is Rs. There are two stops inside it, basically one benefit, one message, all these are the read of the answer, so this is its time for Lakshmi Haar, but this can be done from now on in better complexity, okay, we can also do it in Bigg Boss Hai from Gopeshwar using stack animals. Before the video camera on question was solved, you will remember the belief that the previous vanguard element is coming and the previous is present and in the next9 element from, then inside that, the same type of something is going to show you that for each album, it is smaller than this. Which element is here, then this small limit has to be found out. is here, then this small element is here, then this small limit has to be found out. Single for each empty stomach, where is this small element here, then this is here, then the question is, when I go to all these above and take out the previous material. For this one hey, here I put a previous molar and here I am Alex Small World A Plus Model Next morning for the animals coming so first you were that person element is okay instead of element we will put the index okay So animals na I will take the index so there is no infection before this minus one there is no one smaller than this - no infection before this minus one there is no one smaller than this - no infection before this minus one there is no one smaller than this - become smaller than this minus one this is smaller one but and I will not write one can experiment in next to give you here two similarly this is smaller That is, its Dashrath is Meena, it is smaller than this, its inductor to is also smaller than this, its intact is that smaller than this is its Small next where do you get my skin actor vansh it is small this ra its next ban that there is nowhere smaller than this so if you put its induction then small somewhere old on this I do a little bit that ca n't kill the notification that minus If it is okay to keep one element then you will find it in Chhota. If there is one then where is the deprived Chhota. I do n't know where 90% of the ninth element is n't know where 90% of the ninth element is n't know where 90% of the ninth element is but here we have prepared because it is in front of us in doing our calculations - pray to him. There may be in front of us in doing our calculations - pray to him. There may be in front of us in doing our calculations - pray to him. There may be some problem in our section, so I want that our traction was there without license condition, if it happens then it will take time to get it done later, after that if the elements move then it will have a small limit. The index of A is not sitting here and it is A little element, this Android white, it's small elements in tears, there's no small element on it, so no space left, the element is on eight and it's not even small, so no, so I put it here in previous12next, hey, for black pepper, we know. It is easy for us to find out how far I am going for any element and after that, it is easy for us to find it. How can you calculate it for some minutes, you will find the next9 of the same next - the previous one of that India next9 of the same next - the previous one of that India next9 of the same next - the previous one of that India is but This is taken out, after that you will multiply it by 1-9. There after that you will multiply it by 1-9. There after that you will multiply it by 1-9. There is an exam on that index for the next generation, so you can take it out in this way. Keep watching, take out the answer and the place from where the trader reached the maximum will be your answer. So, if you have taken the previous calculation and Next9 is taken out, so for this I show you the audio record, friend, this is your work idiot, the time will work for the 15th time inside it, so you have taken out Bigg Boss and here in the space, if you are chatting, it will be expressed and after that you will run the quote. If you do another Farooq Jitendra Tiwari Krishna, then he is going to be on Bigg Boss, then it was 1007, which will do your overall growth and time for technical, then you will be fooled by this relationship, then show you how much it is like this, you did not follow these two. One coaxed and one question we had asked earlier about cap and muffler and Max Muller told that you have a very important question, that is the question coming ahead of you, if it would have been used, then here I am a part, now and we will see its use in tension. And okay, this area one, we came out here like 11 apva to next molar mess sinus but - mez to one next molar mess sinus but - mez to one next molar mess sinus but - mez to one minus miss two minus one which one will tire off and wishes for this let's do it so one - - 06 2012 Jeev one - - 06 2012 Jeev one - - 06 2012 Jeev Velvet To which S2 Disagreement expressed friend that for the next month wise element on this element its laxative this or wallet or come first then I spooned here now you can write this - - now you can write this - - now you can write this - - remind me to women vastu tips for so for this Your idea for this keeps on bringing on its people 9 - - - 200 on its people 9 - - - 200 on its people 9 - - - 200 youth special 921 warning signals against violence in addition to this Fab - Toe Witch 3 - 1255 richest Fab - Toe Witch 3 - 1255 richest Fab - Toe Witch 3 - 1255 richest 100 school association 26 to minus one day workshop and six to this relationship this Text message to 4 - Vansh bhi lilavati hoga aapka no - Vansh bhi lilavati hoga aapka no - Vansh bhi lilavati hoga aapka no so oily 271 witch s60 to which is wealth whether it will be successful - Special to take medicine witch be successful - Special to take medicine witch be successful - Special to take medicine witch one male voices for above from here 192 67 - One witch smashed his - One witch smashed his - One witch smashed his twelfth's look everywhere Your answer for this is that if that index of yours for green chillies was light then how long the rectangle could have gone for it, then that is what I have to see first and last time. For the face, I am getting tan here, if only theirs. The training is at Simaria Ghat, the whole family along with the bike is at two places that here these two are the acid attack on 12222, this is what we have done, we can shrink it very easily, we are ginger and tell us what is going to happen, okay, so here I have Increase the volume by doing one chord also. Figure time, we have the next Maurya and Lebanon option. Okay, so I have made the previous Marwar option here. The function of next9 can be increased. Yes, by doing this, how else to make this one, we have seen the logic like that. Had taken from this, we must have seen this Rajouri on the last wali media. Same question, what is peer wala and whatever job was inside it, we will do the job, today we are returning the file, whoever loves first, hey, that was the value of your actual index, it is fine. The maintenance that he has to do here inside the network or business is what we are doing in the tax return, that's the whole thing, okay, rest of the whole thing, how will you do the work, then prevention of I made a career out of an intense yorkers back. After listening to this, it will be formed, after that, we will run a follow, now from zero to the end, we will check the complete and hybrid elementary whether you are exempted from this relationship, if Amavasya will take out the antibodies from the companies and at that time the elements will enter into the circle. For ax The chart of elements is big, okay, take out this element and like if you increase the top limit, then small Adams cannot talk, August is an exception, so I have put advice in it, so this is the element that we are putting here, we are asking about this, we are indexing. You are not enrolling, so here we will get into the index by doing such topics, there we will get connected with others and within this, we are returning the price index. If that person has a better understanding then I would request you to definitely do it instead of Next Life. We will see, okay, there you will be charged yogic, after that you are in the same manner, from the next 9 news rooms, it will be same for the network, here instead of great money, garlic will come and from behind, you people are walking with urn, so it is yogic. After that, you should write this here in the blogadda awards for friend's NSI - 5 - One must provide for every nook, - 5 - One must provide for every nook, - 5 - One must provide for every nook, we take out Karan and one, we have made coffee, maximum only macromax of this, so here I am from one of the accidents. It will be big and he will go on a fast. Okay, so if you give another example, here we have an example to submit. For this, first of all, if you take out the revolver, then TVS motor's previous mode will come out, it will be for free - it will be for 151 - For 142 - it will be for 151 - For 142 - it will be for 151 - For 142 this 0123 iron of their youth this position 120 element etc induction stove and for this will be to that T-20 match friend two induced by chance that T-20 match friend two induced by chance that T-20 match friend two induced by chance bike accident happened but element here fear this credit we signal which next that what will happen then Okay, I will take one, okay, this lineage is its lineage, if we do not have any small limit, then we will put it here and okay again installed here similarly, if there is any small limit for it, then we will put it. If there is any special judgment for this, then next month. Will put for a little, when it is small, no one came to the side like this, after that, let's go to here, first let's go to the next, then first for the index, we would discuss with zero that what is it friend, then the current extracting juice is our one - - - 2 - Mrs. extracting juice is our one - - - 2 - Mrs. extracting juice is our one - - - 2 - Mrs. Bramble is her husband, here is the time of Navratri people, Muslim sir or the current, which is bigger, the maximum was 900, the current was our dear, he encouraged us a lot, the ceremony for three was of red, now we go, so what is the matter as many This Kapoor - - - - - so what is the matter as many This Kapoor - - - - - so what is the matter as many This Kapoor - - - - - - If the shift in this four-storey building is fine, it has been - If the shift in this four-storey building is fine, it has been - If the shift in this four-storey building is fine, it has been complete and what is the maximum, the current is our three and our society has our full support, phone number four, then look at its here, come here for Here is the wave for - 153 Malik - I have a Here is the wave for - 153 Malik - I have a Here is the wave for - 153 Malik - I have a Twenty-20 cricket tournament in my to-do Twenty-20 cricket tournament in my to-do Twenty-20 cricket tournament in my to-do and I will not update it already, it is ready by adding it, so then I took two visits to minus one month for which is this one? So from here I add bread crumbs to the off course, hit four and one, because the form is coming here, it is very simple, here you have taken the next mode, then the next mode, you can fold yours in the same way and whatever is your height. If you do not get the crown then remember at that time that the index which is the length of the juice add plus the one which is inactive which you have put here is fine - put it in otherwise then you will have to do some Saif is fine - put it in otherwise then you will have to do some Saif is fine - put it in otherwise then you will have to do some Saif Ali Khan Sanjay. If there is a rifle - Ali Khan Sanjay. If there is a rifle - Ali Khan Sanjay. If there is a rifle - then which one If you want to handle it properly, then to avoid that NDA, I have put N inactive at the end here. Okay, and I have included your post injection, which is a question, and after that we will discuss in the upcoming videos. If you like this video then please like it. I will meet you four days a week. Sitam by O
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
931 |
hello viewers welcome back to my channel hope you are enjoying all the videos that I'm uploading if you haven't subscribed yet please subscribe to my channel and share among your friends so today's problem is minimum failing path some given a square array of integers a we want the minimum sum of the following path through a falling path starts at any element in the first row and chooses one element from each o the next rows choice must be in the column that is different from the previous rows column by at most one right so basically if we are given with a square array that is n by n array so basically the number of rows and number of columns are same right so in that kind of array we want to find out the minimum falling some basically the path starts from the first row it could start from any element in the first row but it has to go through the first element first row till the last row so the path should have first row through the last row so that means n elements in the paths assuming that n by n matrix rates or in that there should be n elements so each element belongs to one row right but the way that you are going to choose the elements in that row is so if you start at first row at an element the next row choice must be in a column that is different from the previous rows column by at most one so it could be in the same column or it could be a column next to it or pria previous to it that's it so you have three choices that means right so the question description says next rows choice must be in a column that is different from previous rows column by at most one so you can choose the same column or the next column or the previous column so you have three choices right so that is what a little bit confusing here the next row choice must be in a column that is different from the previous rows column by at most one right so it says it should be different from and it says by at most one right so that means so if you combine the at most one and different from these are like quite opposite to each other right so it should be different or it can be same column also that's a question anybody would have but the way that we have to understand that is it could be same row oh sorry same column or a column plus one or a column minus one so do you have three choices like that's what we do we need to understand so if you look at the example one right here 1 2 3 4 5 6 7 8 9 so this is a 3 by 3 square matrix so the first elements that is the first column is 1 4 7 so that is also one of the possible falling paths that's what it said in the explanation right so with that what we can understand is from this description it is confusing right so with this explanation what you can understand is it can be in the same column and it can be in the column plus one our column minus 1 right so there are three choices that we need to look at right so let's go ahead and try to understand algorithm so we are going to solve this problem with dynamic programming methodology right so what we are going to do is we will be declaring it some 2d array two dimensional array with same number of rows and columns of a right so whatever the columns and rows that are given in the matrix a right so we are going to create a similar array to Riario and initialize all the elements in the created 2d array to the into max value basically so the those are the maximum into possible value right and then fill the first row with this first row in the array with the first row of the a right so since there is no change to the first row so 1 2 3 will be 1 2 3 that's it because that is the that is where we are going to start looking at the falling Sam right so first row will be same right and next that's where the DP technique starts so from the second row onwards we will have to go through the full row and try to identify which part is having the less sum because that is what our final goal minimum falling path rate minimum following paths am so we you have to look for minimum sum right so in the array that we created the some array right in that we are going to collect the sum and put the minimum as we know there are three choices that we can look right so if you are starting from element IJ right at the current element IJ with the sum obtained at I minus 1 J minus 1 I minus 1 J plus 1 right so that means so you are at I throw Jeth column I throw jet column that is a cell right so initially IJ will be to start with it will be 0 right so now for 0 what you are going to look is three choices we said right the next row is I plus 1 J right i plus 1 is the next row and J right and I plus 1 J plus 1 so that is 1 and I plus 1 J minus 1 so those are the three things right so here what we are assuming here is it is we are going to have three things right so we are adding I plus 1 and I minus 1 G right that is a addition and I plus IJ plus I minus 1 J minus 1 that is another sum right and I J I minus 1 and J plus 1 so these are the three things that we are going to add and put the minimum sum in sum of I J right so there are three possible ways so you are at IJ right and what you're going to do is the pre so here when we refer to I minus 1 right so that is a previous row right from the second row when we are starting to process right we are going to look what we are going to add for right so from the second row onwards that means we have to look a row which is prior to the current row since we are processing the second row we will look in the first row obviously so IJ I will be since the arrays are zero based index I will be 1 right so I minus 1 will be obviously 0 right so if you are looking for 1 0 let's say right so there will be only 2 options so far because first column you have only two options right so there is no like minus 1 column right that's right so but if you are calculating for 5 let's say right so then you have this column and this column two columns are available right so not all the numbers will have these three choices exercised right so some columns you only have two choices right some columns we have all three choices especially the first and last columns won't have three choices but all the in-between columns will have all the in-between columns will have all the in-between columns will have all the three choices so that is what we need to remember so what we are essentially saying is sum of IJ will be the minimum of IJ plus I minus 1 J so we are saying even though I'm saying IJ I minus 1 J right so you need to think like the contents at that particular location ok so keep in mind we are only using the indices here just to understand what we are not exactly adding the indices here but the content the contents of those indices are those cells right so once you have the sum right you will be able to generate the minimum thing right so at the last row right at the last row you will have all the sums calculated so now what we go what we need to do is you need to find the minimum of the last row right so that is the final step finally we go through the last row of the some 2d array and find the minimum from it right so we will be going to go and look at the code for this right so it's the same approach that we talked right so minimum falling fat sum so let's get the M and M so although the m and n are same here I purposefully got it differently right even though it is given as a square I probably got it as different you can just use a single variable there is no harm in it right and once you declare this what we said is initialize the some array element to into max value that is what is being done here and the next thing is fill the first row with the first row in the input right so that is what we are doing in this for loop right and the next thing is so this is where the actual logic so the three condition right so the three conditions will start right here so for since we already filled the first row we can start from the second row that is what we are doing here so we are starting from the second row so if J minus 1 is greater than 0 and J plus 1 is less than n that means this is a middle column right this is a middle column anywhere in the middle column so in that case you have three choices as it right so you have three choices aj+ sum right so you have three choices aj+ sum right so you have three choices aj+ sum of I minus one J a IJ and sum of I minus 1 J minus 1 AI J sum of I minus 1 J plus 1 right for the all middle column so this for this if is it checks whether it is a middle column or not right and this one so this one it checks ji J minus 1 is less than 0 and J plus 1 is less than M so this checks were first call so for the first column you have only two choices right so these two choices that's it and this is the last column so J minus 1 is greater than 0 but J plus 1 is greater than or equal to M in that case this is the last car so you have three scenarios this is the middle column this is the first column and this is the last column that's it so we covered all the columns right so finally we get the minimum sum in each row but what we are interested is minimum falling sum across the board so that will be at the last row so what we are going to do is going through the last row and finding the minimum in the last row so finally we are going to return that minimum right so whatever we the sum that we have obtained in the last row you have to choose the minimum of the sum that will be the answer for our question so let's go ahead and look at the time and space complexity for this algorithm so let's look at the time complexity first okay so time complexity will be for this Pearl oh it will be order of this for loop it will be order of M and M into n this for loop order of n and for this order of M minus 1 into n so even though I'm I already said M and n are same I purposefully took em and us different but you don't need to worry about them so what we can say is the total complexity here will be order of M into n so if you add up everything will be order of M into n in other words you can just say order of n square as well right so in other words you can say order of n square L as well since the problem given is a square matrix anyway right so you can say order of n square that is also works so similarly if you look at the space complexity right so we are declaring a some array which is equal to order of M into n again so you can say it as order of n square right so the time complexity and space complexity both of them are order of n square for this particular algorithm so if you have any questions please post them in the comment section I will get back to you on this thank you for watching if you haven't subscribed to my channel yet please go ahead and subscribe and don't forget to click the bell icon you will get the notifications for all my future videos if you click the bell icon please share among your friends as well again thanks for watching I will be back with another video very soon till then bye
|
Minimum Falling Path Sum
|
maximum-frequency-stack
|
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`.
**Example 1:**
**Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\]
**Output:** 13
**Explanation:** There are two falling paths with a minimum sum as shown.
**Example 2:**
**Input:** matrix = \[\[-19,57\],\[-40,-5\]\]
**Output:** -59
**Explanation:** The falling path with a minimum sum is shown.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 100`
* `-100 <= matrix[i][j] <= 100`
| null |
Hash Table,Stack,Design,Ordered Set
|
Hard
| null |
1,288 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified when i post a new video so without any further ado let's get started so problem is remove covered intervals see very simple problem uh like usually when we get these type of problems now intervals involving intervals so we do the same kind of work so let's see what we will do so we'll be given a area of intervals right and where each interval of i means at each index we have an array which has two elements left and right like l i r a so this represents the interval remove all the intervals that are covered by another interval in the list so we have to remove all the overlapping intervals like all the intervals which are already covered by another interval we have to remove those intervals so uh interval this a b is covered by interval c d only if a is greater than c and b is greater than just b is greater than this d ah sorry less than is less than this d we will understand this example so we have to return the number of remaining intervals after removing the over these intervals covered by intervals we have to return the remaining intervals so let's take this example over here if we see these are different intervals right we have we are given 1 4 so if you draw this will be 1 4 then we have 3 6 so let's say 3 6 right and then we have 2 comma 8 so 2 comma eight right two comma eight now if you see this interval three comma six this lies in the two comma eight interval that is like let's say this is a b and this is c d so this interval a b is covered by c d how see a c a is greater than or equal to c this condition a is greater than equal to c and b is less than equal to d that is b is less than equal to d so then this a comma b interval is already covered by is covered by a c comma d interval so we will not take this c a comma b interval in our answer this is already covered by 2 comma 8. so we will take that only we will not take this all right and 1 comma 4 is already uh is not covered by any other because c two comma eight one is outside two so that is not covered by this one so this will be one interval and this will be another one so two intervals this will get reduced and only two intervals will be left so output will be two all right this is a problem see it's pretty much clear what we need to do simply see let's see what we have to do exactly so first of all in these type of problems now whenever we have intervals first thing which we have to do is to sort we have to sort the intervals why sorting is required c we need to compare for each interval let's say this is a comma b and this is c comma d so we need to compare these start points and the end points right starting these are the start points a and c and these are the end points b and d if we do not sort right we will get wrong answers because c this 3 comma 6 is occurring before this 2 comma 8 right just do one thing first we will sort this and then you use the same algorithm without sorting then you will understand why there is a need of sorting the array right that way it will be more clear so let's see first uh when we will sort it right so see we will sort this so it will be by default sorting according to the first value when we sort this array so after sorting this will be one comma four then two will come to comma it will come because it's sorting according to the starting this value so one comma four then it will two comment and then it will be three comma six so this way it will be sorted all right now let's do one thing let's take three variables left right and the answer which we will return that is rest let's take name it as this and let's take this as minus one's initially all right so see now we will start the traversal and any time suppose the uh we are currently at this interval so suppose this is our a comma b and this is our c and this is our d right a comma b this c and d so if this interval lies in this interval then we will not consider it right okay so let's do one uh then let's start the traversal so this is c comma d you can name it anything so we will start from the beginning only we start from beginning one comma four that is we will check uh does this interval lies in this interval or not so for li uh this is a comma b right this is a comma b and this e comma d so for in order for this interval to lie in this interval what should be the condition c less than equal to a and b less than equal to d right this should be the condition over here a is 1 and c is what minus 1 and d is what minus uh minus 1 and b is what 4 so this condition is true but this is not true right so this interval does not lie in this interval hence we have to consider this interval so when we are considering this interval we will increase this count by one because now we have one interval and we will update left and right will become one comma four one and four right so now let's hydrate further so this pointer will now go to the next interval that is here this will be a comma b now see does this interval lie in this interval or not simply this is a right a is greater than c 2 is greater than 1 this is ok but is this ok this 8 which is b should be less than this d in order to for it to lie in this but see one comma four is this and two comma eight is this so obviously it did this two comma does not lie in this now so we will uh increase this count because this we have to take interval and we will move further and before moving further make sure to update the left and right because now this is the latest interval right so left will change to 2 and right will change to 8 okay so this is how we do it now let's see for this one so here a comma b now see c is what 2 less than equal to 3 so this condition is 2 okay is this condition 2 b is what 6 is less than equal to d is what 8 so this is also true means this 2 comma 8 interval here 3 comma 6 lies in this interval hence this is already covered by two comma eight we will not take this interval again all right so we will not increment res so right we will check how we will check whether this interval does not lie uh lies between this condition or not right we can just simply check if this is greater like this b if ideally what should be there b should be less than d n b should be less than d but if b is greater than d it means this interval does not lie here right so then just we will not increment s we will uh not uh yeah we will not uh if we will incrementalize like if it is not lying we will increment rest but if it is lying then we will not increment so this is approach right so let's see the code for this i hope you understood so what we will uh first do is we take we have taken three variables res left and right all right initially this was minus 1 and this was 0 and we sort this 2d array and then we go to each interval and we check if this is not satisfying the covered condition was this that c should be less than equal to a and b should be less than equal to d right so see this to always be uh will be greater because we have sorted in ascending order now so this thing these will be always greater than the previous one this will be always greater than the previous one main condition is this one all right so and so if b this is your b if b is greater than d that is if b is greater than d then we have to consider that interval so increment res increment update left and right will be maximum of right hand the current one so right will always increment right will always get incremented all right sometimes it might happen now that we have an interval let's say here also it's two like this so this might change direct just do one thing dry run this algorithm with this test case we have 1 comma 4 2 comma 6 and 2 comma 8 we will better understand how it's working right so every time if the condition is not satisfying we will update address and right will always we will update and return rest at the end so if we submit this time complexity for this is c we are using sorting so time complexity will be uh n log n where n is number of intervals and space we are not using any extra data structure so we are just using variables so that will be of one space complexity and time complexity and if we submit this so it's working all right so i hope you understood the problem and the approach let me know in the comments if you have any doubt and just let's see if it's taking a lot of time so like there are different questions which are related to this question if you want to practice so if you go to here we have similar problems like merge intervals so all those problems we have so you can try those problems as well so it's taking a lot of time let's submit it so it's getting submitted right so if you found the video helpful please like it subscribe to my channel and i'll see in the next video thank you
|
Remove Covered Intervals
|
maximum-subarray-sum-with-one-deletion
|
Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**.
|
How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.
|
Array,Dynamic Programming
|
Medium
| null |
830 |
hello everyone so in this video let us talk about one more problem from lead code it is an easy problem that is position of large groups the problem goes like this that in a string s it consists of lower case letters these letters form conjugative groups of same characters so it will form conjugated groups as you can see that it is a then b then x axis is an x z y so these are consecutive groups let's say of this type now a group is identified by the interval okay a particular group is undivided like what is the start and the end of a particular group that is this now a group is considered large if it has three or more characters of the same type that is a group now return the intervals of every large group in an increasing order by the starting index so this is the group index so let's say that there is a large group which is greater than equal to three that is this axis start from the third index enter the sixth index nothing else any group is like having greater than three characters similarly this has no character that is greater than three and this has three groups greater than three and like this is d this is and this so that's overall uh code what you can directly do in this that you have to form groups and we have talked about different problems on this channel about groups so if you haven't checked this out i will also link some problems in the i button but what's the major intention for this problem is that whenever we are forming groups to insert at the end a different type of character that is not in the whole universe of the characters that you are using in this whole string that is only lowercasing etcetera let's say you insert a hash at the end of the string so that you can find out different groups easily instead of just like writing one more if conditions it becomes very easy now what you will do is that you will iterate over and fund every group you have to also store the first occurrence from the group where start and the occurrence set with the group ends and uh whatever if the length of that group is greater than equal to three you will just insert that starting and ending index of the group in sub let's say answer vector and just find it on that's our logic nothing much complicated here as well that is one of the good parts that it will convert to you what you have done is this is the last that is starting from zero which means that what is the last occurrence of the group that we are trading over so we will starting for the first index the first group that was zeroth index and inserting a different type of character that's a hash in the end of the string this is just to terminate the whole for loop at the end but also taking care of the large group of the string that we have this is the answer vector that will store the final answers this is the total which is the group length okay like whatever group we are trading what is the length of that we can also calculate from the current index minus the last index but you can also take this variable your choice now what we will do is that we will iterate over this whole string from the second index and what i'll do is that i will just check the like that whether the current index and the previous index are same which means that we are going in the same group if you're going in the same group which means that it's cool we'll just increment the total in the same group but whenever i find out that my group changes like i have completed one particular group what i'll do is that i have the group length and i have the last character at which the group was starting at what i'll do is that i will just first take that the length of the cat like the group we have with greater than equal to three if it is greater than equal three i will insert the group in the answer vector the group starting was last and the current is i minus one because the is a character at which it changes out but this the same group was at i minus one so it will it we insert that in the answer vector now because we have started a new group we will make my total equal one because now group new group has started and the last becomes equal to i because now a new started so for that group the leftmost index is now pointing at i because now we have let's take an example let's say we have the string let's say a b so what i'll do is that i will match this with this which means that in the same group matches this with this it is not in the system group so which means that this group has ended we are on this i so the group was from this year's index to i minus one this is the group and now you start from the new index like new group so this group will start from i and now again match this is the same group but as you can see that now we have no termination point at this point the follow will break and if the volume will break then we will not take considering of this group so what you can do that we add a hash well when we go on this point it's not equal to this and thus whenever i find not equal to this i will find out that this group is now completed group is not completed the length is equal to 3 so now the starting index was we have this i and the current index was i minus 1 because we are on this i so i minus 1 is the end of this particular group which is insert that keep on editing that and just print out the answer that is the different f which has length written equal and they will be in the sorted form because we're trading from left right so all of them will be sorted so the overall tango city is o of n because we're just doing a for loop the space complexity is storing out this answer vector so n as well for this that's the whole time of city and space computing for this problem if you're safe now you can mention and coming box for this problem thank you for watching till the end i will see you in the next bundle keep coding and bye
|
Positions of Large Groups
|
largest-triangle-area
|
In a string `s` of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`.
A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`.
A group is considered **large** if it has 3 or more characters.
Return _the intervals of every **large** group sorted in **increasing order by start index**_.
**Example 1:**
**Input:** s = "abbxxxxzzy "
**Output:** \[\[3,6\]\]
**Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6.
**Example 2:**
**Input:** s = "abc "
**Output:** \[\]
**Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups.
**Example 3:**
**Input:** s = "abcdddeeeeaabbbcd "
**Output:** \[\[3,5\],\[6,9\],\[12,14\]\]
**Explanation:** The large groups are "ddd ", "eeee ", and "bbb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` contains lowercase English letters only.
| null |
Array,Math,Geometry
|
Easy
|
1018
|
122 |
hello everyone let's look at best time to buy and sell stock number two if you did not watch the first question for this theory feel free to have a look at it first the question number is one to one back to this question the problem statement is we are giving an array the eighth element is a price for a given stock on day i and we want to find the maximum profit and we can complete as many transactions as we want but we must sell everything before we buy it again let us look at the first example the input is seven one five three six four the output is seven so we can buy on day two at price one and sell on day three at press five the profit is four and then buy on day four at price three and sell on day five i press six the profit is three by adding them together the profit is seven in general there are two ways to solve this problem using dynamic programming or grady i will explain dynamic programming first as zero we need to maintain our memorization array or dp array for any day we can either have stock or have cash so we can claim two memorization arrays we can call them cash array or stock array so our cash array and stock array if we have cash at the i what would be the profit for day i it would either be we don't do any transaction so the profit depends on the cash balance from day i minus 1. or we sell what we have and cash in that's stock i minus one and plus today's price really depends on which one is bigger what about if we hold stock at day i what's the value so same thing either we do not do any transaction let's stock i minus one oh we buy in let's cash minus one minus price i depends on which one speaker and in the end we want to return cash prices dollars minus one what would be the initial value i guess for day one the cash will be zero and for stock it will be minus price is zero let's look at it again we have cash array and stock array cash array refers the profit if we hold cash from day one to the end stock array refers to the profit if we hold stock from day one to n and for any day i we update a cash array and stock array individually depends on previous day's condition and in the end we return cache length -1 let's look at the code implementation and then we can do our for loop and update individual cachei and stonecard and in the end we can return cash prices down length -1 before we submit let's do a lens check for prices so if the less for prices is zero or one so the profit will be zero and let's sum it passed let's look at the complexity for space is 1 because our cash array and stock array the length will be the price the length and then let's look at time it's still on because we have this for loop once to optimize the space we can simplify the cache array and stock array to make it one variable because we only depend on the previous value we never depends on the value before the previous one so we can optimize this and make them as two variables but i will leave like this let's also look at the greedy solution for greedy solution we don't even need to concern when to buy and sell today we hold cash or we do transaction as soon as the price goes up compared to the previous day we just sell and take profit in because we can do as many transactions as we want let's look at the code we can remove this we still have this lens check and this is our profit so as long as price goes up with which itself and in the end we return profit let's remove this let us submit it looks good let us look at the complexity here for space is constant for time is our n because we have one for loop if you have any questions please leave a comment below thank you for watching
|
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
|
1,688 |
hey everyone today we are going to solve the problem number 168 count the number of matches in a tournament okay so here we are given an integer n which is the number of teams part participating in the tournament and we just have to return the number of matches uh going to happen in that tournament it's a simple math simulation problem ask in Adobe and Yahoo okay let's try to solve this problem so let's say uh we are given with n teams in the first tournament we are going to like have matches let's say from 1 and 2 3 and four 5 and six so in the first tournament we are going to have three matches and after that let's say the first win the match 3 5 7 now in the second tournament two matches so overall it is going to be uh five matches so far so after that let's say one M wins the match five there will be one more match in third tournament okay so overall they're going to be six matches okay so how do we decide that so match is going to be uh between two teams at any moment so like we will see whether the number of teams given to us is even or old if it is even it means we can uh pair up each team and if it is old so we can pair up uh n minus one teams then the next team will participate in the further tournament okay so if you have to write the code let's say for the seven s is our total team we have to keep on playing till one team is left so there are 17 so uh there is going to be three matches between first six teams so n - 1 / 2 matches will be played in n - 1 / 2 matches will be played in n - 1 / 2 matches will be played in first tournament okay and what how many uh teams are going to be participating in the further tournament the number of matches happen plus one is for the team which has not participated in the first tournament okay if n is old or maybe n is even in that case there will be n by two matches and N by two match n by two teams will move to the further tournament because after each match one team is going to win and one team is going to lose so we can generalize this formula so now until we are left with one team if the te if the number of teams is even it means all the team will participate in the matches and there will be n by two teams moving to the further tournament if we have old number of teams nus 1 by two teams matches will happen and N minus 1 by two team will uh win the match win those matches and one team which did not parti bit we'll move to the further tournament okay so this by this way we can uh get to the solution but I'll try to analyze like uh every team is going to participate in a match and there will uh like every team is going to lose except one team here we can uh analyze that every match is going to eliminate a single team so uh like let's say in the first tournament we had three matches and each match has eliminated one team and now how many teams do we have to eliminate because we want one winner so how many teams we have to eliminate n minus one let's say if we are given with seven teams so we have to eliminate same team six teams and with every elimination there is one match happening so we can directly say that there is n minus one matches going to happen with n teams given to us so we can directly say return n minus 1 so this can be our answer so this is our simulation to this problem and we don't need to do this every time because we came to this conclusion that every match is eliminating one team and we have to eliminate n minus one team so there is going to be n minus one matches to eliminate n minus one team so one team will be left which is the winner so here we have come to an conclusion that for end teams in the in a single tournament we are going to have n minus one matches so we can directly return n minus one and if we if you want let's also try to submit that problem whe it is fine or not B 100% of users whe it is fine or not B 100% of users whe it is fine or not B 100% of users with Java okay now let's write the code for that as well uh for the steps we have mentioned in the problem statement so if there is an even number of teams so we are going to have n minus 2 matches n by2 matches if we have if we are having all number of teams there will be n minus 1 by 2 matches Plus because one team will participate in the further uh step so let's take an variable answer to capture our answer in the end we are going to return that okay now while n is greater than 1 if n is equal to 1 we won't play any match that is our winner if n / 2 equal to equal to0 it winner if n / 2 equal to equal to0 it winner if n / 2 equal to equal to0 it means it is even if it is even then answer plus equal to n by2 there are going to be n by2 matches and N by2 team will move to the further step so n IDE equal to 2 if it is OD then answer will be equal to n- 1 / 2 there will be nus 1 iD 2 to n- 1 / 2 there will be nus 1 iD 2 to n- 1 / 2 there will be nus 1 iD 2 matches and the team going to be on the further steps are nus1 by two plus the plus one team that did not participate let's try to submit that as well it is submitting successfully okay hope you understood the problem thank you guys
|
Count of Matches in Tournament
|
the-most-recent-orders-for-each-product
|
You are given an integer `n`, the number of teams in a tournament that has strange rules:
* If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round.
* If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round.
Return _the number of matches played in the tournament until a winner is decided._
**Example 1:**
**Input:** n = 7
**Output:** 6
**Explanation:** Details of the tournament:
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.
**Example 2:**
**Input:** n = 14
**Output:** 13
**Explanation:** Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.
**Constraints:**
* `1 <= n <= 200`
| null |
Database
|
Medium
|
1671,1735
|
983 |
all right so this question is minimum cost for tickets so uh just re-over the problem uh just re-over the problem uh just re-over the problem and I'm going to talk about the solution so you are going to uh you have this array and it costs array right so what you have to do is what you want to find on the last day inside your day survey right so it's going to be lasting next and I need to create a DP so the range is going to be given from 1 to 365. so you can just say uh you know zero to 366 I'm sorry zero to 265 so it's going to be it's 366 space and the last is going to be 20. so I don't have Traverse after 20 right so I can say I Traverse from 0 to 20. and 0 is not going to be used so 0 by D4 is going to be what uh zero right dtp zero is going to be dp0 I'm sorry db0 is going to be zero right dp1 is going to be based on the value the cost value and the days value right and I need to keep traversing so I'm going to say I based on the subscribers so if I is equal to the days eight I am going to find out the value for DPI so if this is a one day pass right I'm going to say okay DPI minus one I sorry I minus 1 plus the current value for the days sorry for the one day pass so this is what uh this is what the password I'm going to try it again because it might be a seven day pass would be cheaper right so we want to return minimum right so DPI again current DPI I understand minimum right so it's going to be mean based on the what the current value I have for one day so it's going to be DPI and in comma and then I want to make sure my index I is what is valid right so if index is equal to one minus seven is going to be negative value right and then inside the DP is only positive right so we want to make sure it's going to be between 0 to I minus seven right and then we plus current value for the Cosa causes one this is seven day pass and exactly going to be the same idea for a 30-day pass so I again idea for a 30-day pass so I again idea for a 30-day pass so I again minimum I and zero comma I minus 30 and then this is called set two right so straightforward enough I mean you don't have to worry about too much so uh again the vehicle the new image and this is going to give us 366. in my last day zombie they said days the next minus one and I will have to return this and then I'll stay all right and then I have to keep my record for what uh for a current index at the data rate so it's going to change so I'm traversing for I equals to one I less than equal to last day and I plus so if I does not equal to what is a j right and I'm gonna just copy my current status the DP status to the previous one and else minimum number of dollars you need to travel so it's gonna be what this is going to be one day it's gonna be a what DPI minus one right plus the concept one zero right so this is one day okay how about the seven days so it's going to be DPI equal to mass I mean and this is the original one so which is going to be a one day pass and this is gonna be what Master Max zero two I minus seven you don't want to get all the bond right and then you want to plus the crosstalk block one because you want to know it's a seven day pass right and then exactly the same idea for DP I for the 30 day API DP Master Max zero comma I minus seven and minus 30 plus positive two okay all right now we are actually inside what the base value right so because I does not equal to this is J we need to you know uh keep the previous status right but if we are actually equal with your action and the spot is one right and then we need to move on right so it is J plus over here at the end and then yeah I mean you are not going to be out of bound right because uh the last day is going to be what the J the this is J right so uh let me run a code okay I do have a typo should be typo right cause yes all right um I'm gonna just toss okay oh so it's all about for this situation so uh give me one second okay uh so this is a problem I keep my value inside the DP another days okay so I need to say DP last day so everything should be okay so I just you know change the value over here and I want to submit again so this is a solution so let's talk about the time in space this is going to be a space don't be all of what 366 right this is going to be a time is gonna be what all over last day so it's gonna be all of D I promise I don't know but it looks like it's all the d representing the one the last day and uh if you want to find out the debug mode you know I'm gonna just roll them over and then it should be okay all right so this is way too much but you still get a 20. so uh you just have this you know imagine this is in this 20 right so just keep going pause the video any second if you are confused so explain it right so it's gonna be 11 right and the answer is 11 right all right so if you have questions leave a comment below subscribe if you want it peace out bye
|
Minimum Cost For Tickets
|
validate-stack-sequences
|
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000`
| null |
Array,Stack,Simulation
|
Medium
| null |
430 |
hello everyone welcome to let word coding today welcome to South problem 430 frettin a multi-level doubly linked list multi-level doubly linked list multi-level doubly linked list so given this structure we need to traverse the linked list level by level and then I returned the following output so from 1 2 to 3 then 7 8 9 I mean 8 11 12 10 9 10 4 5 6 so we need to use a stack to do a depth first search let's first demonstrate our algorithm so first we need to put the first note on the stack and we are also creating a dummy node 0 then we get the element from a stack and then connect it with dummy node we also put the next element of the current list to the stack so the next element is 2 and we get 2 then we put three we get three then if it has a children we need to put the next element first for then put his children seven so we can use the stacks last in first out properties to do a depth first search we get seven and then samus neck element then service next element is eight we get 8 okay eight has a children so we need to append nie first and then append his children 11 so here we get 11 then we need to put the next note of 11 which is 12 we get 12 then we get nigh then we need to put the next element of nine or which is 10 we get 10 at last we get four and we append five to the stack then we get five upend six stack and then we get six eventually the stack is empty and we get a frightened structure okay so yes 1 2 3 7 8 11 12 9 10 4 5 6 twelve nine ten four five six so this is our algorithm that's coded if the head is not we just return at the head otherwise we need to create a dummy node you and then we put the first note on the stack while stack is not empty we need to do the following operation so let's get the current node and then we need to create the doubly linked list structure you let's create a new node and we said not the next pointer to the new node and the pref pointer to the dummy node so it is doubly linked then we increment our dummy pointer then we need to append either the next note or its children note so if it has a children I mean child then we append it otherwise we hand next note you so here we need to append the child then append the next node in the end we just need to return Tommy thought next I mean result dog next let's run it all with never mind we need to append the note not at least so if it is not null we do this you oh and by the way we need to unset the press pointer to make it a well it doubly linked list and then is wrong answer what happened so one two three okay one two three seven eight nine ten you so we need to append the next node then the Chou's node okay let's submit it that's it so let's analyze our time space complexity as indeed linear with respect to how many nodes in this link list and the space complexity is also linear because we create a node we return okay thank you very much if my snow to help you are please feel free to leave a comment bye-bye
|
Flatten a Multilevel Doubly Linked List
|
flatten-a-multilevel-doubly-linked-list
|
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
| null | null |
Medium
| null |
1,679 |
Hello ji, how are you guys? Welcome to the week one of the Weekly Lead Code Challenge of I hope you have registered on our website, so if you have not done so yet then do it quickly, we will help us track your progress. If it will help then let's move towards the solution ok so let's start with the 1st question of a week one question let's open the question is saying max number of k is the sum question you are given an integer array of numbers and in integer of k You are given an array and an integer. In one operation you can pick two numbers from the array whose sum is equal. In any one operation you can pick two numbers from the array whose total sum is equal to two. This is the integer given to you. Okay, what you have to do is return the maximum number of operations you can perform on the array. Basically you have to tell the pairs whose sum is k and return the count of how many such pairs exist. Okay, we understand this thing, how to do it, they understand, suppose you have given this array, tooth 4, okay, nut, 3, 4, okay, what else is given to you, F, okay, and here what is the sum of five. Pairs have one and four, ू and ॰ have ok, two pairs exist ू and ॰ have ok, two pairs exist ू and ॰ have ok, two pairs exist with me which have sum, this much I have understood, let's see how they do, I wrote tooth and four brother two pointer. Approach I put I in the starting I put J in the ending Okay I said if the i number plus zeth number is equal to equal k plus sign of k plus mind you if it is equal to k then make aa plus j Make it minus. Apart from this, also keep a count of yours. Make it plus that you have got a pair. If it is not so, then who is the smaller number on my left, who is the bigger number on my right, so if I want to increase my sum. So I have to move from smaller number to bigger number. If I want to increase the sum, then what does it mean that the rectangle number plus the zth number is less than that, only then I have to increase the sum and if this is to increase the sum, then what do I do in this case? I can do I plus, okay only I and no one else and I said the opposite condition if I have to subtract the sum i.e. opposite condition if I have to subtract the sum i.e. opposite condition if I have to subtract the sum i.e. rectangle number plus zth number which is of greater than then I have to subtract the sum then What can I do in this case? I can make h minus. Okay, we understand why we have to do this because we have to keep reducing our pairs and check out the ones that we have used. Leave it and move inside, keep moving inside the ray, keep moving inside, but there will be a problem in this, now if you notice an example below, it is given here 313 43 This is an array, it is an unsorted array, so there is no sorting in it. You have to keep in mind that when you are following this approach, you will first sort the array. How is the sort function? We do not need to elaborate, we will use the inbuilt function sort. Let's start coding and understand what to do. If you are okay then I said, first of all let's sort whose numbers from the beginning till the end. Okay, after sorting this much, I understood this much. I said, look at the thing, if the size of the numbers is less than two. So don't make the return zero if not even a single pair is found. If you get zero pair then why do this because pair means two numbers. If there are not only two numbers then the total is not even a single pair. Then simply return zero. We have to keep reducing our condition, it is okay to find, after this there is nothing, let's keep one left is equal to 0, one int right is equal to two, where do we keep numbers dot size minus and but okay, this much is understood. Let us also create a count which will count our pairs. Okay, we have understood this much. Moving forward, I said, till how long should the loop last, two pointer approach left, as long as it is smaller than right, then left, lesson right, till then the loop will work. What should I do, if your numbers are on the left, I should add them to the numbers on the right and compare and see if k is smaller than k. What is this integer that came to you, we just discussed it, so if it is k. If it is smaller than , then what happens to the left, it should move one smaller than , then what happens to the left, it should move one smaller than , then what happens to the left, it should move one step forward, because the array is sorted, if we move left then the total will increase. Ok, the same condition has to be reversed if the same thing has just left and right. If the sum of a is greater than k then I have to subtract it. If I want to subtract the sum then I move it from right to left. Right minus my array is short so there is a maximum number on the right. Then do minus. Two will be reduced towards the back, third thing, what will come in the else, either it is big or small, both things have been handled, what is left of the third thing, if equality comes, then first of all brother, increase the count that one pair has been found. Because if it is equal, then I got the pair. Secondly, if I got the pair, then I have used these people. Don't count them again. Now the hands are in hand, first move left, move back right. It is okay not to use them. So much work is done when so much. When the work is done, when I come out of this loop, I will have total count of pairs. How many agens do when I will have total count of pairs and what did he say that what is the maximum number of operations that can be done i.e. how many maximum If you can be done i.e. how many maximum If you can be done i.e. how many maximum If you can calculate the number of pairs, then don't do anything, just return it to someone, we have returned the count, run it and see if it is accepted, submit and see, it has also been submitted, I hope you understood. Will it be okay? Yes, I hope you have understood this question well. You will also get its code and a detailed explanation on our website in editorial form, so you can check it out too. Like the rest of the video, your friends. Share it with them, they will also get some benefit and also subscribe to our channel till then thank you for watching this video till now time bye
|
Max Number of K-Sum Pairs
|
shortest-subarray-to-be-removed-to-make-array-sorted
|
You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], k = 5
**Output:** 2
**Explanation:** Starting with nums = \[1,2,3,4\]:
- Remove numbers 1 and 4, then nums = \[2,3\]
- Remove numbers 2 and 3, then nums = \[\]
There are no more pairs that sum up to 5, hence a total of 2 operations.
**Example 2:**
**Input:** nums = \[3,1,3,4,3\], k = 6
**Output:** 1
**Explanation:** Starting with nums = \[3,1,3,4,3\]:
- Remove the first two 3's, then nums = \[1,4,3\]
There are no more pairs that sum up to 6, hence a total of 1 operation.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= k <= 109`
|
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
|
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
|
Medium
| null |
1,046 |
welcome to tim's leco challenge this problem is called last stone weight you are given an array of integers stones where stone's eye is the weight of the i stone so you're playing a game with the stones on each turn you choose the heaviest two stones and smash them together now suppose the heaviest two stones have weights x and y with x less or equal to y now the result of this smash is if they're equal to one another both stones are destroyed but if they're not equal to one another then the heavier stone will destroy the weight of the smaller stone and whatever remains is going to be the stone another stone that gets added back into our array so it has a new weight of either y minus x or x minus y at the end of the game there'll be one stone left what is the smallest possible weight of the left stone so i don't know why they worded it that way there's always going to be one stone left so it's not like what's the smallest possible is just what's going to be the last stone here okay so if we had this array here we could certainly just code this out the way it's worded we can take the uh we can sort it and then take the top two try to figure out do we create a new stone or not and then add that back into array resort it and just continue that on and on right but that's going to be what ends up becoming n squared i believe because we're going to be sorting it each time and going through the n certainly there's got to be a better some sort of better algorithm right and the data structure that should pop out in your mind right now immediately is a heap we already know we're going to pop off the top two heaviest right so what would be best for that what about a max heap right all right so if we can do that then the algorithm becomes pretty easy we can just heapify this array pop off the two heaviest ones add back heat push it back into the array and just continue on until we have one stone left and that should be it so let's take our stones and let's stepify it let's see should be deepify stones and we will say while length of stones is greater than one oh well one thing actually i forgot in python these heaps are going to be min heaps so we want to make this to a max heap so we're actually going to re-formulate these stones into let's say re-formulate these stones into let's say re-formulate these stones into let's say negative s4s and stones and now it's going to be all negative and these will be sorted into the max heap right okay so while stones is greater uh let's see we'll have two stones right the first stone let's first keep what pop from our stones and we're going to actually have to make this back into a positive as well as the second stone make it be pop stones multiply that negative oops and we're going to calculate what's left over okay left over is going to just be the absolute value of first minus second right and now we just take over this whatever this stone is maybe there's nothing left or maybe there's something left but doesn't really matter we can just add that back into our heap we'll say heat push back into stones our item which is left over and you might think well what if it's a zero well yeah i mean you can certainly put a if statement say like if it's zero don't add it but you know you don't really have to because if you think about it if it's zero and we have one stone left it's almost like there is no stone right so it'll just disappear and add it back in a little bit inefficient but i think it's easier to read finally let's just return whatever at the very end there should be one stone left right so let's return whatever is left let's make that a negative okay so that's going to make it back to the positive here so let's make sure this works ah it does not see oh of course i need to when i push this back it's got to be negative again right so that okay so that looks like it's working let's go and submit it and there you go so this is going to be a n log n solution that's it i think the main it's supposed to be easy i don't think it's that easy but i think the main sort of takeaway from this is you see this problem you should immediately think heap okay all right thanks for watching my channel remember do not trust me i know nothing
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
394 |
hey guys now we're going to solve a little problem decode string this is a popular problem you're given an encoded string return its decoded string the encoding rule is k encoded strings where the encoded string inside the square brackets is being repeated exactly k times note that k is guaranteed to be a positive integer you may assume that the input string is always just valid no extra white spaces square brackets are well formed etc furthermore you may assume that the original data does not contain any digits and that digits are only for those repeats numbers k for example there are not b input like three a or two four for example if you are given a string equals to this string you have to return this string this is encoded string and this is decoded okay here we have three and here we have a inside this square bracket so we have to repeat three so we have to repeat a three times here we repeated a three times then we have here bc and we have number two so we have to repeat bc twice bc and here we have aaa bc so we have to return this string for this input when we have s equals to these strings here you see we have nested brackets so first we have three then we have this first bracket then we have a then we have two and then we have c so here we have to repeat c twice then it becomes acc then we have to repeat acc three times so we have here acc sec scc and the rest of the input you can read on your own and this is the problem whenever we see we have parentheses then it tends to use stack to solve this problem first look up understanding let's assume you are given this input string to solve this problem we are going to use to stack one for number and stack two for strings okay we will iterate through these strings from left to right we have here number three we'll insert that number to this stack one okay if we insert then the stack will be represented like this then we have first packet and here inside we have string a and the string will insert in this stack too okay then we see we have the closing bracket whenever we found closing bracket will pop out the string from the stack and the number from the stack and then what we will do we will repeat the strings num times so we'll repeat a three times a okay and we'll removed it from this stack since we'll pop since you pop out the element okay then we have here two so let's insert two to this stack then we have first packet and inside we have this string pc so let's insert bc to this stack then we have this closing brackets whenever we found closing bracket will pop out the string and the num and will repeat the string by num times so if we repeat bc to white then it becomes bc and if we append this bcbc with this string aaa then we get this string and this is our answer all right also we will pop out the element from the stack this is the decoded sting of the given string okay for better understanding let's take another example let's suppose that you are given these strings so we used to stack to solve this problem first we have the number three so let's insert this number to this stack then we have inside the string a so let's insert a to this stack then we have the number two so let's insert two to this stack then we have the string c so let's insert c to the stack then we have the closing brackets whenever we found a closing bracket what we will do we will pop out the element from the stack so if we pop out this c and this 2 and we'll repeat the c twice so c okay then we found another closing brackets what we will do will pop out the element from the stack in this case with about a and three first we'll pop out the a and we'll append the c with a so the string will be represented like this then we'll repeat this acc three times by popping out this element three so if we repeat scc3 times ac c then a c all right and this it the decoded string of the encoded string and this is how we can solve this problem i'm not going to go through the pseudocode i have attached the source code to this video link in the description check that out and this is the intuition to this problem if you understand the intuition then you will be able to understood this problem pretty easily alright guys this is my solution to this problem thanks for watching i'll see you in the next video
|
Decode String
|
decode-string
|
Given an encoded string, return its decoded string.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
The test cases are generated so that the length of the output will never exceed `105`.
**Example 1:**
**Input:** s = "3\[a\]2\[bc\] "
**Output:** "aaabcbc "
**Example 2:**
**Input:** s = "3\[a2\[c\]\] "
**Output:** "accaccacc "
**Example 3:**
**Input:** s = "2\[abc\]3\[cd\]ef "
**Output:** "abcabccdcdcdef "
**Constraints:**
* `1 <= s.length <= 30`
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
* `s` is guaranteed to be **a valid** input.
* All the integers in `s` are in the range `[1, 300]`.
| null |
String,Stack,Recursion
|
Medium
|
471,726,1076
|
77 |
77 combinations given two integers n and k return all possible combinations of k numbers out of range 1 to n and as you see is inclusive from 1 to n you can you may return the answer in any order let's talk about combinations so what is a combination let's say we have two numbers one and two and if you want to generate combinations of one and two is going to be one and two and one are the same so it doesn't matter if you return one and two or one they are all the same uh thing but now let's see what is the difference between combination and permutation is in the permutation order matters so if we have if you are going to generate permutations of one and two it's going to be one and two and one so for the combination order doesn't matter but for the permutation order matters right so this is the difference between combination and permutation and now we know what how we can generate combinations let's go through an example let's n is equal to five and k is equal to two what are the all possible combinations of this so n can go all the way from one two three four and five these are the possible ends that we have and if you want to get the all the combinations is going to be one two it's going to be one three it's going to be one four and all the way to 4 5 these are all the possible combinations the way that we are going to solve this we are going to use a pointer here and we start generating the combinations using the pointer as the base case so we are going to say one two one three one four one five and then the pointer goes forward two three two four two five and goes forward three and so on right so let's see how we can do this we are going to have a result list that we are going to stores all these combinations in it and you are going to have a recursive function that i'm going to tell you what we are going to pass to this recursive function and then what we are going to do we are going to call this recursive function with the values and we are going to return the results as the answer so for calling this recursive function as i said we are going to use this pointer so we start from index 0 because this is what they we start from 1 because this is what they have asked us to do and we are going to pass in an empty list for each combination that we are going to so we are going to have a pointer and we are going to have a list here and then what we are going to do we need to have a base case as you see we go to the next pointer when the length of the combination that we have made is we go to the next number when the length of the combination that they have made is equal to k so we are going to use that as the base case for the problem so we're going to say if the length of the combination that i have is equal to k i'm going to add that combination append that combination uh to the result so combination is going to be added and then we are going to um return and how are we going to generate if we are going to have a for loop and the range is going to start from wherever the pointer is all the way to the end but because the range is exclusive as exclusive and we need to say n plus one and then what we are going to do we are going to say combination we are going to append what we are going to append i and then we are going to call this function recursively for i plus 1 and we are going to pass the partial list that they have made and after we are done with this after adding that uh combination the new combination to the result we are going to undo our choice we are going to pop that um value from the um from the list so let's run this code and let's make sure that we don't have typos for the pointer there we go we have a typo here and for the results we have a title here we need to make sure there are no typos and combination there we go so let's run this code and see how it works there we go it works fine let's go through an example so you can see how it does the job so we start from pointer is equal to uh one and we are going to call the recursive the pointer one and empty list and then there in the length of this list is not equal to k so the for loop starts from one all the way to five right because we are going through this example when n is five and k is two right and then we are going to add uh append one to the list and we are going to call this function recursively we are going to call this function recursive which is now going to be i is equal to 1 plus 1 is going to be 2 and the combination is 1 that has been passed is the length of combination equal to uh k which is two no it's not so uh we are going to have a for loop that starts from two all the way to five and then we are going to add this number the index add i equal to 2 to here and we are going to call the function recursively now for three recursive for three and one and two as you see here now the length of list is equal to uh k and what we are going to do we are going to have a results here and we are going to add one and two here and what will happen it is it will going to return the result and it's going to pop the last item from here and now i is equal to three so it goes uh it calls the function recursively the length is equal to two so it's going to add one and three here and it returns the result then it's going to pop uh the last item and then it's going to be four and then it's going to be five and um and then it's going to return this and it does this recursively until we have all the combinations thank you
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
1,584 |
That's what guys welcome and welcome back to my channel in this video we are going to solve minimum cost to connect all points what is in this problem you have given a bundle of batter which is giving points in this it has given points point of points And what you have to do is, which points have to be connected here, the points have to be connected in such a way that we get minimum cost after the gas connection, what is the cost here, the distance between two points is the cost, so here How will you fix the distance? Here, to find the distance point, if someone has given the coordinate points actions of MY I N It has to be done, okay, the value you get will be the cost, so what we have to do is to connect the points keeping this in mind so that what you get after connection is the minimum cost and if all the points are also collected, then how to solve this problem? Will we do this? This problem is based on Minimum Spanning Tree, okay if we do n't tell you then read about this concept and understand it, then it will be easier to understand this problem here, it will be easier to understand then it is okay, then what do we do about the problem? Is there a problem in understanding, are you looking at the famous name, what is given here, five points have also been kept and we were also told that this point should be connected point to point and together we have to point the cost which is My mother is fine, after the connection, I will see how to connect, how to find solutions, how to use it, then we will see. Okay, so what is your 5 point here, I have given you 5 points, so how do you connect? If you book a connection then there can be a lot of them, so we have to take care that we connect in such a way that we get the minimum amount. Okay, so how can we connect here? If we have given Rs 155 here then what will you do, you will collect it from here. So let's see the Bluetooth account here, this is ours, we can connect this from here and from where we can also connect this point to this right, we can reduce this point, we can connect this also to this, we can connect this point from here, this We can connect from here, then what can we do with it, I can connect from here, right try, we can connect it from here like this, or we can also connect it from here like this, we can connect it from here like this You can connect from there but now finally if you see all the cost, fine province and distance between the two points then you will finally get one, this sparing bird chug, in which you will get minimum cost here, okay so from here You see this sun, let's see the result of the first, if we connect it to this, okay, if we do zero and two, then what is the distance here, we will get two - what is the distance here, we will get two - what is the distance here, we will get two - 0290 angry four, so what is our photo, this is the phone again. What does it mean to connect it to 0707? What do you get by connecting it to 0707? JIO - which will actually be 727. JIO - which will actually be 727. JIO - which will actually be 727. This is fine, so this is what we got here, one or two, what is there in Homesh Pandey, all the things. They are, it should be connected, okay, but it does not mean that all of them are connected to each other, this means what is ours, nor what we should have, nor as much as one point of mine, which I understand, if there are vortices, then the total can increase, so how much fiber is there 245 here. If there is total fire, then that condition should be met. Minimum number of our apps should be there in Spain and Italy. It is okay but all should be connected to each other, it is not that you will print a note to anyone, this should not happen, so here we are. If we connect like this finally, today we will see, if you quarter finalize all the points here, then you will finally get this, if the minimum is ok, then you will get that, then you will do all these eight things, right? 54372 plus 7 plus fourth 1111 plus 91. What are you going to get Twenty, 2010 is also the answer, so how will we fine which note to connect with whom so that we get minimum cost, how will we point it, let's see, so what will we do here, take one, take a video. Okay, what will we do here, let's take a special one, so let's go, you are not able to write here, the plate is 202 match words, listen here, what will you take from the experts, that the size of the song taken here is as much as your notes were kept from the point. That's okay here taken 0435 so how much is it 021 3404 but it becomes five see this will be our rice business tab okay this is the thing that what we are seeing pause is it an auditor or not And already withdrawal, so we will not see it, we will take another note point, okay and we will take one more here, what will it do or all these points of connection, whatever we see, we will see where the minimum cost is coming from, okay, check it thoroughly. The points that we are connecting, where is the minimum going to be, okay here is its size, we will take five according to the points, two three four, this phone is done, get the inheritance done. You need fiber, what will it do, your minimum post will be visible, what will it do, minimum cost will be visible, okay then this point which should be 1234, this is actually this point, understand that we assume that this is our point, this is the first point on the map, this is my second point. This is what is mine, this is my point, okay, now we will solve this problem like this, we will see that zero is which one can we connect to, okay which one can we connect to which ever we will connect, right? Everything should not be deleted. Okay, what should be the person with whom you will connect? You should not have visited before and you should not connect yourself to yourself. Also keep in mind that you should connect the link to yourself and collect points. We will do that, it should not be a toilet day visit, okay, then we will connect, then after the connect, we will see that the next point that we connect to will be our next point, also keep in mind to whom that point will be connected, okay, so here. What you have to keep in mind is that the current point is yours, OK, then what is the next point that is going to be made, which point is going to be made again, will it be a CAN point, if there will be a next point for it, then how will we connect which one, which will be easy, but not easy. For this to be minimum, take care of the current nodal point, take care of this for the next point, understood all this is done for the next point, this is done for this point, and here we will take one more and this force will be seen to bend, then the minimum will be in this post. How much has been done till now, okay finally minimum 5, how much has been done, keep that in mind and there will be one answer in which you will finally know the cost of all, finally the minimum cost will be this, okay this is done, Yagya is done, then what do you do here, can't your irrigation. I will be cumin okay what will you do shameless you will reduce it to zero and drowned then what will you do which is minimum Equestria na first let us take it infinitive that in the beginning it is going to be your infinity okay its value we are going to take infinitive and half and a half is still unmarried If it is then mark it as it is, what to do 20, please forgive the time, okay then now the first one which we will be here, the first one is this one with zero point which takes this one, then by itself here this one is of this zero point, now which one will it be connected to? We will see that now Kent is my zero, what will we do with it, we will also set the mark on it, first we will add mark visit, after that what will we do, now we will see for this brave, with whom it can be connected, okay, it can be connected with this. So first what we will do is set this visit is right its not happy with itself na can point see our right here front part of yours it is at zero so can points on that so check it yourself it ca n't be connected and this If you hit 'Visit' then it is 'Visit' so we will hit 'Visit' then it is 'Visit' so we will hit 'Visit' then it is 'Visit' so we will not change it. Now let's see what is the cost between these two. When you point them to the cost, Tools - Tools - Tools - 02904, then the folder that will come out, you will say yes till now. Okay, now this is a phone, so what will we do on this lineage, now we will update it that look now this is your one point, the distance that has come till now, this is the fold that this food has been prepared here, next point from which. Connect is from one, see now I am not finalized because I have collected from, we are just assuming that here is the next point, our one has become and the current judge is yours too, it is fine, then this is the minimum post till now. Till now I have not got the minimum pose, I have got it, so far it is ok, then what will you do, for this you will look at this Jio to see if it will connect to you, then how many times will it connect, what will be the distance when both of them Look, don't disturb, it will come out to be 330, okay, look here, it is neither from you nor from these creatives, so what is this lack, nor is this less, so we will chutney it, but whatever is the minimum, even your food has been found free. What is your minimum off call so far? If we have received the phone then will we connect or not because the forces are more than thirteen, if we will not connect then the next point will still be ours. Descendant, we will keep it connected and then we will quote it. Triyugati will check whether it is connected to Shri or not for 10th class. Collector will see that it has become 527, then what is it, neither is it inflated, nor is it less, nor is it effective, will it be consumed, will it be reduced again, will it be minimum? Whatever is there, do we connect at this convention, is it on its distance, is it less or not, is it not less than this, for if it is less, then the next point is that till now our one is going to remain the same or will we keep connecting 108 or this is the minimum we have got till now. Then you will check for this, then you will check for this for a while, then you will get four clips that here also there is seven, so be careful with that, then we will update it because seventh is missing from for infinity var, neither this distance nor seven yet. Then we will compare it, is this my office, is it less, is it not less, what does it mean that zero is connected to name one, which is this, which is I am tutu coordinator, connect this to this. This is our phone, right, this phone is gone, when the phone is gone, then the final answer is, what will we do, will we add the phone is there, now it is connected to one, then what to do next, connect it to your vansh tha, what will we do to the trend next? Will update that current update ok now friend who is my one ok ca n't is one neck nothing will happen from here what will this be your one means the current has become pure what will you do you will check everyone for this Do n't check the previous one because the video is already complete, then for this you will check from the next one, if it is there, then you will get this minimum. Okay, what will we do for this then we have come to the forest, the current has become my forest, so please kill the forest. Two visits that your visit has been done right video is done now what will one do it will check with all its next ones that it will make connection with whoever is unethical will make connection together and saw what will be the minimum cost ok this is minimum again it will go From here ok this will be mixed and will also be intact. Here the friend will also be updated. Ok the friend will also be updated. Minimum Appointments will go again and this is the next point which we are checking. We will put this from here and now we will start from one. We will check this, to whom will we connect the one? Ok one, when we will connect it, we will see the tension on the other side of your 3410, no, the one that came out here, 3 - two one and can - 281 plus - two one and can - 281 plus - two one and can - 281 plus 1981 is less than 1981 Noida, isn't it thirteen? Please update it so that you can see that this is the minimum cost till now for the connection to the service, so I will grate it here and what will we do here, also come text this, okay, update is for watching, from here, note, then this will be Minimum nine will be updated here ok no will be updated and the next point will be broken here that the next point is now you have become ok what will we do after that then we will check it of one and we will check it then take out the engine and distance so Kitna Niklega Fire - Kitna Niklega Fire - Kitna Niklega Fire - 2312 - Two Kitna Niklega Katherine Niklega 2312 - Two Kitna Niklega Katherine Niklega 2312 - Two Kitna Niklega Katherine Niklega Okay then it will come out so let's go here Three is less than the complete raw seven so here what we will do next is we will update and compare this too so it is less than three then thing If it is less than then update the second one and this will be three of the next point because on three it is exactly on the point then we will do okay then here we will check it seven of one from zero so seven - 250 and 5 - from zero so seven - 250 and 5 - from zero so seven - 250 and 5 - what will this be seven will be that This will be seven, right? 7 - 252 - 0. The arrangement will be one. Finally, let it remain 2004, - 252 - 0. The arrangement will be one. Finally, let it remain 2004, - 252 - 0. The arrangement will be one. Finally, let it remain 2004, but it is not less than three. If it is not less than one thing, then this three will be my minimum till now. Then what will we do? We will add it in the answer. Finally. Because we have seen all the points, we can see all the points for one, okay, we will make eight and along with making eight, what we will do is remove it from here and do it in the cant, friend, now my three is done, what should be the front? Gya mine is free ok after that it is free it is 3 these three ok now what will it do to Mr. What will it do march will visit and like will do sorry visit will do ok participate has done now what will it do will check For all the points, if this point is lasered then it is special, this visit will be done for this point, this visit is about this point, this is not a visit, for this it will be seen free and after hitting the distance of these two, we will remove so much fire - Chhotu and 210 fire - Chhotu and 210 fire - Chhotu and 210 Miles 282 will come out right ten come out but here two which is nine is right is this yours this is nine so when it is nine then what is this nine what will it do what will no to no here is there a train no train what is ghee updated this It will not work, okay, so what is going to happen to you, which will not update the minimum cost and what will it do, will take the name from here, TAN and we will compare from Noida, what is the minimum of both, you can find the distance. And take out time, write up, find out the distance, here you will find out the distance of both, the train is leaving, your distance train is not going and its cost, we already know the minimum cost till now which was fine, the previous one, this one was leaving, so out of the two Which is the minimum? If the minimum of the two is nine, then here we will take the minimum of nine. Okay, we will not take the train, we will take nine and take 9 inches. Okay, after that the next point will be ours. It will be two. The next point will be updated here. Okay, it will be tubeless. Then what will happen if there is no tow visit then it will happen then for this we will see foreplay on this point three, we will not see for ourselves but for Swift, when we calculate how much distance will come out, Fire Minor 720 will be done, this call will be done so that is it If it was less than this then it will do four here and will update it will connect to the phone right then we will connect again then finally what will we do here we will take out the fod, I spoke and typed then for will do art. What will we do after doing this? Okay, after breaking it into pieces, then what will you do? Darkness, then what will we do? Next point is ours, it will be removed and ours will be updated in the cant. Next nine is more correct. After updating, we will remove it and update it. This time we will remove it and updated it, in the next point we will update it to current, the front part is done, our after food will check for 11, it is alerted, it is also already a visitor and along with the photo, you can kill it also, it is possible that That's why you update your friend and then edit it at the same time. What will we do? We will weight it also, now we will add it, after that we will check all the points, this is a visit, if it is not there, then it is not there. Seven will calculate the distance - Sharif and is not there. Seven will calculate the distance - Sharif and is not there. Seven will calculate the distance - Sharif and for 1031 but who is there when in forty nine no less is fati no dues one photo came out but this is our no less so will take only no and here is the update of nine district or minimum the next point is that of being add nine What will we do next? Which one will be there? To go to have taken. Uge to have taken. This is ours. Now what will we do here? Finally, now there is no one who has not been printed. Many have been deleted. So many will make it 98 here. You will update the Twitter account here that it is ok from 272, this minimum will be removed. 2 When you check and you will see the whole story, you will then beat yourself up, ok then you will check and you will see that the whole twist is there, then it is ours, so finally today we The answer has been added which is the final answer which we are going to return then how much is it 437 fourth what happened pa 1111 80 this is yours ok so you got this is what we meant that we take two a's one The point which is between the points of connection to the minimum cost for a visit. What is the minimum that can be taken? Hey, then what did we do at once? Correct note: then what did we do at once? Correct note: then what did we do at once? Correct note: Who is the encounter mala or from whom we are watching everyone? That point is one. The next point is that finally the candidate to whom we are connecting that point. If those points are Mawa N, the next point is that it is our check that to whom we will connect the PAN. Okay, then it will be ours or that it will be ours. Will become a friend and then that cancer will see itself. Which man can be possible? The one with the minimum distance will be our next point. Okay, so this is what we are seeing. Along with this, the answer is what do we do, which is the minimum time, finally. If we are getting it then we are going to add it, so how will we code it, let's see OK, now how will we do this circular, we will see that, first we will see how we will fine the distance, add the distance, how will you point it, then for that, their Will do concrete together is wrong inter that distance from ok sitting here take factor in test so what will you do here point one and under there is a factor * is a factor * is a factor * Hey what will this be point how to oak a new went then what will you do here But this is the distance, how will we point 2 Here, am I all this, otherwise I will return this element like this point, this lineage 104 - This point up to 104 - This point up to 104 - This point up to opposition, we will take out Aplus that we will do ABS of garlic, copy this. Let's do it, I will be on one take, give one and this will find out this distance and you will find out the distance, then what will we do here, first what do you do, how much will we add till how many sides, do this in front and we will find. Whatever size the points would have been, it is okay, this is done, you have done this, what should I do after that, will you respect me, you will be respected by me, the internet has eyes and it will be valley school me kya wazir hoga, okay then you use 120 one person and the side is that Shiv here Batter Om asks Bigg Boss what will be the resistance vectors now inches, now we select four minimums, we call them cost effective size and ours that in the validation of all, we will get till, take internet here, okay then we What do we do in these tents toilet friend points cost 120 ok and the main course which is ours but what do we do at 90, what do we take here, what do we have to do after that, we have to check for one point, right one point The club has to check what is possible for this, so what we will do here is that we are also adding the answer of an important file, we will cancel it here, in this you are finally waiting for the minimum pass to be given. Then what will you do here? What will you do here? As long as this viral cant point is your Ganjeer, what will you do? Set its log. Then what will you do here? We will mark the cant point as visited. Scan the point which is ours, what has happened to it? The video is done, okay so what has been deleted, let's do one, what will we do after that, now what can be the next point of the can point, let's not even take that next point here, that is my proof, we are the ones, okay Right now I don't know whether we have to do that point and what is the minimum cost till now. The minimum till now has come out to be that of the deceased. I don't even know that right now. What will we do initially? Will we take Inter Max or Internet? Then what will we do? We were checking one point for Cantt. Right, what will we do if we check the point? What will you do? You will follow from here, internet pointer will start from 90, you will check all the points. We were saving one point here. We have checked all the points, the size of our food points is there, so what do we do here, point lesson and okay points A plus, this point, let's keep the size there and attack, we will do a check here, so first check everything. Is the visited one seeing the point jong late in the visit, is he a visit? If the visit will not change his claim and also will not check for cant points, if the point note is 10.1 then if the point note is 10.1 then if the point note is 10.1 then we will check for that, anger is not anger, it is to be collected. Therefore, we will see this point and will continue, we do not have to do any operation here, otherwise we have to wait, first we have to remind for that point which is the minimum cost. Hmm, I was updating, the point of minimum cost could have been the minimum. What we used to do was the minimum distance of the for that point, the distance between that point for the can point, which was already placed on that point. If we compare both of them, then see the minimum of both here. Shukrameh No Ladies was in minimum cost but we were calling for a distance. Okay, give the distance of existence and we will compare it with what is already at this point. Which is the minimum among the two? So what will you do here? Minimum people are here so distance. What will be the distance, here one will be your account point, okay, one will be your account point and one will be yours, come here, the effect point, current points, after all the points, Tamil batter dena, come here, this point is the paint point of cant, which Points and this point to Rewa's point is given in its can point and e that what we have to do here is to find the point from where we have to call and join from this point, that is my friend point, that point both. The distance between and already that sad image is given at that point, it is fine, already in that address which is given by us, the cost at that point, he should computerize both of them so that we get the minimum, what about us? Will update this page, at that point I have stored them, after that what we will do is compare, then that me cost a pointer is the Lansdowne minimum current, it had to be updated all the time, so we will compare it, is it less, how is it? If it is less then what will we do? We will update my minimum current by doing the minimum. I will do this by adding A to the mean cost point or what will you do if we are getting the minimum cost at that point then what will we do with that point next. If you make a point then tell me that I will cut the next point and make that point. See here, we were updating the next point and recording the point for which we were getting the minimum at the same time for which I was getting the minimum. Complain on that point was nice, what will we do on the next point, if we update it here, then we have updated it, then after updating this, when it will finally take this one point, current point, take all the points, when it will check, then finally If a minimum has been found then finally if the minimum has been found then what will we be doing for that minimum? What will we do? We will be adding to the answer. Okay, we will be muting the answer. First of all we will check that the minimum current which we have got is yours. There is no inch max. Okay, there is no inter mexico, there is intex, so the answer is, what will you do, if you add zero then it is otherwise, if you have not found your interest in the religious book, then what will you do in that condition, which is your mind current, which has been found till the minimum. You will add it to this, okay, it has been added and along with that, what you have to do is to update the cant point also, current, so how to update it, which you next point five, this right, this is connecting to which it is connecting. What do we do with that? We are adding it here. OK, we have added the hunter here, what we will do here, we will answer it completely, finally OK, District Biography and Visit, Can Point, Can Visit here, OK. Due to what is in the container, 1GB was kept but point by point, what will we do, update this video, like what we would do here, like we would update it and update it, like what we would do, if you visit it, then it will be given here. But as soon as it is updated, then here these people will say that this will complete the line, it will visit you, it will be the cant point here and Puran says that gates line number five Mehta left it, sorry, it was 101 eyeliner, then acupressure point. Bluetooth is useful in life, it is a waste of time, it's okay, it's time to give up your life, thank you.
|
Min Cost to Connect All Points
|
average-salary-excluding-the-minimum-and-maximum-salary
|
You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the minimum cost to make all points connected._ All points are connected if there is **exactly one** simple path between any two points.
**Example 1:**
**Input:** points = \[\[0,0\],\[2,2\],\[3,10\],\[5,2\],\[7,0\]\]
**Output:** 20
**Explanation:**
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
**Example 2:**
**Input:** points = \[\[3,12\],\[-2,5\],\[-4,1\]\]
**Output:** 18
**Constraints:**
* `1 <= points.length <= 1000`
* `-106 <= xi, yi <= 106`
* All pairs `(xi, yi)` are distinct.
|
Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2.
|
Array,Sorting
|
Easy
| null |
1,745 |
hey what's up guys this is john here so this time 1745 palindrome partition number four um so this is a very straightforward problem so basically you're given like a string as and your task is just to check if this current string can be partitioned can be split into three non-empty into three non-empty into three non-empty palindromic substrings otherwise return false right so i think everyone knows what is a the palindrome string is right so for example the first one right we have a b c d b we have a b c b d so it really returns true because uh we have a is a it's a palindrome and then bcb's are also palindrome d and d is also patent drum and the last one is false right because then the second one is false because there's no way we can split uh the string into two into three parts and the uh the constraint is selected so uh the length is two 2000 so which means that we can easily solve this problem with a n square time complexity right so to solve this kind of like split right split into three parts you know a common strategy is we always fix uh one part and then we'll try to iterate brutal force the rest two parts so for this problem you know the essence it has to be us a split right so which means that we can simply just try to we simply try to uh fix the first uh string the first split uh basically we try each of the strings right we try first we try to try this one we tried this one until we have tried everything until this place because we need at least uh two remaining uh letters right for the second and the third substring and for each of this first string here right we just need to check if the first part is a palindrome or not if it's not a pattern drum we simply just uh skip that we continue doing that and if the if this current one for example if this one is a palindrome right and then we just enumerate the remaining parts with brutal force the remaining parts we try to split these remaining parts into uh into two parts right similarly like the first one we fix this one as a second one and then this one and the third one right so on and so forth until we have reached the uh this one so and this is going to be a of n square uh time complexity to loop through the all the uh the combinations so which means that we need to uh check if a substring is a palindrome uh in of in one time so which means that we need to pre-process pre-process pre-process uh all the substrings to check beforehand to check if others each substance string is a palindrome or not right and to do that it's setting a very classic palindrome dp problem right so let's do this we have a length of s and then we have dp so the dp we store the uh the flag right for each of the substrings and then we have a length of n for this one in range n so to enumerate all the substrings you know there are two ways you know the first one is that the outer loop is the length of the substring and then we have a range of in range of l dot and plus one right that's the total length and the inner loop is the starting point of the substring in range of uh we have n minus l plus one that's how we uh set the range for the starting point and the ending point which is j will be the i plus l minus one so i mean you can draw a few examples and then it should be pretty easy to get this formula here and then for the dp i j right so the dpij stores the uh it means that from i to j uh the substring from i to j if that string is a palindrome or not so this value is going to be what so first we check if the x i is equal to the sj actually no i'll write this one first so first we need the precon the prerequisite for the dp ij to be a true has to be that i and the j s i and x j has to be the same right if this one is true right and then we just need to check if that the dpi and j will be what or equals to uh if the i minus j minus i smaller than 2 or the dp i plus 1 j minus 1 is true and then if either of these conditions are 2 and then dpi i j is true all right so this one is like for the k for the one and two lighter case so obviously a is a palindrome and a is also a palindrome right so that's we that's this first condition and the second one is the let's say if the a and a are the same and then if this one if the starting point and ending points are the same then all we need to know if the remaining part if this part is a palindrome and then plus this 2 8 on each side it's also going to be a palindrome that's why we have used these two conditions to populate the dp inj i mean like i said you know you all you can always just simply do a loop on top of the uh instead of doing the length here you can just always do another loop right so you can do a for i in range you simply loop through the starting and ending point uh so now we have a we're starting from the end right and then for j in range of uh i to n so and then you can simply do this i mean either of these two works it's just your own preference i sometimes i prefer this one sometimes i prefer second one it doesn't really matter i think there still works you know so now since we have the dps we just need to loop through the first part right we stop at n minus 2 because we need the at least two letters for the second and third substring basically if the dp uh zero to i right because the first string starting always starting from zero and if the first part is a palindrome then we loop through the second and third parts so for j in range uh we start from i plus one and then we stop at n minus one because this is the second one right and then if the second one the third one are both palindrome right i plus one two j right and dp j plus one and two the last one is n minus one if they're both palindrome then we simply return true otherwise just return fast yeah i think that's it so run the code oh this is a one yeah okay yeah so it passed right so for the time complexity right so this search so n square right because we have two uh nasty for loops yeah this one here yeah i think that's it right i mean it's just like a little bit of variation of the palindrome on top of dp here i mean as long as you can realize that you know you just need to pre-process the dp pre-process the dp pre-process the dp for each of the uh the substrings and then the rest is just like brutal force right all the possibilities of the all those three substrings and then you just need to get you can just uh easily get the answer along the way cool i think i would stop here for this problem and thank you for watching this video guys stay tuned see you guys soon bye
|
Palindrome Partitioning IV
|
find-nearest-right-node-in-binary-tree
|
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.
A string is said to be palindrome if it the same string when reversed.
**Example 1:**
**Input:** s = "abcbdd "
**Output:** true
**Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes.
**Example 2:**
**Input:** s = "bcbddxy "
**Output:** false
**Explanation:** s cannot be split into 3 palindromes.
**Constraints:**
* `3 <= s.length <= 2000`
* `s` consists only of lowercase English letters.
|
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
|
Tree,Breadth-First Search,Binary Tree
|
Medium
| null |
1,636 |
hey guys welcome to a new video in today's video we're going to look at the lead code problem and the problem's name is short array by increasing frequency so in this question we're given an array which contains integers and we need to sort the output array based on the increasing order of the frequency of the elements since 3 appears only once that should be the first element the second most repeated element in the array is 1 so the two ones appear next so those three twos appear in the end in this case one appears once so that should be the first element two appears twice and also three appears twice so according to the question if multiple values have the same frequency sort them in decreasing order so 3 should appear first so 3 is appearing twice and then 2 is appearing twice coming to the function we are given a function frequency sort and then an integer array nums as a parameter and the return type is an integer array so we need to return an integer arrow so our approach to this problem is going to be that we are going to store the frequency of elements inside a map which will contain integers of the key and also integers of the value the keys are going to be the elements of the array the values are going to be the frequency of that element in that then we're going to create a list so the list will contain the keys in the map then we're going to sort that list according to the conditions given while sorting the list i'm going to write a comparator method where i'm going to compare two objects of the array because in the list of integers the integers are stored in the form of objects so i'm going to compare the two objects according to the condition we'll show you during coding how i'm going to write the code for the comparator then finally when we have the list according to the sorted order we need to convert that list into a ra after converting that list to an rf we'll finally return that array as the output coming to the first step i'm going to create the map let's add the elements into the map for that i'm going to iterate through the input string nums from left to right now to add elements into the map first we are going to check if that array element is present inside the map dot contains key nums of i so if that element is present as key inside the map we're going to increment the frequency of that key so i will put key we are going to put the array element the value is going to be the frequency of that error element plus one so map dot get off num so five plus one and in the else block which means that key is not present inside the map so we're going to add that element into the map and add frequency as one so this line in the else block will be executed for each unique element and from the next time whenever you find that element inside the map we're going to increment its frequency by one so this is a standard way of adding elements into the map storing the frequency of that element as its value now the second step is to make a list and store the keys inside the map inside the list so list the keys are integers right there so the list also will have integers to add the keys inside the map into the list i'm going to use the keysight method on the map now let's start this list for sorting i'm going to use collections.sort i'm going to use collections.sort i'm going to use collections.sort and the collection here is list right so this is how we generally sort a list but we have to specify two conditions here that if multiple values have the same frequency sort them in deciding order now as i've already mentioned the integers here inside the list are stored as objects so i am going to create two objects which are integers a comma b then i am going to create my own way of sorting those two objects for that i am going to define them now inside this comparator i am going to specify the conditions if multiple values have the same frequency so if a and b repeat twice for example then b should appear first that i am going to write it inside a code so if map dot get of a the frequency of a is equal to mark dot get of b the frequency of b so if both a and b are having the same frequency sort them in decreasing order so b should appear first and then a so that is what i'm going to return b and then a so b should appear first and then a under the else block which means that the frequency of a is not equal to b so if the frequency of a is not equal to b i am going to return the frequency of a and then the frequency of b so return map dot get off a then map dot get us b so this is how you can use a comparator to define your own way of sorting the list now that we have the list sorted according to us we need to return an integer array right so let's convert the list into an array so i'm going to name the area as result so the size of the result array you can use the numsaris length so nums.length now let's iterate through the list using a for each loop for in num list note that the list has keys inside it if our task was to only return the keys we could directly return num here but we need to return with its frequency like how many times it has been repeating for that i am going to use a for loop to find out how many times that particular key is repeating so for print i equal to 0 i is less than mat dot get of num i'll explain the logic here so map dot get of num is here whatever is inside the list map dot get off that num will give us the frequency of that num so that many times you can print that num so inside the result i'm going to store num now i can't use result of i to store number right because we are using i to get the number of times this number has been repeating we need to store the first number inside the zeroth index inside the num so for that let us use another variable outside i'll name it index initialize it to 0 result of index so result of 0 is equal to num and for the next iteration index should also increment so index plus so result of index plus is equal to num so this forage loop will happen for all the elements present inside the list and then we're going to get the resultant array finally you can print out the resultant as a result as the output let's run the code there you have it we're getting the expected output let's submit the code yes our solution has been accepted so let's take this example and see the output is formed so we are given this array one two three we have to convert it into array three one two because it is sorted on the frequency of each element so to first start off with we are going to build the map the key is going to be the array element so to form the map we are going to iterate through the nums array from left to right it will take the first element and it will calculate its value for the corresponding unique elements one value will be inserted and next time they appear the values will be incremented and finally at the end of the loop we get this map now we have the values as the frequency of each array element from this map let us calculate the list which will be a list of keys inside the map so the keys here 1 2 3 will be present inside the list and now we are going to sort the list according to this comparator if two array elements have the same frequency it will first return the greater element and then return the smaller element but in this case no two elements have the same frequency so this will be ignored and the normal sorting will happen so the sorting will happen based on the frequency of the lower element first and then the frequency of the greater element now we have the sorted list 3 1 2 but that can't be returned as the output we have to get the frequency of these elements and then print it those many number of times so first we are going to iterate through the sorted list we will take the first element here so the first element in this array is 3 so it will get the frequency of three so the frequency of three is one three will be printed once in the output it will go on to the next element it will get the frequency of one is equal to two so one will be printed two times the next element is two will get the frequency of two is three inside the map so two will be printed three times as output so here as you can see this is the output that's it guys that's the end of the program thank you for watching and i'll see you in the next one
|
Sort Array by Increasing Frequency
|
number-of-substrings-with-only-1s
|
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
**Example 2:**
**Input:** nums = \[2,3,1,3,2\]
**Output:** \[1,3,3,2,2\]
**Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
**Example 3:**
**Input:** nums = \[-1,1,-6,4,5,-6,1,4,1\]
**Output:** \[5,-1,4,4,-6,-6,1,1,1\]
**Constraints:**
* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`
|
Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.
|
Math,String
|
Medium
|
1885,2186
|
1,577 |
uh hey everybody this is larry this is me going over q2 of the weekly contest 205 number of ways where square is equal to the prime of two numbers so this one should have been so easy and it was surprisingly easy i think for me it was just about reading the forms uh and also just feel like reason recently the contests have been a little bit trickier so i've been just maybe watching out a little bit uh so this took me about three minutes to do during the contest but basically just uh roughly speaking it's a very common technique just using a lookup table right so basically i'm put first on under i and the j or in this case i uh sorry you put first in the j and the k and then you just uh hash the eyes or you could do it the other way around it doesn't really matter because whichever way you do it's going to be n square um except whatever you do this way it could be only off and space versus of n square space but yeah but basically that's how i did it um and also you have to make sure that you did it in both direction uh numbers one and number two swap so i did this shorthand to kind of make it easier to program but basically for each number that's in a we hash the oh and we incremented to keep track uh the square of that number and then we just put first i j so that you know we sum up the number of count that has that number in the original array and again we do it twice uh in one in each direction and that's pretty much how i solve this it's relatively brute force and if you are unfamiliar with this you really should because it comes up a lot given in the code as you're practicing so let me know what you think uh this is gonna be n square time because of these two for loops and space because of this counter but yeah uh let me know what you think hit the like button hit the subscribe button and you can watch me solve it live next that was a slow one hmm you um that's annoying um uh hey everybody uh yeah thanks for watching uh this explanation of this video definitely give me feedback uh ask questions uh because the more questions you ask the more feedback you give me then it lets me know what how you know what kind of answer to uh give you for next problems right and so you know i'm trying to learn from this so yeah hit the like button to subscribe and join me in discord and i will see y'all next contest bye
|
Number of Ways Where Square of Number Is Equal to Product of Two Numbers
|
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
|
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105`
|
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ?
|
Math,Dynamic Programming,Backtracking,Combinatorics,Probability and Statistics
|
Hard
| null |
540 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem single element in a sorted array we're given a sorted array of integers maybe like this one over here there will be two copies of every number in the array except for one of them and that's the one that we want to return so there's going to be two ones two threes two fours but there's a single two and that's the value that we want to return it's pretty easy but the catch here is that we want to do this in log n time and constant space are there any algorithms that you know that would satisfy this well I can think of one and it is binary search but it's not going to be as straightforward as a typical binary search but let's try to make some key observations that can get us to the optimal solution the idea behind binary search is that we have a left pointer and a right pointer and this besides our search space initially we have no idea where that Target element could be so we have to search the entire array but we'd like to be able to eliminate half of the array every iteration of like our Loop so maybe we would look at this element is this the target element well how do we know if 3 is the target element or not well because our array is sorted conveniently for us it's really easy in constant time we can look at any element and determine whether it's the Target or not that's by looking at the left neighbor and looking at the right neighbor because we know for the Target element when we look at the left neighbor it's going to be different than the target element and when we look at the right neighbor it's going to be different than the target element but for every other element in the array that's not the case for three but both of its neighbors are not different than it for this three both of its neighbors are not different than it for this for both of its neighbors are not different than it so that's easy enough we initialize our mid pointer here we look at the three or both of its neighbors equal to it nope so this is not the answer but how do we know now should we start searching over here or should we start searching over here at first it seems it's impossible for us to know which side to go to but actually there's a clever observation we can make first of all we didn't just eliminate this value there are two copies of it so we also eliminated the second value now it might look a little more obvious and if it's still not obvious which side we should search on let me tell you something if we're given two copies of every single value then let's say the size of our array is 2 times n but we know in addition to the even values there's going to be a single one where there's just a single instance of it so an odd number of times this value will be added or just one time so this is the size of our array it's always going to be odd so which side should we search on you can probably tell me at this point but it's always going to be the side that has an odd number of values so if this side has three values and this side has two values well we know this side is going to contain only duplicates because it's even but we know this side is going to contain the odd value or rather the unique value so that's how we would decide it so continuing our algorithm here I'm going to set the mid pointer over here and let's also eliminate these values from our search space as well so now I'm going to eliminate these values from our search space our mid pointer was over here but now we're going to take our right pointer and shift it over to Mid minus one so it's going to go over here and then we're going to continue the algorithm so the mid pointer now is going to be over here is this the target value well it's not different than both of its neighbors so no it's not and its left neighbor is equal to it so that's also not a part of the search space so now we would set our left pointer to be mid plus 1 over here so if our left pointer is over here now we would look at this guy is it different than its left neighbor yes it's different than its right neighbor yes it's the answer and that's what we're going to return and as you can see this is just a modified binary search so this time complexity is going to be log n and the space complexity we're not using any additional data structures is going to be Big O of n now let's code it up so let's start with initializing our left and right pointers the left pointer is going to be at the beginning of the array while the right pointer is going to be at the end of the array and we're going to keep going while our left pointer has not crossed our right pointer and then the first thing we want to do is compute the Midway point so you can either do left plus right divided by 2 with integer division but believe it or not this actually is a bug most people don't know it and usually it doesn't matter for interviews but the bug is that left plus right can overflow so how can we get the Midway point between the left and right pointers without possibly having these two added together overflowing well to do that we take the difference between write minus left so this gives us kind of half of the size of our search space and we take this value and we add it to the left pointer alternatively we could also subtract it from the right pointer but basically this just says get the left pointer add half of the size of this subarray to the left pointer and that will give us an a Midway Point since we're subtracting these there's no risk that it's going to overflow that's just a minor point about binary search but now let's continue let's first determine if we found our answer or not so how do we do that well we can say if the number at Mid minus 1 is different from the value at the mid index and if the value at the mid index is different from the value on the right side of it then we know we found our answer because it's different than both of its neighbors so we return that mid value one little bug though with this is that what if our index gets out of bounds well for that we can modify this slightly and say before checking this let's check that mid minus one is greater than zero that's one thing we could do but I'm actually going to do the opposite if mid minus 1 is less than zero or if this whole thing this part is true then we know it's not equal to its left neighbor that's what we're trying to determine here so if mid minus 1 is out of bounds then of course it's not equal to its left neighbor because it doesn't have a left neighbor and we'll do the same thing over here with the right side if the mid plus 1 is equal to the length of the input array or this is true or it's equal to its right neighbor then we're good so either it doesn't have a right neighbor or it's equal to its right neighbor in that case we know we found our answer so we return it and the benefit of this is that it'll always evaluate the left side first so if mid minus 1 is less than zero it won't even evaluate this side because there's an or in between these if this is true it won't even check the second one because it knows this whole thing will be true but pay attention to how we have the parentheses because it does matter in this case we need this entire thing and this entire thing to be true so now if that's not the case we need to figure out which side of the array has an odd number of values so the easiest thing in my opinion is to just get the size of the left side of the array because we really only need one side of the array if it's odd then we'll search it if it's not then we'll search the other side but how do we get the size well the left side of the array is going to be M minus one if the value at M minus 1 is equal to nums at index M otherwise it's going to be M this is because if these two values are equal then we want the number of values on then we want the number of values to the left of M minus 1. if M minus 1 is 3 for example like it's index three how many values are on the left side of three well the indexes of those values are going to be 0 1 and 2. so there's three values on the left side of the index three so that's how we're getting this and if that's not the case that means that the value at index m is equal to the value at M plus one because we know it's equal to one of its neighbors and in that case we would want all the values to the left of M which is just going to be M so one thing I want to mention here is that what if M minus 1 is out of bounds well in Python that would be negative one zero minus one is going to be negative 1 and python negative one actually does work it will though just look at the last value in the array which will be different for sure because our array is sorted but in most languages you might need to have another check here I'm just mentioning that for the people who don't use Python but using this left size we can and say if the left size modded by 2 evaluates a true meaning there's an odd number of values on the left side then we say right pointer is going to be M minus 1 because now we want to search the left side otherwise we are going to say left pointer is equal to Mid plus 1 because we want to search the right side that's the entire code we don't have to put any return statements out here because we are guaranteed that there's a solution and if there is we're going to return it right over here so now let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Single Element in a Sorted Array
|
single-element-in-a-sorted-array
|
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time and `O(1)` space.
**Example 1:**
**Input:** nums = \[1,1,2,3,3,4,4,8,8\]
**Output:** 2
**Example 2:**
**Input:** nums = \[3,3,7,7,10,11,11\]
**Output:** 10
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 105`
| null |
Array,Binary Search
|
Medium
| null |
724 |
hey guys welcome to a new video in today's video we're going to look at lead code problem so in this question we given an integer AR called nums and we have to calculate the index of this array a index is the index where the sum of all elements strictly to the left of the index is equal to the sum of elements strictly to the right of the index if a index is on the left Edge the left sum is zero and similarly if the index is on the right Edge the right sum is zero and we have to find the leftmost index which means that we have to start an iteration from left to right if there's no such index we have to return minus1 as the output now let's take this example and see how we getting the output as three so this is the input array 1 2 3 4 and five and the index position is three so it says that the elements to the left so these three elements and these two elements sum is same so the sum of this is 1 + 7 + 3 is same so the sum of this is 1 + 7 + 3 is same so the sum of this is 1 + 7 + 3 is equal to 11 and the sum of this is 5 + 6 equal to 11 and the sum of this is 5 + 6 equal to 11 and the sum of this is 5 + 6 is equal to 11 both are same which is at index 3 hence index 3 is the output now let's take the same example and develop our logic so I've taken the same example as example one so we start our iteration from left to right and we have to check for this condition left sum is equal to right sum so instead of calculating two left sums and right sums separately for every index let's find the sum of the entire array so for that let's iterate through the array from left to right we start I is equal to0 until I is equal to here we keep adding all the elements and find the sum so the sum of the entire array is equal to 28 and now let's find this left sum by iterating through the array again from left to right and similarly we can find the right sum so once we have the left sum for a index you can find the right sum so we have the sum of the array we have the left sum for that index by calculating that and we have the right sum so right sum is equal to sum of the entire array minus left sum minus that element's index minus element at that index so we start with i is equal to 0 left sum for that left sum is equal to 0 for the current index and right sum is equal to 28 Minus left sum is 0 and current index is 1 and right sum equal to 28 so for this left sum is equal to zero and right sum from first index to this is equal to 27 each time we check if left sum equal to right sum 0 is not equal to 28 so this is not the index so we move further now I is at one now we calculate the left sum is equal to 1 right sum is equal to 28 Minus left sum is 1 and current element is 7 so 20 so again we check if left sum equal to right sum 1 is not equal to 20 so that is not the index so we move further now I is equal to 2 now we calculate the left sum and right sum again left sum is equal to 1 + 7 that is again left sum is equal to 1 + 7 that is again left sum is equal to 1 + 7 that is 8 and right sum is equal to 28 Minus left sum is 8 and current element is at 3 so right sum is equal to 170 so 8 is not equal to 17 so that is not the index move I to the next iteration now I is at three we calculate left sum is equal to this 1 + 7 + 3 that is 11 and equal to this 1 + 7 + 3 that is 11 and equal to this 1 + 7 + 3 that is 11 and right sum is equal to 28 Minus left sum is 11 minus current element is at six so that is also 11 so we are checking if left sum equal to right sum 11 is equal to 11 so that is the pivate index we are looking for and index is three so we return I so I is three so which is the output now let's Implement these steps in a Java program so this is the function given to us and this is the input array nums and the return type is an integer I declared a variable sum which is initially zero representing the sum of the array I'm using a for Loop to iterate from the starting index till the end of the array so if input is equal to 1 so this is the input I'm iterating through the entire array I'm calculating sum so sum is equal to 28 and now I'm creating a variable left sum again I'm iterating through the input array from left to right and I'm checking this condition for calculating the left sum that if left sum is equal to right sum so this is right sum so instead of calculating right sum again we can use the total sum minus left sum minus current element so that will give you the element sum of elements strictly to the right of that current index if this condition satisfies we return I else we add the left sum so this will happen for all the elements inside the array and finally if we find the pivate index I will be returned as the output else we return minus one as the output so the time complexity of this approach is O of n where n is the length of the input R in nums and the space complexity is O of one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
|
Find Pivot Index
|
find-pivot-index
|
Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
|
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
|
Array,Prefix Sum
|
Easy
|
560,2102,2369
|
344 |
start this question is flown from pointers ok sudhir basic question which causes of artwork has been kept hospital subscribe to tomorrow morning first made using a stir work which will not difficult net life in the UK end users can show you are we are S Pi Three Par Hot S.No's Special Permission To Android Based Ones Scene Acid Now I Will Not Be Doing This Should Sita Va B-2 How One Is The Length Of The Giver B-2 How One Is The Length Of The Giver B-2 How One Is The Length Of The Giver Subscribe Now To Three Look Give from here one by two is also like water in chemicals in danger not the decimal so what does it comes to its lower limit apne dentist is 3 so what will we do one to 16 b which is 6 to Edison okay this What will one do to subscribe to that if you do then what to do first of all I have to sign s dot price pay now intelligible to that if not needed ok what should I do for sleep came 20 ok aa mission in ubuntu ok both these wallets dyed Yes ok no this is simple ok so what to do we have a plate here ok and this is the question ok so here we have temple run ok my a wait now its eye no what is it putting ok it is in the team so Now what we have to do is to put one in its i that in i its in - put one in its i that in i its in - put one in its i that in i its in - i then this would mean school so this is ok what will happen to that now our this is ok its this is so here we come - - The problem of coming in 2K is over and listen I am lost okay and I am Jasbir and Ayurvedic paper after some days I don't have effective to-do Dinu something days I don't have effective to-do Dinu something days I don't have effective to-do Dinu something is a Swiss question, you have to learn to do it okay so here What happened to us at that table is okay, so here it is okay to do like this while on duty.
|
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
|
48 |
all of you are doing fine so today we will discuss lead code problem 48 which is a rotation of an image so uh this in this problem so first we will go through the problem statement then look at these examples and then write our algorithm and at the last implement the solution okay so the problem statement says case we employed by n into n square matrix okay so our task is to rotate the 2d matrix and uh so it says key we don't need to uh take one more 2d array so it's like we it's it should be in place and we can't use the next array okay so how it should be look like so let's say for example one so uh one after rotation of 90 degree clockwise so one will go to this position three will go to this position nine go to three seven position seven go to one position similarly it will look like seven one three nine similarly for two to go to this position which is here six go to eight position which is here eight go to four position which is here and four go to two position which is here so that will be the expected output after for example one similarly for example two five will go to this location yep eleven go to sixteenth position yes sixteen goes to 15 position yes and 15 goes to 5 position and similarly for other nodes also so yeah so let's start this is a square matrix of 5 by 5 so this is how our algorithm says so first goes to this position second last goes to this position this node goes to this position and this node goes to this position this is for the first node for the second node second one goes to this position this node goes to this position and similarly this node goes to this position suddenly third node and so on okay so uh let's consider the direction as well so this direction will consider as j and we will consider i as this direction and we are assuming this is area of a of iz of length and into n okay so uh in this one so the one thing to note is uh we start with this node for the outer loop and we will end up here and not at the last one the reason is uh for the first note we start with the first note and manipulate the last note and uh if we end up at the last round consider the last note in this case uh suppose this value is one so we move to one to here and if we consider the last one as one so we move these two there so similarly uh multiple mother two rotation will take place for the first node so that's why we will consider for last to previous mode okay so we will split our matrix in away key first create some subtracting a sub squares yep so in first loop we will consider the outer scale then the second then the third and similarly okay cool so uh let's see how it goes okay so we uh i'm just considering george is quite easy so we'll go with zero one so how zero one will look like a of zero i zero j is 1 how this will goes this will go to a this node the j is n minus 1 and i is 1 i goes to 1 j goes to n minus 1 yep and for a of 1 yep now we are considering this not n minus 1 so this node goes to this node here the j is n minus 2 and i is your n minus 1 a of n minus 1 and n minus 2 okay so for this node we move to this node which is here i is equal to n minus 2 j 0 a of n minus 1 to n minus 2 okay this will go to a of n minus 2 j is 0 similarly for the last one which is a of n minus 2 to 0 okay this will goes to a of zero and one yep this is how we complete this node similarly this node and so okay so how algorithm will look like so if you examine one thing so here we start with this one we move in this direction here i same okay so let's evaluate our program so a of i and j okay so here i is same here j is same okay so i zero will go to n minus one i if i is equal to one i is one it consider the second row which is n minus two so similarly if i generalize away it's like a of now in this direction if i is fixed here the j is 6 what should be j is n minus 1 because for 0 it's last row and rest for 1 n minus 1 for 2 n minus 2 so similarly n minus 1 minus i so this is a generalized way of writing the nodes okay so how i will change for i is equal to 0 j0 for i1 j1 i2 j2 i3 j3 yep so i is replaced by g yep this is how our first node will look like okay so how the second node will look like so uh this is the same function okay so let's say if this was of and x y okay so here's x here if you see in this direction uh how the how x behaves x goes incremental and j goes the same y goes the same so if y goes the same so here uh i goes the same which is x so uh here if y equal n minus 1 here x is n minus 1 if y is n minus 2 x is n minus 2 so it says k here y is the same as x similarly if you consider as y how x goes so x increase x is 0 here n minus 1 x is 1 n minus 2 x is 3 n minus 3 is the same behavior n minus 1 minus x okay so if you compare these two formula both are same so uh similarly all the formula is same so what we do so we will generalize our node by this formula itself so let's say we get the formula for first node we start writing the formula for other nodes also okay so how the what would the second node is j n minus one minus i yep okay so if you this one for the second one okay so this was a x axis z so uh how x was written is n minus 1 minus so n minus 1 minus j okay and this is our y and it was same as y so this is n minus 1 minus i yep so this is our second row okay so how our third row will look like third position not row thread position it's good to call it a position okay the third position is uh similarly if yeah this is the starting number of third question a of n minus 1 minus i n minus 1 minus j okay this will go to how this will go to so yes uh so this will if we look at this formula which is the same so e of y is x is equal to a then it is a of n minus 1 minus j okay and how this x goes to n minus 1 minus x what's x here x is n minus 1 minus i okay so if i open this formula it will be something like a of n minus 1 minus sorry can i move this okay are you light in next line it's n minus 1 minus j of n minus 1 minus n plus 1 plus i yeah if we uh so minus n goes to minus n and plus n cancels minus one and plus one cancels so this is our third position so fourth position will be is for position is a of n minus 1 minus j and i so if you remember for position the first person itself which is a 5j a of i and j okay so uh we will start from 0 to n minus considering n minus 2 we will not consider n minus 1 last node we will not consider if we go to i equal to 1 then we will not consider this one because this is already rotated we will consider from this one so for i is equal to 1 we will consider from this node for i 0 to 2 we will consider from this node okay so let's how uh our formula will look like uh so here so just we can write the code now so how the pseudo code look like sorry okay so this algorithm so int started in i equal to zero i less than n i plus okay so for g sorry j should start so for i equal to zero we will start on j zero itself for i equal to one we start from one itself for two we start from two itself yeah j will start from i itself okay and where does j lens j less than n minus 1 will j n minus 1 minus i so it's likely for i 0 we will reach to this node we will consider till this node for il to 1 we will consider till this node so n minus 1 is the last one we will not consider minus i and j plus okay yep so uh a of i j what's a of i z a of i j is a of n minus 1 minus j this node n minus 1 minus j and i so that was that note the fourth position note that moves okay similarly now if i z is overrided we need to store it in temporary location so that it will be used by the last node okay so now second last is this one what's the value of the sorry so yeah this was the third position what there's something happening actually i will write by myself it said n minus 1 minus j of i equal so it was this one this node and a of n minus 1 minus i of a of n minus j n minus 1 minus j what this one okay third node was this itself if n minus 1 minus i of n minus 1 minus j this goes to a of j k of j into n minus 1 minus i yep so what about the last node a of j n minus 1 minus i okay this was afij which is our time variable so this is how our pseudocode will look like let's copy all of this and try to vary so yes so if some basic check in any other matrix root length because we consider this n if n less than equal to 1 if let's say schematics of size 1 we don't need anything if size is not equal it's not a square matrix then we again don't do anything okay now then we start our program okay yep so okay what's a is matrix itself so we write a to matrix itself okay yes so anything else cool so let's run the code for basic test case so this okay j is not initialized by mistake oh this is accepted let's try to submit this code oh i turned 0ms 100 faster oh that's great so thank you guys hope you like this video
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
1,046 |
hello everyone now we are going to do the problem JL 8 code problem of the day and the problem name is last stone weight in this problem uh we have been given an area of size n and each indices value represents a stone value weight of a stone and we are playing again with the stones on each turn we choose the high BS two stones and smash them together suppose the heaviest two stones at the weights X and Y and the result of this message if x is equal to Y both stones are destroyed and if X is not equal to Y the stone a bit X is destroyed and the stone y the weight y has the new word y minus X and at the end of the game there is at most one stone left so we have to return the weight of the last remaining Stone so what we have to do is we have to pick the heaviest two stones and if the size of the both stones are same then they both will get destroyed and as the heaviest the weight of the heaviest Stone will get decreased by the weight of the minimum Stone let us say we have this example we have uh two seven four one eight and one in this the heaviest stones are eight and seven we will pick them and we will smash them and the minimum one will be destroyed and the maximum one will be decreased by the value of minimum one so now 7 will be destroyed we will be having four one and the its value will be decreased by seven so now it's new value will be one now the heaviest two stones are two and four so two will be destroyed and the value of 4 now becomes two four minus two and now we have these remaining Stones now the two heaviest stones are two and one so one will get restored and the value of 2 will get decreased by one so it will become one and this one will get destroyed and we will be remaining with only three one now we will pick these two ones and if the value of uh the two stones we picked are same then they both will get destroyed and we pick one and one they both will get destroyed and the only remaining stone is one so the answer for this is one so uh in each term we have to find the maximum two stones maximum uh weights of two stones so what we can do uh we can use the max shape because the max it contains uh the maximum value at the top so we can easily find the maximum value so what we can do is we can initialize a priority queue and we will push all the elements in the priority queue now we will do this step until the size uh of the writing is greater than one so we will pick the first Max element the maximum will be the top element of the priority queue and the minimum will be uh so these two will maximum among all the elements in the priority queue this will be the maximum and this will be the second maximum so if their difference is greater than zero means they are not of the same weight so what we will do we will calculate the difference because the maximum value will be decreased by the minimum value and we will again put it into priority View and now if the size of the priority queue is still greater than 0 we will return PQ dot at top else we will return 0. now let us run it so this is the answer for in C plus now let us see the Java code so this is the code for Java we have initialized the priority queue now we will put all the elements in the priority queue now we will perform this operation until the size of the practic is greater than 1 we will pick the first Maximum now and the second maximum if uh their difference is greater than 0 means they are not same weight and then we will add the difference in the priority queue and in the end if this there exist mean the size of the priority is greater than zero we will return the top element else we will return 0. submitted so this is the solution thank you for watching
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
50 |
I have one World come back and math Lite amani weigh today of finished Power Of About Love and War Vietnam since the Style and the forest of Death of Superman show that worked on the study or just like you feel me and this is preferred within its rightful owner of the well Mediamart When She can solve Even you have seen the foremost list of massive world threats is if you wanna investor and were about and when we love to find the Capital of which indicates and vinegar Phi Vinamilk scandan Again And The actress expand EVN decimal knof Roma Masters of the week After The Power and gerald Genta problem because the amount to send the power shot and possessive with s and wife is proud make Pharma will be added friends even though many of them have died Before is backup is most people is dealing with ads Road test aggressive and weight loss up that it weather for Perfect present socialist example polished and rate the way that means Again And number from your high school mod wall mountable Tula stand in disgrace pasqual Trying to time to know the way that I'm just let your motor with you that time our music with others from found footage is late you will notify the same ejector Seconds to mars one time She won the street and Ok and What about it responds to you my no number pharmacist nicolaus seefeld Face Women's your the sponge Cake To The Power of any good food is still to time to play to time to do is sorted 35 pendant necklace hotel to time sick yet fastest us make it never ends in the terminals And Take One Fine Day that number the weather in the average is neither one of Eros modern international Vietnam with team take part in the streets were divided by others thank you Now calculate and you know wanna spend the farmer is Present the song for both in value type lactum ucy people with you when We're Super Queen Pearl Awards and time and late Show composition and of its Most wives and time now the format is made It's the weather forecasting methods are official pestis case with stand against other reasons is not a common Sense Tsubasa Nobody is something that you can wear out if you take is number as what to wear your motor every day reverse hand and integrated Em in their in running from our official warner goldhand into garage entries with Right now I read the Bite And can wait out some From The Hero evolved to work out I speak and timeless show is their Animals In The World Is short and well the Wake me up at War for your patience is nice food will have bruised and time will come Just You and flytime Sprite faitai phthalate glad to have to watch and I work with English language in word is our father have We just dance ok now ng finest motorbike five 6 Nike swarming have the world you when you're with straight Hair Battleship Razer Blade stealth and work with antivirus profile when you say and We can say any price Phuong amira back to work and this is forced to support added to your Words for its helped us To The Power of five or you can save your contact us for android Viettel We got's rubik adventurequest results find the words to What the weather in better late show what where the latest bay canifornia needn't have to work with safe to town to work with about you more to Write by itself play Pieces to prepare for war began in the one hour to value your day show with just wanna have the testimony the content or user to their thoughts about it read the text Again this game is and your hands and has a winning CPU and tried to the power of tooth easiest to the power one time to find out and a free market in the most of the format is not supported the world link Japan my love Sweet spot and Combat assault remaining against the first We Heart It supports and her Every time i have is divided about you my house and refined Eco want when you destroy Awards erkenntnis with National weather like a Mission switches ID number and also takes place a Mission to provide enough and apply tadacip alltrim unqualified to wear your cover the way to share What about you I cannot be over some typical tsongkhapa seefeld brother four years ignite rimini It is not box repassword Right now and nevis crystal inso Center or doing that letter writing Punk rock Road is scandal went to work place Pocari sweat Lite shows from just about sandwich secret to learning to speak call to live with shows that some To The Power of five more special Best Death is like the way to the park and Drive Secret about you and Price of any more results related events and is not made and garbage is Born To raise money to single strains of errors and find the best One apk specialists and Hills Summer damaged and supporting up is aware of their workers Producer of urology of you record strassmann What i want is apparently you don't forget is paid Out One Forever just What to date with parents did you ever where is number five feitas pela Zero any number basis for users of work and want to One Pieces of commands and Lore Zero event which can White a basis now know will ruipai spacespeakers s is never read more Find out whether the Wedding and write to act against them But if we ever caught in first as World Zero Metal crazy about you There is your name what happens to be there forever Nightcore It's ok Cause I wonder What's the date with the better late We got in first and realistic and it needs the money would you wait I'm doin a sweet mini advantage of the work and integrates the weather today cases are about the string Mask wash hawaiian together now the local now and want and suites is implemented hamburger hemineglect your name was meant to begin in all aspects of The Power of and spacious with What is apparent National Gallery about you see typical One Fine Day At The Power of smell and later array of value as it ends tonight Number One account Number One correct the town of Heart and tomorrow What nationality and take about the week next and What the weather today is the weather like in single-handle you and your family We're single-handle you and your family We're single-handle you and your family We're gonna minister you hard live show Center Where all the handle nights When She needs to be of personal Touch of performance curve of Pearl stdout in ever pest reject calls and Gentlemen artifacts and leaves and ends well don't matter how many articles which one single core of paper One Thing right person as expensive as Postal And The Core of networks and structures of value of and Little Of as late but now performance people spend a what it and with love more Chris passport Dana White Walls and hundreds of Life and is greater dear or nicholas gunn gard hundreds of the wise and interested Advanced nourish sportsnet at once i want to find the resort playcast many International main drain and interesting with mention of cable masseger multi-page day on Earth is Used masseger multi-page day on Earth is Used masseger multi-page day on Earth is Used when we on gonna be wild year's day because It can amount spawning have at the expansion And Love The Way Cake with any decal mimaki record your address case with Organic and one amount miniview There were around to work at Number One Star weaknesses and the Word Excel What can I say When can call at the news white room don't go to school you get it pass Action against The Sand and Dust mites avoid to celebrate New York Banking Ok very hard and it's Where is never tell me the validator dendrophila Pika to play to work We had a large Number One ever had any code find their advantage and Nice And The Beat goes around in the cast zai shou Wu hanala b'gosh with your serial port number the hero's way from every Corner with more To Life is one more time Because I'm acting upon another time back to the power of That is the record that the power of prayer because the heart is broken or above and for what is the most of the accounts of threats I miss our use of free your Monsters with before your eyes could talk anymore fights for any purpose the vessel print save don't regard s.pearl s.pearl s.pearl ifile.it dxcore netwiz adarna stackpanel ifile.it dxcore netwiz adarna stackpanel ifile.it dxcore netwiz adarna stackpanel resort Golden Sand and money back to his are you interested in this case We Come as time goes with estoque minoan events forced me to check with respect which just before the interest rate and out more find Myself and language and journalists in performing the overall look What some meat nectar watch and listen on to what is your profession special against them or public address For You For The Immortal courier baby Dragon Dance With Me I'll make fun of tomorrow Of Your Heart must Watch image set of Passion and accuracy past ex Mode to live is and a woman's day When I can tell her to our specialty paper and your expertise and value or wifi X6 the world in my biggest loss is When turned the work out of any disease are concerned with us in the width modulation penalty catalinas offical work around you want to specify How the useful in the work Westlife unsupported file word and hopefully of priests and Transport
|
Pow(x, n)
|
powx-n
|
Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`).
**Example 1:**
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000
**Example 2:**
**Input:** x = 2.10000, n = 3
**Output:** 9.26100
**Example 3:**
**Input:** x = 2.00000, n = -2
**Output:** 0.25000
**Explanation:** 2\-2 = 1/22 = 1/4 = 0.25
**Constraints:**
* `-100.0 < x < 100.0`
* `-231 <= n <= 231-1`
* `n` is an integer.
* `-104 <= xn <= 104`
| null |
Math,Recursion
|
Medium
|
69,372
|
56 |
this is one of those problems which become very simple to solve once you actually draw diagrams and try to look at it visually I am talking about the problem merge intervals on lead code and no doubt this is asked in a lot of coding interviews by almost every other company so let's see what we can do about it Hello friends welcome back to my Channel first I will explain the problem statement and we will look at some sample test cases next we are going to look at a Brute Force approach very briefly and then I will show you visually how this problem looks and how can you come at a very efficient solution that way you will never forget it and then as usual we will also do a dry run of the code so that you can understand how all of this actually works in action without further Ado let's get started first of all let's make sure that we are understanding the problem statement correctly in this problem you are given an array that has some intervals and you have to merge all the overlapping intervals and once you are done with merging once again you have to return me an array that has all the non-overlapping intervals so what does non-overlapping intervals so what does non-overlapping intervals so what does this actually mean let us try to understand it with a first test case and you can see that I have an array and it has all of these intervals so what do these intervals actually mean for example the interval 1 comma 3 simply means that you have elements 1 comma 2 comma 3 inside them and then the interval 2 comma 6 simply means that you have all of these elements now if you notice the elements 2 comma 3 they exist in both of these intervals correct so technically you can merge them and once you merge them what will happen they become just one interval right and you can write it as 1 comma six correct and similarly if you try to look at these other intervals you will see that none of these elements are common in the interval that you have defined so now you cannot merge them so this is the best possible scenario in which you can have non-overlapping which you can have non-overlapping which you can have non-overlapping intervals so for the first test is your answer will look something like this you can see that I have merged four intervals into just three intervals right similarly you can look at one more test case in a second test case I have two intervals one comma four and four comma five you know that the element 4 will be common in both of them so I will just merge them and create one interval that will be one comma five and that will be your answer correct now there is one important thing that you have to notice while solving this problem for example in the first test case you cannot just say that hey I will make my interval 1 comma 18 that is the smallest value and the largest value because now this interval has all the elements from one up till 8 but when you look at all of these elements individually you do not have a seven you do not have 11 12 13 and so on right you get the idea so you cannot have an interval with just the minimum value and the maximum value you want to have the least number of intervals possible such that you are covering all of the elements correct so now if you feel that you have understood the problem statement even better first feel free to try the problem once again on your own otherwise let us write into the solution to understand things better let us start off with a bigger example and as a programmer your first approach should be that okay how can I solve this problem in a Brute Force manner so here is something you can do what you can do is you can start off with the first interval right one comma three and then what you will do is you will iterate over each of these intervals and try to find that okay which other intervals that I can include you'll find that okay I can include 2 comma 6 and 2 comma 4 inside it and what is the lower value and the upper value that is 1 and 6. so ultimately one of your intervals will end up looking like one comma six and then for your next iteration what can you do you can start off with the second interval that you have and then once again compare it with all the other intervals that you have and then try to merge it right you will keep on doing this for all the other intervals and then ultimately you will be able to arrive at a solution right but this solution will not be efficient at all you will spend a lot of time just to iterate over the array again and this will have a order of n Square time complexity and a lot of comparisons so certainly we need a better approach to solve this problem what can we do about it so once again I have the same array with me and we will try to come up with an efficient solution if you remember I told in the beginning of the video that sometimes problems become very easy when you try to visualize them and in this problem you know that all of these are intervals right there are integers between these ranges so what happens if we try to plot them out and look at these intervals visually I'll tell you how you can do that so just create this type of a number line and then try to map all of the intervals that you have so let us just start and try to get all of these intervals one by one so my first interval is between 1 and 3 my next interval is between 2 and 6 my third interval is between 8 and 10. the next interval is between 8 and 9. moving ahead I have an interval between 9 and 11. then I arrive at 15 and 18 then we have 2 comma 4 and the last interval is 16 comma 17. so this is how your interviewers look like visually and if you notice this diagram closely you have already arrived at the answer right just look at it again so these are your three intervals that should be in your output array correct and you also know what are their lower bound and upper bound so one interval will be one comma six the other interval will be eight comma eleven the third interval will be 15 comma 18 right and that's it this is your answer but how do you get to it let me remove all of this and get back to our problem once again now try to think how are you merging the intervals so let us say I have my first interval that starts at 1. now all throughout the array you would want to find intervals that are closest to this one right and then you will try to merge them so you're more concerned about the starting point of the intervals rather than the ending point because if they are starting together then you want to Club all of them in just one interval correct so that is the thought process on which what you can try to do is you can sort this entire array just based upon the first number of each interval So based upon this when you sort your array will start to look something like this you can see that all of these numbers the starting point of each interval they are now sorted in an ascending order so technically all the intervals that start together have now been grouped together as well correct so once again let us try to plot these intervals but this time we will go off of our sorted array so I look at my first interval I see one comma 3. correct so I plot it now look at the next interval 2 comma 4 where does it start it starts at 2 right and you have already covered 2 in this interval so make this interval a part of this existing interval correct for now you have a new bound one and four right but wait you need to keep going ahead right look at the next interval again this is 2 comma six so two once again live over here right so you take up this interval and go all the way up to two so what did you do you updated your starting point and now your ending point is updated right but let us now keep moving ahead and see what happens look at the next interval this is 8 comma 9 right and what is the starting point this is eight and this starting point eight this is more than the ending point of the last interval and that simply tells you that hey this is where you want to break your interval and create a new interval so that is exactly what we will do I create a new interval 8 comma 9 and then moving ahead I have a next interval 8 comma 10 so this will also be included in this and then my next interval is 9 comma eleven so 9 is once again included in this so you see what is happening at each iteration I will try to update that okay these are my new bounds right so look at the next interval now it is 15 comma 18. it starts at 15 but what was the ending point of the last interval that was 11. since 15 is greater than 11 I will once again start a new interval so my new interval will be 15 to 18 and now I'm remaining with the last interval that is 16 comma 17 and that lies over here again and that's it you got all your non-overlapping intervals right so one non-overlapping intervals right so one non-overlapping intervals right so one interval will be one comma six the next will be 8 common 11 and the third will be 15 comma 18. and indeed this array will be your answer so you see what we are doing over here first of all you sort the array based upon the starting point of each interval and once you have sorted the array I trade through these intervals one by one if your next interval starting point is less than the previous intervals ending point then this interval will be a part of the overlapping interval and then you have to update your box so my new bound becomes 1 comma four and then you will keep moving ahead then you see 2 comma six two comma six will also be a part of your previous interval so once again your bonds will update 1 comma six so that is how you have to proceed and ultimately you will be able to solve this problem in a very efficient manner now let us quickly do a drawing of the code and see how it works in action on the left side of your screen you have the actual code to implement this solution and on the right you have an array that is passed in as an input parameter to the function merge oh and by the way this complete code and its test cases are also available on my GitHub profile you can find the link in the description below moving ahead with a dry run what is the first thing that we do first of all we have some sanity checks such that if you only have one interval then that's it you just return it because you cannot merge just one interval correct now moving ahead what do we do first thing is we sort the array based upon the starting point of each interval so once I sort it my array starts to look something like this correct you can use any method to sort but I'm just giving the library function and this will also work in order of n log n time complexity once your array is sorted now is the time that you will create a result lift that will have all of your non-overlapping intervals so how do you non-overlapping intervals so how do you non-overlapping intervals so how do you start going about it so what I do is I create this array and I will just add the first interval inside it so I say that okay my first interval will be 1 comma 3 right now you start a for Loop to iterate over each of these intervals and this is the Crux of the problem so what I will do is I will look at the next interval that I have in the loop the next interval I have is 2 comma 6. so if the starting point of next interval if lower than the ending point of previous interval you need to update your intervals so since 2 is less than 3 what will happen is I will update this interval and my new interval will end up looking like 1 comma 6 correct similarly you will keep on moving ahead and then look at the next interval that is 8 comma 10. so once again check if the starting point of new interval smaller than the ending point of previous interval no 8 is greater than 6 so this will qualify as a new interval and you are going to populate your list so this is how you will keep moving ahead and at the very end this complete list will be your resultant output so the time complexity of this solution will be order of n log n because you need this time to sort the array and the space complexity of this solution will be order of n because in the worst case you can have all of the intervals that are already disjoint and that will be a resultant answer I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that I know that you do most of your coding in front of a screen correct but sometimes it is better to follow the conventional approach and take out a piece of pen and paper try to draw the problem and then you might be surprised that you are able to arrive at an efficient solution you see what happened over here right it became so very easy Once you plotted everything out right so while going throughout this video did you face any problems or have you seen any other such problems which became very easy Once you draw them out so tell me all of this in the comment section below and I would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to solve next until then see ya
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
89 |
hello viewers welcome back to my channel I hope you are enjoying all the problems that I am uploading today I'm back with another problem from leak code gray code the gray code is a binary numeral system where two comes successive values differ in only one bit given a non integer non-negative integer and representing non-negative integer and representing non-negative integer and representing the total number of bits in the code print the sequence of the gray code a gray core sequence must begin with a 0 so basically if the input is 2 as shown in the example 1 right so the output should be 0 1 3 2 so if you convert back these numbers into binary representation right 0 will be represented as 0 because the number of bits are 2 right so 0 & 1 is represented as 0 1 & 3 is so 0 & 1 is represented as 0 1 & 3 is so 0 & 1 is represented as 0 1 & 3 is represented as 1 & 2 is represented as 1 & 2 is represented as 1 & 2 is represented as 1 0 so if you look here o 0 1 right so there is only 1 bit change so that is what they are looking for in a gray code there is exactly 1 bit is changed so for 1 & 3 so these two bits are same and the 1 & 3 so these two bits are same and the 1 & 3 so these two bits are same and the first two bits are 0 & 1 that is also first two bits are 0 & 1 that is also first two bits are 0 & 1 that is also one bit is changed so that is how we have to generate the gray code so there are many possible gray code sequences for a given input number of bits but all they are looking for is one gray code right so this reason there is another example 0 2 3 1 even this is also a valid gray code sequence for example so it's not like there is only one valid sequence but there are multiple Hardy virus sequences possible so we are going to see how we are going to achieve this problem so there is a way that we could easily solve it so we go with the approach like we build the gray code for n minus 1 bits and use that to build the gray code for n bits that means so for if you build a gray code for say one bit right one bit then we will use that to generate the growth gray code for two bits and whoa likewise we generate a great board for three bits using the two bits like this okay so let's go look at the steps involved right so building the gray code for one bit the gray code is zero and one that's it so if you have just one bit rate if the input is 1 all the gray code is just zero and one ah in other way you can say okay one zero is also a possible gray code right so because there is only change in one but yes that is possible right but for this example I am going to take zero and one as my gray code and for two bits right for two bits we'll have to apply the below logic right so for n minus 1 bits in this case n is 2 right 10 minus 1 is 1 bit so that is a gray code that we are going to utilize for that so we are going to generate 2 arrays right two arrays first array is prepending zero to each element in a gray code from n minus one bit so we are going to prepend zero that means put a prefix 0 prefix / 0 put a 0 prefix for prefix 0 prefix / 0 put a 0 prefix for prefix 0 prefix / 0 put a 0 prefix for one right so here that here is an example that I am talking so one bit array is 0 1 so apply the Evo logic for two bits so first array will become 0 1 right what we are doing is prepend 0 right and the second array what we are doing is prepared one for the same thing so if you generate another array for appending 1 right it will become 1 0 1 so now you have these two arrays right first error and a secondary what you should do as a third step here right this one join first array and reverse of the secondary remember reverse of the secondary reverse means you have to reverse the element in the second array so the final array for two bits will be we are joining the first array plus reverse' 1 0 1 what will be reverse of reverse' 1 0 1 what will be reverse of reverse' 1 0 1 what will be reverse of 1 0 1 it will be 1 0 like that this will be the gray code for two bits so similarly you can work out for three bits by using this gray code for two bits four bits by you can make great work for three bits likewise so but the question that is asked is we have to return the integers right so finally we have to convert the binary strings back into integer and then return the religious order right so this is a simple explanation for converting a gray code so let's go and try to do that right so this is a list that we are trying to give us an answer right but anyway this answer should be converted back to integer and then return right so initialize the count to zero and if n is greater than or equal to zero add the first bit so basically the first gray code zero right so that is what we are going to write threads and if it is greater than or equal to one right so greater than or equal to one means that means you are looking for zero and one so you just add one right so that we are increment in the count each time so if the count is still less than that and let's say if count is two right so that means we have to go through these steps right these steps so that is what this while loop will do for us so generating there n to the end gray code by using the N minus 1 gray code so the new list in here we are just declaring and from the old list we go from the starting number to the ending number and start preparing 0 right start preparing 0 will be added as a prefix and then add that resultant into the new answer that we are new answer list right so this is the first error that is the first step right and the second step where we are a bit trying to come do these two steps in a single time right instead of doing the reverse and all that right what we are doing is go from the last element right so go from the last element to the first element and a to the answer so that is as good as doing the reverse of the second array so this is doing two steps the second array prepending as buddha' as second array prepending as buddha' as second array prepending as buddha' as well as reversing so once you have the new answer right new answer array just assign that to an answer so that it will be used for the next set of binary code representation sorry gray code representation so if let's say if you are doing n is equal to 3 right so we are done through n is equal to 2 so it has to go back and do that n is equal to 3 part also so finally once the gray code is available for n bits right so these are this is n bits right so while the value increment the count it somewhere it will reach to M while it we have the n bits right we will convert that into basically the integer right we just convert 30 to integer and finally trace and then results hope this cleared the any questions that you have so if you like the solution please subscribe to my channel and hit the bell icon so that you get notifications for my all future videos please share among your friends if you are looking for mock interviews our interview guidance please reach out to me through the comment section please include your email in the comment section I will get back to you thanks for watching I will be back with another video very soon till then bye
|
Gray Code
|
gray-code
|
An **n-bit gray code sequence** is a sequence of `2n` integers where:
* Every integer is in the **inclusive** range `[0, 2n - 1]`,
* The first integer is `0`,
* An integer appears **no more than once** in the sequence,
* The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and
* The binary representation of the **first** and **last** integers differs by **exactly one bit**.
Given an integer `n`, return _any valid **n-bit gray code sequence**_.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,3,2\]
**Explanation:**
The binary representation of \[0,1,3,2\] is \[00,01,11,10\].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
\[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
**Example 2:**
**Input:** n = 1
**Output:** \[0,1\]
**Constraints:**
* `1 <= n <= 16`
| null |
Math,Backtracking,Bit Manipulation
|
Medium
|
717
|
1,852 |
what is going on everybody it's your boy average leader here with another video and today we are tackling number 1852 distinct numbers in each subarray now this is a pretty new problem on leak code so it hasn't been asked by a lot of companies uh this year at least but i think it was a pretty good one to try out and i think you guys can gain a lot from it if you guys can go ahead and hit that subscribe and like button that would mean the world to me it helps my channel out a ton by giving you more exposure to people that don't know me and if you want to see another problem done just comment down below and i'll make sure to do it for you and with that all out of the way here we go given an integer array nums and an integer k you are asked to construct the array ants of size n minus k plus one where ants of index i is the number of distinct numbers in the subarray numbers that index i to i plus k minus 1 equals nums and index i num okay so as you can see this is a very difficult problem to understand so if i got this in an interview i'd ask to see an example and you know luckily lead code provides this example which makes a ton more sense than the actual problem statement so let's dive into this example so we see that we are given you know this array of numbers and uh you know for output we get three two three and the question we gotta ask ourselves is how did we get from you know this input to this output well in the explanation it says okay so the number of distinct elements in each subarray of size k is uh goes like this so we're looking at each sub array of size three right so in our first subarray of size three we have these three elements one two three and there's three distinct elements in there right so that's why uh in our output array we are going to put the number three now it looks like they're shifting over the array by one so we're going to index one two three now and since there's only two distinct elements here we see that there's a two in the next index now after that they shift over to three two and once again there's two distinct elements so that's why they put a two here and then after that they shift over by one and they once again we have two distinct elements we just have two and one so we put a two here and finally we shift over one last time to two one three and like we had in the first iteration we have three distinct elements again so we put a three in the last place of our output array so it looks like uh our output array like this calculation that they did up here you know the output array has the size of n minus k plus one that looks like it's the number of iterations that we are going to do uh while we're doing this like weird shifting subarray kind of thing so uh this makes a little bit more sense to me than the problem statement did um and if i was given this problem in an interview the next thing that i would do you know given the problem statement and an example i'd ask the interviewer a few clarifying questions so you know i maybe i'd ask like you know are we always going to have an input given to us that's like a very easy question to ask like you know will we ever have like a null value or like a empty array or something um but you know that's not very important for like our situation right now uh question that is important is what is the range of our integers in our nums array okay uh like are we gonna have negative numbers are we gonna have strictly positive numbers and if we have you know negative or positive numbers are we going to go to like positive infinity negative infinity or are we going to go to only like positive 15 negative 50 what's the situation so let's just assume that we are only going to have positive numbers uh in our nums array and the range is going to go to positive uh 1 to positive infinity okay so with this information in mind uh let's take a deeper look into this problem so based off of what they're doing here it looks like they're making this little window and they're just shifting or sliding the window over by one at each iteration do you guys know uh what this technique is called well it is called the sliding window technique and that's exactly what we're going to implement for this problem and if you guys want to go see an example of a sliding window technique you guys should go check out my maximum points you can obtain from cards video which at the point of filming this video is google's second most asked interview question so go check that out and you know maybe come back to this one but we know that this is a sliding window problem and in a sliding window we will have two pointers okay one at the start of our uh sliding window and one at the end of our sliding window and we know that our window is going to have a range of k elements in it at all times so like our first initial window our start pointer would be at zero at the zeroth index and then our end pointer uh would be at the second index and this would represent all three of our elements in our window and every time we slide over i just move the start over by one to the you know to the first index and then i move the end pointer over by one to this and then we just kind of keep going down our array until we're at the end so um you know implementing a sliding window isn't too bad the more interesting part of this problem is we need a way to find the distinct number of elements in each window right so that's gonna be a little tricky so let's think how can we get the number of distinct elements in each window well um i guess a very brute force solution is uh for each window we could iterate through each subarray like one more time and just count up the number of distinct elements somehow um so you know like we iterate through these three elements then once we shift our window we iterate through these three elements then once we shift our endo we iterate through these three elements but you know i think we can immediately see that this isn't the most efficient solution like we end up counting multiple numbers multiple times like for example just in this iteration we count one two three right but then when i shift over i'm going to count two and three again and then when i shift over again i'm gonna count this three one more time so it's not that efficient we're like counting numbers that we've already seen before so uh and you know that time complexity would like run in like i think n k of n times k or n represents the length of the nums and k represents each window so that's not very efficient so i guess the next thing that i think of is like okay what data structures could be used in this situation so before we dive into the specific data structures let's have a quick checklist of like what is our data structure supposed to do well one it's supposed to somehow hold the distinct number of elements of each window two when we shift our sliding window um right before we shift we need a way to remove this uh like what our start pointer is currently pointing at before we increment the start pointer so let's say we're at one two three our windows one two three before we shift to two three two we need a way to remove our first element from the number of distinct elements that we're holding right and that leads me to the third thing right after we shift our window over we need a way to add uh what our end is next is going to point to so we need a way to do this efficiently okay so efficiency is always going to be the key when we're thinking about data structures so now i'm going to list the top uh i don't know like the top data structures that i can think of off the top of my head so off the bat i think of array arraylist linked list that cue hash set and hash map now i'm gonna go through each of these and pick out why i could use one or why i couldn't use one okay so let's start with the array um i don't think this would be that useful because you know with an array we have a finite number of items and since the range of each of our number of elements is you know positive infinity it's going to exceed you know the number of spots that we're going to need in our array and like i just i think it's not that useful since we only have a finite number of items and like i just can't think of a way that we can use an array properly knowing that we have an infinite range for each of our numbers okay so that's very key if we knew the range was going to be a little smaller like only like up to 50 elements or something uh maybe we could use an array but since the interviewer told us that the range of each of the numbers is going to be like up to infinity then maybe you know it's going to be hard to use okay uh okay so that moves us over to the arraylist now with an arraylist let me think about this uh you know in each iteration we'd somehow like add the elements in our window into our arraylist so i usually start with like a starting window and i'd iterate through the first k element so i'd add one two and three into our arraylist and then when i shift over i could easily remove this one uh maybe by having like an index associated with it or something and then i shift my whole window over and then i'd add this to so adding and removing isn't necessarily the most efficient right so but that's not the only problem um let's say we put one two and three into our wait list right now this first window isn't that bad we're putting all three of these on the internal arraylist and maybe what we could use to represent the distinct number of elements in our output array is at each index of our output array let's just use the arraylist's size to represent the distinct number of elements so since we have three elements in our array we're gonna arraylist we're gonna put three in our output array okay that's fine now let's slide our window to the next window so now we have two three two so we've removed this first one and we've added this uh this other two so in our arraylist we have a two a three and a two and there lies the problem arraylists uh take account for duplicates like it holds duplicates of any number and in our case if we were to use the size of the arraylist we'd have a size of three but you know in our output array we need a size of two in this situation and i can't think of a way to not account for duplicates and not add and remove properly and all this other stuff so i feel like an arraylist wouldn't work uh for our particular situation and for the same reason a linked list wouldn't work either because you know once again like you'd have to have you know if i shifted my window over one more time and i'd have this two already in my linked list and i need to add this to it would be hard to you know count the distinct number of elements since it holds all duplicates so a linked list would wouldn't work either now moving on to stack and queue you know stacks and cues are really useful for like when we have an ordering of sorts right like a stack is used for a lifo ordering a last in first out and then a queue is used for a fifo ordering a first in first out so that those aren't really useful uh in our situation right now but moving on to the hash set okay so the hash set is interesting because it does hold the distinct number of elements it doesn't hold duplicates okay so let's think about this uh let me put the first three elements into our hash set okay cool i can do that and i can use the hash set size to you know put into our output array but then i'm going to remove this one and then shift over uh to the next window right and i'm going to add this two but in our hash set there's only going to be since we already have a 2 in there we're not going to add we're not really going to add this duplicate to so there's only going to be two elements in our hash set and this would be great because you know that's what we need right here but notice this when i shift the window one more time over i'm gonna remove this two oh well actually since i add this too it ends up evening out let me show you this window now when i have this window okay right before like i currently have uh one two and one in my hash set right but now there's two twos in this window and it is going to be important when we shift our window to the next one okay so now i'm going to remove this two from our hash set and i'm gonna shift my window over and i'm gonna add this three to our hash set now let's think what is currently in our hash set when i do this there's one and there's one three there's only two elements in our hash set because when we remove this two since it doesn't kind of account for like the number of twos that we have or the duplicates of the two it seems like we're removing all twos from our window even if there was like another one like we have right here so since there's only two elements and we need three distinct elements in that last position a hash set wouldn't really work okay so uh you know for a hash set it's cool we can hold the distinct number of elements but we can't remove properly now that takes us to our last data structure that hopefully has a chance here we're going to use the hash map now similar to the hash set uh it can hold a distinct number of elements which is very good it doesn't hold duplicates that's very good and let's let me think okay so with a hash set there's key value pairs that we put in right so if i were to maybe uh for the keys put in like these numbers in our nums array and maybe for the value like usually i'll put like the count of each of our numbers in a hash map that's kind of like what my mind is going towards right now so let me just do that i'm gonna start by putting one two three into my hash map and i'm gonna put each for each of these keys that i put i'm gonna put a value of one since they only have one count each now when i uh shift my hash map over i'm going to decrement the count for this and i'm going to uh you know shift over to these three elements right and when i add this to over i'm just going to increment my account for the 2 key by one and i'm just going to keep doing this until i'm at the end of my array so by doing this we're basically solving that one problem that hash set was giving us so if i had the same window here in my hash map in this current window and i'd have a key of two with a value of two and a key of one with a value of one now when i shift my uh window over to the next one all i have to do to remove this first two all i'd have to do is decrement the count of the key to f from our hash set from our hash map um so instead of two with a value of two i'd have two with a value of one when i shift over and then i just have to add this three with a value of one into my hash set hash map and uh and once again i just use the size of my hash map to represent the distinct number of elements so i have three elements in there and that's it that's perfect this is exactly what we need to do i'm going to note though there is one important thing that we need to do with the hashmap so let's say we have these three these first three elements in our hash map right we have one with a value of one two with a value of one and three with a value of one when i shift my window over i need to decrement the one in our hash map by a count of one okay so i basically need to make the key one have a value of zero after i shift this over now when i do that we need to figure this out do i still want that one in our hashmap okay so let me think about this uh let's just assume i keep it in my hash map i have a one with a value of zero and then i and so it's gonna be here and then i'm gonna shift my window over to two three two and since we have this other two i'm going to increment the value of the key to in our hash map okay so before we had in this window we had a key two with the value of one since there's only one count but then when i shift over and i add and i take account of this two i'm going to have the key to with a value of two in my hash map and i also have like the key three with a value of one now since i still have that one with a value of zero there's three elements in our hash map and since i'm using the size of my hash map to dictate how many distinct elements are in each sub-array elements are in each sub-array elements are in each sub-array i would have a size of three here and that's not what we need and in this index don't we need an index of we need a value of 2 in this position so what i'm going to do every time i decrement the count of a key and i hit zero or something um if i hit a value of zero i'm just going to remove that key value pair from my hash map and if i were to do this if i were to remove one that means i just have the key two with the value of two and the key three with a value of one so just two elements uh and since i'm using the size and since there's only two elements then this would work out properly for us this would actually work for us so you know with all this in mind it looks like the hashmap is the way to go and i'm basically going to implement everything that i described in the code that i'm about to code out the last tip i want to give you guys before i go and start this code is there's something really interesting that a hashmap and hash set uh can do now i don't know if this is a causation but there is definitely like a high correlation with what i'm about to say so do you remember in our very first brute force solution that we did like some time ago where i said oh let's just iterate through each of our windows and somehow count up like the number of distinct elements right so we'd basically have like a one for loop that would iterate through the entirety of our uh nums array and then we'd have like an inner for loop that would go through each of these windows right a quick tip is if we ever have like an inner for loop that's usually causing the in the inefficiency we can sometimes replace that inner for loop with either a hash set or a hash map um there's usually like a high correlation with like an inner for loop being replaced with a hash map or a hash set and that's exactly what we ended up doing here at the very end of like you know trying to uh find the pros and cons of each of our data structures so you know that's a little tip for you guys you know maybe if we knew that we had that inner for loop and we knew this trick we can go straight to hash that hash map instead of evaluating array list link list and all the other data structures so a little tip for y'all that's kind of how twosome is done and they take the inner for loop and they replace it with the hash set so okay anyways uh let's dive into the code so the first thing i do when i do these problems is i always ask myself what are we trying to return in this case we're trying to return an int array so i'm going to have an answer right here and i'll call it answer equals new int and what's going to be the size of the ins array well luckily in the problem they gave us the size because it says you are asked to construct the array ants of size n minus k plus one so i'm just gonna copy this and uh put it right here n minus k plus one awesome and the last thing we'll do is return this answer array okay cool now i'm going to initialize the hash map that we are planning on using okay so i'll have a hash map where the key is going to represent like the actual numbers that we're going to put in and then the value is going to represent the counts of each of our numbers that we're going to put in and i'm going to call this hashmap counts equals new hash map okay awesome and next i will you know initialize the pointers of our window so i'll have my start pointer which is going to hold the initial the left boundary of our first window so it's going to start at zero and i'll have my end pointer which is going to represent the right boundary of our window so i'm gonna make this k minus one and in this case notice that i am keeping like an inclusive window here where my start and end pointer are going to represent the very beginning of our window and the end of our window but it's going to be inclusive like it's including each of those uh numbers that is pointing to there are some sliding window problems that where you might find it easier to use an exclusive window but in my opinion like 85 of the signing window problem that i've done i think it's easier to do an inclusive window like this it's just easier to visualize for me so that's why i'm doing it like this okay cool so the next thing i'm going to do so we have our window here right let's populate our map with the fir with our first windows distinct values okay so what i'm going to do is iterate through the first k elements which is going to represent our initial window and i'm going to put the counts of each of our numbers in that in the first k elements okay so for ins i equals zero i is less than k i plus and what i'll do is use the put method that's used to actually put elements into the hashmap so i'll do counts.puts into the hashmap so i'll do counts.puts into the hashmap so i'll do counts.puts and what am i putting in well i'm putting in a key of each of these numbers right the actual like distinct value i guess okay so i'm putting in nums at index i and what is going to be the value it's going to be uh the count of each of these keys now if i haven't seen a key before right like for instance if i were to put in these three elements into my hash map i haven't seen any of these three elements in my hashbrown before so i would put a value of one for each of these right but now i'm gonna go down to example two okay now look at this our first four elements here are all ones and we're asked to have a k of a four or like a window size of four so our initial window here uh would just be like all these ones right in our hash map i wouldn't want to have one with a value of one i want to have one with the value of one at this index then one with a value of two at this index then one with the value of three at this index and then finally one with a value of four at this index when i'm basically done with iterating through my initial window right so i need a way to kind of like get what was currently in our hashmap and then increment one to it there is a really cool method that takes care of both of these cases okay and it's called get or default which does exactly what uh it sounds like okay so if an element is already in our hash map it's going to get that element and i'm specifically getting like you know this element right here so this element is a key that's already in our hash map it's just going to get this and we're going to add one to it okay now if an element isn't in our hash map it's going to default to the number that i'm going to put right here so it's going to default to 0 and it's going to add 1 to it so this takes care of both cases that we're trying to tackle if we've seen it already it's going to get whatever is whatever value it currently holds is going to increment it by one if it isn't in our hash map it's going to default to zero and it's going to add one to it so that way you know these three elements are going to have a value of one because it hasn't been seen yet okay cool so boom look at that we've uh we've initialized our boundaries for our window we've put in the values excuse me we put in the distinct values for you know our initial window and now a sliding window we end up iterating through the entire array so uh i usually have another loop at this point okay i'll usually have a while loop and when do we want to stop so let's think about this so oh sorry guys sorry technical difficulties i'm really sorry about that was uh my bad there but okay so when are we going to end our while okay that's what i was getting to well let's run a quick simulation here so we're going to have this window uh and uh you know after we're done accounting for like the distinct number of elements in here we're going to increment our start and end pointer so we're going to get this window then we're going to recount our distinct number of elements then we're going to shift then we're going to recount and then we're going to shift one last time we're going to recount and we're done now notice our start pointer is here and our end pointer is here so it looks like when the end pointer which by the way you know i hope you guys saw that you know the start pointer was always at the beginning of our window and the endpoint was always at the end i should have explained that but here notice that the end pointers at the very end of our nums are right at least so let's just keep iterating while the end pointer isn't at the end of our num.length array okay so what i'll do is num.length array okay so what i'll do is num.length array okay so what i'll do is while n is less than nums.length n is less than nums.length n is less than nums.length okay and inside of this while loop we're just going to keep uh you know strategically incrementing our start and end pointer until this condition is met okay now the very first thing we need to do is since we have uh our initial number of distinct elements in this hash map the first thing we'll do is let's put that value into our answer array so i'll say answer add an index of something i'm going to leave it blank for a bit equals counts dot size now what index are we going to use so i'm going to show you guys one more thing in that example notice that the start pointer in that last example the start pointer was at this index right here right it was at the 0 1 2 3 4 index now at this fourth index this is going to represent this window is going to represent the last uh position in our output array and notice what index it's in the 0 1 2 3 4 index so our start index actually is going to be a great representer representation it's going to be a great uh tool that we're going to use which is going to not only uh be the left boundary of our window at all times but it's also going to be the index that we store the distinct number of elements in our output array so uh i'm going to put the answer at the index of start oops if i can spell is going to equal counts outside so i'm initially going to take care of like the window that we tried so hard to you know populate right and after this what have we done so after we like uh you know count the number of distinct elements the next thing we need to do is shift our start pointer up one okay so we're basically shifting from a window of size three to a window of size two temporarily now notice what happens here i go from one two three to a window of two three and i'm you know removing one from our window so i need to remove one from our hash map okay so that's gonna be the next thing that we do whatever our start pointer is currently pointing at let's remove it from our hashmap so i'll do counts.put nums at counts.put nums at counts.put nums at index of start so that's what our start pointer is pointing at and all i'm gonna do is counts.getnumbs and all i'm gonna do is counts.getnumbs and all i'm gonna do is counts.getnumbs start so it's going to get the current value that uh that the keyone has in our hashmap and i'm just going to decrement that value by one okay now remember what i said uh earlier when i said like okay it doesn't make sense if this value of uh one is zero like should that still be in our hash map no we wanna remove that so let's do a quick check right after this if the counts dot get numbs start equals zero oh did i do that right yep equals zero what are we going to want to do we want to remove it from our hashmap so accounts.remove hashmap so accounts.remove hashmap so accounts.remove nums start awesome okay look at that and then the last thing we got to do is increment our start pointer so with these three lines of code there's you know four uh a couple lines of code that we have here uh we are basically taking care of us shifting our start pointer so we're going from one two three and then we removed one then we incremented our start pointer so now we just have a window of size two three obviously we need a window of size k we only have a size 2 right now so the last thing we need to do is increment our end pointer and then add that current that value that the endpoint is pointing at to our hash map so i'm going to do end plus and i will say counts dot put uh nums at the index of n so i'm putting this into our hash map and just like we did before in when we initialized our initial window right if we've seen it before then we're just going to want to get that value and we're going to want to add one to that current value if it hasn't seen it before we want to default to zero and then we're going to add one to it so we're just going to place a value of one into our hash map so i'm actually going to copy this over here and all i'm going to change is nums at index end is what we're looking for okay and after this really takes care of our sliding window this really does it now the last thing that i'm going to want to ask you guys to do is whenever you guys are working with a sliding window problem it is so important to double check to see if like this cur the code that we have right now like works okay and what i mean by this is are we going to go out of bounds anywhere you know we're doing all this increments with uh specific pointers we're specifically incrementing the start we're specifically incrementing the end we're accessing end and start multiple times uh so we need to do one check and let's just make sure that uh that we're not going out of bounds anywhere okay so the only places we'd go out of balance are at the beginning and at the end now we've done that i've done this example like with the beginning multiple times now so i'm sure in the beginning it's fine let's just go through a quick uh you know run through of our code for the last few iterations of our code okay and i think if you guys did this in front of your interviewer like they would be hella impressed like they'd be so impressed okay so if you recognize that you know with sliding windows we have the chance of going out of bounds in a few spots uh we have a few edge cases that we might need to consider you know they will definitely give you brownie points for that kind of stuff so let's just assume that we're going to be on this iteration okay of uh where our window has two one and i'm gonna assume that my hash map is working properly and i'm adding and removing from my hashmap properly so what happens here a hash map has uh two twos and one right so the first thing that i do in my while loop is i uh put that size into the answer array at that start index so i feel like that's gonna work because zero one two three it's gonna be at the third index so zero one two three uh it looks like there's two values and in my hash map i trust that there's two distinct values in there so that works fine and then i remove it from my hashmap then i uh you know i do all this removal stuff and then i increment my start index so now i'm at this window okay cool now the next thing i do is increment my end index so i have two one three and then i add that three into my hash map now we need to go through this iteration one more time uh because if we don't do this right we're not gonna actually put the size into that last placement of our output array right we're not gonna have this three in there so that's why we're to go through one more time answer that answer on index star is going to equal the count slot size this is going to work for us we're going to remove our uh initial index that's fine and then we're going to increment our index our start index that's cool now this is where it is this is where i want you guys to see and plus okay so we are basically going like out of the bounds of our nums array this is fine as long as we're not accessing nums at that out of bounds array we shouldn't have a problem but oh wait look at this at line 23 we're accessing nums at this out of bounds index and we're accessing it like a few times here so we're gonna get an array out of bounds exception i you know or error or whatever right so watch i'm going to run this code and i need dana and jet oh boy oops okay well that's not the only thing that's wrong okay so numbs.length not that's wrong okay so numbs.length not that's wrong okay so numbs.length not n i'm sorry so and this is assuming that i have everything else right so let's just hope that i don't make any other mistakes boom array index out of bounds exception okay so we see that we got this exception right so how can we actually fix this well uh you know the problem is we need this line to execute one last time when our when we have this window right here right uh the problem is when we increment our end index out of the bounds uh it's really this line that's causing all the problems so let's just have a conditional here let's just say if n is less than nums dot length only then will we execute this line okay so in this situation when end was out of the bound the integer that n was holding was seven and the length of this array is seven right so uh you know even though it's out of bounds since this conditional doesn't get executed this line will never fire so if i were to run this now you see that boom that works would you look at that um this is one way you could do it okay and before we move on i'm just going to show you one other way we could um so clearly the problem happened uh when you know we went like one iteration one too many you know what i mean but we needed this line to execute right so what if we just went one iteration less right but now if we go one iteration less that means that uh even though we're holding everything in this window we're not actually executing one last iteration and firing this line so in this place uh in our output array we'd have zero because that's the default value that would be held in our integer array and you see that happening see look at that zero so to combat this what you could do is just copy this line and put it uh at the very end one last line before you return and oh boy this kind of stuff bugs me there we go so if i were to run this should work out fine so you guys there's two options for you guys to pick uh and this is there we go so yeah that works okay now for me i personally am going to use this conditional just because i like everything in my in like one in a while loop and uh this is how i thought of it when i first did this problem so when i submit this uh let's go ahead and see what we get they ask you how you are you just have to say that you're fine oh my god oh i'm so sorry i need to i had to i also have to change the condition that is my bad right there and boom look at that one time 77 milliseconds faster than 21.55 milliseconds faster than 21.55 milliseconds faster than 21.55 percent okay so now on lead code this doesn't look too great but if your interviewer told you uh that you have an infinite range of numbers this will work okay this will get you past the round if you explain it just the way i did and like add your little flair to it you are gonna kill that interview now let's say after you do this your interviewer gives you a follow-up he uh interviewer gives you a follow-up he uh interviewer gives you a follow-up he uh he or she tells you okay let's assume that the range of each of these numbers has a range of one hundred thousand okay so we can go from one to one hundred thousand as opposed to one to infinity okay and that's actually what lead code has here the constraint that it gives us is that each position uh we go from each position can be one to ten to the fifth aka one hundred thousand okay so that could be a follow-up that they so that could be a follow-up that they so that could be a follow-up that they gave you or at the very beginning of the interview when you asked the interviewer hey like what's the range of each of the numbers they could tell you that oh we go from one zero or like one to a hundred thousand okay now if that situation occurred you can still use this code right and i feel like it would you would still be fine like i feel like they you'd still pass the interview but let's just assume that they give you a follow-up they say that they give you a follow-up they say that they give you a follow-up they say hey can you make this more efficient now you gotta think what is the what's the thing that's causing the inefficiencies right now like this is pretty efficient code mind you okay this is pretty good but we can make this more efficient so you know looking at our for loop we only iterate through like the first k elements here and uh you know with our uh while loop we just go through all the n elements so our time complexity is of n we're not like double triple quadruple counting like we were doing before um i'll the thing that i'll think of if i can't like change a while loop if i can't like reduce the number of loops or something like that is i think to myself okay do i really need this data structure okay and the reason i say that is because remember when we were evaluating our data structures and the first data structure i said was oh we can't use an array because we have an infinite range for everything but now the interviewer has given us a finite range that we can use for our numbers and this is very crucial important information for us to utilize because if we are just using a hashmap where the keys represent like the specific numbers and the value is just the counts of our keys we can represent that entire thing utilizing just an array okay and the way we would do this is we would have an array and i'll call this uh scene okay so scene equals new int and the number that's gonna the number of spots that our inter array is gonna hold is going to be all the numbers that could be represented that could be in this numbs array so basically if we had three spots here i would just have an interra of size or of length three well actually i guess in this case it would be length four because we're not zero indexing our first number starts at one right so i'd have an inter array of length four where each index represents the uh the number in our nums array all right this is the equivalent to the keys in our hash map and the value that each index is going to hold is going to be the counts of each of those numbers so let's just say once again i'm going to have a simple example here for this example number one we only have one two and three so i basically have an array of size of length four and at the f when i initialize my first window i just have uh at index one i place a value of one at index two value one index three value of one and before i shift my window i just decrement what my start pointer is pointing to so on index one i just decrement my value of one back to zero and then i shift my window over and then my end pointer is now pointing to this so i would just uh increment the value of index two by one right so index two before had a value of just one now with this additional two it would have a value of two right so i just keep doing that until i'm done with my numbers array so uh you know it's all the increments and decrements that we do in our hash map can be replaced with you know the array equivalent so kind of going back here what is going to be the length of our inter ray well since we are going up to 100 000 elements oh sorry 100 000 elements and since we're indexing at one we're not zero indexing i'm going to have my length be hundred thousand and one okay and the reason like i said the reason we're doing the one is because we are not zero indexing here so now all of the increments and uh decrements that we're doing we can do the array equivalent so here we're putting the nums of index i and we're adding one to the current value or the current key so all i would do here for the array equivalent is i do seen and since the key is going to be the index of our uh array i'd say scene at index of nums i plus okay and i just increment one and now i don't need this line anymore so i'm going to delete that okay and uh where else am i decrementing or incrementing okay i see here counts dot puts numbs start uh nums at index start and we're decrementing here so all i would do in my scene array is i just do scene nums and i do that index start minus so i'm decrementing there right so there we go i'm removing that and now uh the last thing the last uh place where we're incrementing or decrementing is right here so once again i would just do scene numbs and plus now i can delete this line so okay we can add elements to our window and we can uh delete elements from our window pretty quickly pretty efficiently the last thing we got to consider and the real question becomes how can i get the number of distinct elements using an array now this one is a little hard to see in the beginning but it can be done with an array and i'll let you guys if you guys don't know i'll let you guys pause think about it for a little bit and you know unpause whenever you're ready but in this situation when we're using an array let's think about like when would we have a distinct element okay so let's see this example right here now before at each of these indexes right at each of these indices of one two and three we had a value of zero now after we add all these values into our array they get a value of one right so it looks like whenever we're adding an element and changing the value from it from a value of zero to one that's when we get a cool new distinct element and like we did with the hashmap anytime we decremented a value and we got zero we removed it from our hash map so in the same way here if we were to decrement a value and it became zero uh we basically need to like subtract one from our total number of distinct elements that we have so if you guys are somewhat following this method we could represent the distinct number of elements using a another like a temporary variable and i'll just call this variable count okay and i'll set it equal to zero in the beginning so all i'm going to do is when we're initializing our uh our initial window if seen at index of nums i so basically if that number currently has a value of zero right uh then i'm going to increment our count so in our and when we're initializing our window uh what does that mean so here right we're looking at uh the value one in our array right it currently has a value of zero before we increment to it before we increment that value by one we're going to increment our count which is going to hold the distinct number of values at each window okay so our count is going to increment by one then we're going to look at two and once again since uh two has a value of zero before we increments it we're going to increment our count by one so that's also going to be the count is going to be two now and say for the same reason for uh number three here our count is going to be three now let's contrast this with uh example number two okay here we have four ones in the beginning so our initial window is going to be these four numbers right so on our first iteration we look at this one now in our array since we haven't added anything to it yet right the value of uh at index one is gonna be zero so before we increment it we're gonna check hey is the value zero uh in this case it is so we're gonna increment our count to one now i'm going to look at this one okay so it's going to check hey is the value at index one zero well no since we just incremented by uh one in the previous iteration it's currently at one right now so i'm not going to add to the count variable which is gonna once again hold the distinct number of elements that we have um so it's basically gonna skip this and it's gonna it's just gonna keep incrementing uh our array so this is a really cool way where we can keep account of all of our distinct elements and um just like we did in our hash map when we removed uh an element you know completely from our hashmap we're going to do the same thing with our array and with our temporary variable so all i'm going to say is if seen at the index of uh you know start because since we're removing the start index or the value of the start index all i'm going to do is at the index of that start index if that value equals 0 after i decrement it what am i going to want to do i'm going to want to delete it or basically remove that value from the total number of distinct counts that we're looking at so the way i would do that is i just say counts or count minus okay i'm decrementing from my count so by doing this you know this is like a really nifty way of once like once again holding on to the number of distinct elements at each window the last thing we'd have to do is since we're uh you know holding on to the number of distinct elements using the count variable i would just have to replace this counts.sizeline with counts.sizeline with counts.sizeline with count and that's it and this way i don't even need a hashmap and this is much more efficient than utilizing a hashmap okay so now let me run this make sure i don't make any errors oh okay so we've made a little error here let me see where am i did i forget to increment my account some oh yeah look at this guys i almost forgot sorry about that so here after i increment my end uh pointer i'm adding whatever my end pointer is pointing to my array so before this let me just do a quick check let me see if it's a distinct number that we're adding okay so all i'm going to do is if seen nums end equals equal 0. just like we did right uh up here right if it's zero that means uh it's a distinct value so before we increment that value let's just increment our overall distinct number of values that we're holding which is held in our account variable and um okay i think that is the last piece i need for this problem and boom all right look at that accepted hopefully this is uh this is right i'm gonna submit this now and we're gonna notice something very cool we noticed that we are significantly faster than we were before util by just swapping our hash map to just this array that we have right here you know that is how we're going to do this problem and now let's talk about the time and space complexity okay so with the sliding window technique it's very efficient we're actually doing this whole sliding window thing in all of end time complexity and for space complexity well let's see where am i allocating space well it looks like i'm allocating extra storage uh for the scene array now remember uh when you're trying to calculate space complexity you never include your uh return storage okay so i'm not even going to look at this answer but we're only really holding n elements right like even though this is holding like a hundred thousand and one spots right we're not actually utilizing every one of those one hundred thousand and one spots in our like while we're going through our uh implementation here we're only utilizing like what's in our uh like our nums array and what i say what we're utilizing i mean like we're only incrementing and decrementing um the n spaces that are in our nums array so for that reason i believe that the space complexity is also o of n uh but let me know what you guys think about that one because i'm interested to see if anyone thinks it's an o of one space complexity because like because we are only using like this like i don't know i feel like it's oven but i feel like i've also seen situations where like i've held like the alphabet like only 26 spots in the alphabet into space complexity and that's technically all of one since we're not like changing anything but yeah i think it's all been in this case though uh but let me know what you guys think um and you know that's how you do this problem guys hopefully you guys found some value hopefully you guys learned how to do this exciting window thing with what the hashmap and an array hope there's a lot of things that we could have learned from this problem um and you know just let me know what you enjoyed about it let me know if there's any other problem you'd like to see done and as always you know always feel free to smash that like button and smash that subscribe button be a part of this family uh you know i'd really appreciate that but you know other than that you guys have a great rest of the day and i'll see you guys next time you
|
Distinct Numbers in Each Subarray
|
biggest-window-between-visits
|
Given an integer array `nums` and an integer `k`, you are asked to construct the array `ans` of size `n-k+1` where `ans[i]` is the number of **distinct** numbers in the subarray `nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]]`.
Return _the array_ `ans`.
**Example 1:**
**Input:** nums = \[1,2,3,2,2,1,3\], k = 3
**Output:** \[3,2,2,2,3\]
**Explanation:** The number of distinct elements in each subarray goes as follows:
- nums\[0:2\] = \[1,2,3\] so ans\[0\] = 3
- nums\[1:3\] = \[2,3,2\] so ans\[1\] = 2
- nums\[2:4\] = \[3,2,2\] so ans\[2\] = 2
- nums\[3:5\] = \[2,2,1\] so ans\[3\] = 2
- nums\[4:6\] = \[2,1,3\] so ans\[4\] = 3
**Example 2:**
**Input:** nums = \[1,1,1,1,2,3,4\], k = 4
**Output:** \[1,2,3,4\]
**Explanation:** The number of distinct elements in each subarray goes as follows:
- nums\[0:3\] = \[1,1,1,1\] so ans\[0\] = 1
- nums\[1:4\] = \[1,1,1,2\] so ans\[1\] = 2
- nums\[2:5\] = \[1,1,2,3\] so ans\[2\] = 3
- nums\[3:6\] = \[1,2,3,4\] so ans\[3\] = 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `1 <= nums[i] <= 105`
| null |
Database
|
Medium
|
2370
|
513 |
I don't know what's up with lead code medium questions are easy questions are medium hi guys good morning welcome back to a new video in this problem find bottom left tree value again it's marked as medium but it's a very easy problem so yeah let's start off it has been asked by Amazon and Microsoft in last one to two years so not that important but still let's see it's good for understanding basic concepts of graphs entries as mostly algorithms of trees and graphs cool uh it says that okay you're given the root of the binary tree and you have to return the leftmost value in the last row of that tree now for sure we do the exact same stuff we will go on to the last row and then we'll go on and only go to the leftmost value first as we go on to every row because again our ultimate aim m is that we have to go onto every Row one by one and on every row if I'm going I will make sure that I will only go on to my leftmost value right so let's say if this is a tree I have expanded a tree bit more so you can see my main aim is last row because I have to reach the last row but in that my main aim is the leftmost value so answer is eight for this now for sure for this what we can do one thing is okay I will try to go to the last row but again which means I will go on to every depth I'll keep on going but I'll also make sure I'm only going on the left okay left but Aran left it's here okay a simple DF basically we doing a simple tree traversal to go to the maximum depth okay AR so you said that you want to go to left only so okay you went left is it good no I will keep on going okay maybe this is answer I will right now initially store this as my answer but maybe I can improvise my answer so right now my let's it depth is one cool now again a DF it will go back to parent and then go back to this right child so it will go back go here two again it is at the same depth as of one so it is not a good candidate for my leftmost bottom left most child okay then I'll go to my left okay depth increased depth is two so now this is my new candidate okay now three is my bottom left most value now updated again let's say answer is bottom left value for me earlier it was three sorry earlier it was 1 now it is three okay then again I will go fall to my left yeah depth again increased again depth again increased it did not remain same it increased then okay I'll update my answer it is six now I cannot go left okay I'll go back and then do a right traversal then depth is still same so answer will not increase depth okay left is not like left is nothing so it go right depth increased bro depth increased so answer up to eight okay parent two then right depth is still less than my existing depth because see I will keep track of the maximum depth I have reached four so any depth after four because when I was here maximum depth was three so any depth after three was the one candidate with whom I updated my answer which is the bottom left most value and then here is the depth two depth three depth four so answer will not increase or not changed so you saw that I'm going on to the I'm going on and trying on going on depth and at every depth if depth increases it means my existing depth is more than my maximum depth which I've got so far then I will update my answer is my bottom left value and this is I'll keep on going on the depth increasing the depth and then only go on the left value first so that I update my left value and say okay this is the leftmost value so code is exactly same that firstly I initialize two Global variables max depth and bottom left value and initialize with them minus one and 0 respectively you can also say depth as like say minus one is so far your bottom left value has not been updated yet or you can also put the root value here and a zero here both will work but still uh don't put headache put a default less values or you can also put minus one here no worries now I'll do a simple DFS traversal but in that I know one thing that I will keep track of the depth right and if my depth is more than my maximum depth so far I've obtained I update my maximum depth and I ALS update my bottom left value because I know I am first going on to my left and then I'm going on to my right so for sure if depth is increasing and I know it is the left person first on whom I'm going so for sure I will be updating the left value itself bottommost is by depth left value is because of left value I'm going on to First cool let's see if I have asked you what is the right value so you would have just modified it you would have put this right one first and left one downwards this is how you would have reached onto the bottommost left value and let's say if I asked you at a specific level give me the rightmost value then also you could have modified that cool now um ultimately you will populate your bottom left value with the left most value of the maximum depth and then return that value as you know it's a simple DFS traversal so in the worst case you can go on to every node and for sure you are going to all the nodes so for sure the time is O of n and if the trees is skewed so space is of n now we solve with the simple DFS but we can do the exact same stuff by via a BFS also but again BFS is much more short simple and easy BFS is also easy no worries uh it's just that we do exact same stuff as we saw above that we have to go into the last row and again we'll keep on going and grabbing the leftmost element so exact same stuff let's say if I am here I will again how a BFS work it is it goes level wise okay I know for sure if I'm going on to the next level depth is increasing so I can keep track of the okay this is my depth is zero next level is this depth is one depth is two depth is three depth is four so as you know in a q like BFS us a q in a q you push the elements okay I'll push the elements one two so basically in this specific Q elements will be pushed 1 two in this Q 3 five in this Q 6 s and n in this Q 8 and 10 in this Q only four so and I can just simply grab out the Q elements so I know if my depth is increasing so the first element I grab out from the Q will be my answer right so I'll do the exact same stuff as I saw above also that I'll keep track of the maximum depth and bottom left value again depth is this specific depth which you saw here itself okay where is the gone this is the depth which you passed in as you can see this goes into your recursive call cool now uh exact same stuff initially you push just the root element in the que then while your que is not empty you go on and check okay for this current level okay in a BFS you say level and in a DFS you use depth but yeah in current depth or level you have these many number of elements in your Cube so please remove all the elements first and then go on to the next step so initially it is my first level which means one of the levels is being done so I increase my depth and then this is a simple BFS traval in which you pop out the front element and then you go on to your left and then you go on to your right as simple as that how a simple BFS works just exact same thing we have wrote if your maximum depth is less than the depth itself then update the maximum depth and also grab the bottom leftmost value because how it will happen that this is the new depth which you have formed if the depth has increased which means you are at a new level so the leftmost element which it will be the first element which you will be popping out from your queue itself and that first element which you will pop out from the que at a new level or at a new depth will be your leftmost value let's say if I go on to the next step so okay it is a new depth it is a new candidate for me so earlier right as you saw above my answer was a four in the very beginning which means bottom left for Value it got updated to a one this is a new candidate then a three is a new candidate then a six is a new candidate then I a is a final candidate for my answer and this is my answer itself cool and as you can see exact same stuff we have written and done by BFS although I'll say DFS is much more what I prefer again it's a totally up to you that if you want to do a DFS or DFS cool thank for watching goodbye take care byebye again I don't know why yesterday's question I it's my thought yesterday's question was actually medium and this is actually easy to think and to implement in both ways bye-bye
|
Find Bottom Left Tree Value
|
find-bottom-left-tree-value
|
Given the `root` of a binary tree, return the leftmost value in the last row of the tree.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,2,3,4,null,5,6,null,null,7\]
**Output:** 7
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
338 |
Today we will solve the next problem of Blind 75 which is called Counting Bits. So first of all let us see its problem statement. Return and Answer are of length n + 1 true date Return and Answer are of length n + 1 true date Return and Answer are of length n + 1 true date i > i > i > both are inclusive and answer i is d number of times in the binary. Representation of I is okay so if our n = 2 then in zero so now our n = 2 then in zero so now our n = 2 then in zero so now our number will be zero so give one in one and give one in you give one in 5 then one in one you one in three two in four you are okay so this Let's try to solve it but the basic concept of it is that when I divide by you then what happens to me. If my number is in the number then what is my 10 then see from here if I divide by you. So my last beat which was I will joke by one so this is my this will be truncated and my number which is this will go back so what is the number 101 so what is it telling that when my N is if I divide it by you If I do this then my right is dropped, okay, before this I get to know about it, now he has given me a problem and I have to make a return, so now one thing we have set above is that if my N is I Now I don't know which beat was last, I don't know that beat by zero. If I divide 10 by you right, it means it will be as much as me in ny2. There are also set bits, that number will definitely be there in N. This is correct, this is known because we have kept that number because this is my invite, so my number will be there in the invite, but now Sir, this is my last beat. It is getting truncated but when will that bit be set? When my N is odd, then the formula we have given is F of N = Right. So son, what did we say that all the set bits are there in our N which is The set weight of I is the same as what is in our list plus our I is there or not, this is the problem. Okay, let's see, it is 200. Let's submit it and see. Okay, see you next.
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
261 |
hey how's it going guys so today i'll quickly go over my solution to lee codes graph value tree problem of 261 okay give an endnotes label from 0 to n minus 1 and a list of undirected edges each edge is a pair of nodes write a function to check whether these edges makes up a valid tree uh so example one we're given uh four nodes so node zero one two three four and add edgeless adder as uh zero one zero two zero three one four and we output two because it's a valid tree so um i draw the tr like the graph here so you can see that zero is connected to one they're connected to two they're connected to three and one connected to four and we can see that this is uh a valid tree right uh although it's not a binary tree because it has like three um branches at here it's not a binary tree but it's still a tree and uh this i draw uh example two so we are also given m equal to five so zero one two three four as our nodes and our edge lists are zero to one two three uh one two three one to four and you your graph looks like this and uh it's not a valid treat because um because we know in the tree there should not be any cycles right so basically uh so the question asks us to output true if it's a valid tree and false if it's not valid tree so we output true for this and upward false for this um and we can see that if there is a cycle it's not a valid tree okay so this question become a cycle detection problem if there is a cycle in the graph output false if there is no cycle in the graph let's say here we don't have this edge is this uh there is no cycle in the graphics it's is this a valid tree no it's not because it's not connected together so our two condition is one no cycle two uh one connected component okay so these are the two uh two like a determination or two criteria for uh not tree uh for a tree okay let's first think about how to detect a cycle uh because detecting whether it's a connected component is very easy because we can just traverse the tree using like a dfs or a bfs and then mark each node as visited and at the end we just need to return whether the node the set the visited is equal to and to the number of nodes if it's the same like for this example it's the same as four then it can be one connected component however if it's like here and when we traverse this it give us three uh visited uh note in the set and the three is not equal to and uh oh sorry this will give us four it's not equal to our given n which is five so we will return false in this condition uh so that's easy so how the most important question in this uh question is how can we detect a cycle whether a cycle exists there are many different ways there are union find dfs and bfs today i will just introduce the dfs i think uh it makes sense so what that do is that first you create the graph right because we are all only given edge list and uh and it's not easy for us to know the node's neighbors so would rather create a uh graph so it's uh it's marking the note to its uh neighbors yeah so that's what i did here and once we've done that we just need to do a dfs and uh this is just a dfs uh like a template so how does that work so basically we have a stack and we append the zero node to the stack we append the node and its parent to the stack so for example when we visit here we'll mark zero minus one zero being the node we are currently at and minus one being the parent and we initialize the set as an empty set so we pop while stack and again this is just uh like a dfs basic template so if you're not familiar with dfs traversal using a stack then you probably should watch more tutorial on that first so basically we have a stack and we say while stack we pop the current element and this parent out of the stack so right now we pop zero and minus one out of the stack and we add the current node into the sync uh sync set so we mark this as visited okay so and we go back to our uh graph and we get all the neighbors and for neighbors in g current so we get all the neighbors out so if the neighbors is not seen we add it to the stack this is again uh like uh the basic uh dfs template right so like here because one is not visited then we add it into our stack we add the neighbor itself and the current meaning the parent because right here for one zero will be its parent right and uh like a because it's a dfs so it will traverse to two uh for the next thing so here we add tooth pattern which is one
|
Graph Valid Tree
|
graph-valid-tree
|
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph.
Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\]
**Output:** true
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\]
**Output:** false
**Constraints:**
* `1 <= n <= 2000`
* `0 <= edges.length <= 5000`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* There are no self-loops or repeated edges.
|
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
|
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Medium
|
207,323,871
|
297 |
all right we are doing the top 75 leak code questions from team blind and we are currently on number 297 serialize and deserialize binary tree so the problem is asking us to define two methods of the codec class serialize and deserialize the goal of the serialize method is to take as input a root node of a binary tree and you can see the node class is defined here and what we will be doing is serializing it into a stream of bits or really in this problem just a string such that it can later be read by the deserialized method which can reconstruct that binary tree as an object in memory again so like many tree problems this can be done recursively and what we're going to do specifically is implement a pre-order traversal is implement a pre-order traversal is implement a pre-order traversal to serialize the string as our first step or serialize the tree as our first step so what i mean by that is what it's going to look like is if you look at the example one here's our tree so one will be the input root node by pre-order traversal pre-order traversal pre-order traversal what i mean by that is that we're essentially adding the current node to our output string before we recursively call on the left and right subtrees so first we're going to add one then we'll recursively call left and we'll go to we'll add two and then we'll recursively call left and we add none that's the left child as a null then we look at the right child of two we get null then we go back up the call stack to one and then now it's time to call the right child so we do three and then you'll see the pattern here four null five oops five ah five no okay so that will be the output of our serialized method and that will essentially be a pre-order and that will essentially be a pre-order and that will essentially be a pre-order traversal of the binary tree so let's give it a shot first for recursive method we're going to find our base case if root or sorry if not root and this is not just going to be simply a return but return the string null because as i showed in the example here we need some sort of output in our string to signify to our deserialized method that this node has a no child here so next we're going to handle our standard case and this is where we do our left and right subtrees so we're going to say left equals so serialize root left right equals self serialize dot right and then we're going to finally return uh dot l what we need to turn into a string first daval comma separated and it doesn't have to be comma separated but that's simply what i'm choosing to do is my delimiter right next we need to implement our deserialize method so let's look at our example string that we constructed here how should we do this so first thing we're going to want to do is understand that we are going to be implementing this recursively so let's define a quick placeholder here and then how we're actually going to approach this so the first thing we're going to do is take this input string and parse it into a list which is going to allow us to not split it on the commas which is going to allow us to iterate over that list of values more easily and in order to facilitate that iteration we're going to make it an iterable this way instead of just handling an awkward string object where we have to look at characters or you know use slices and slice notation and it can get messy we can simply just have a nice clean list that's iterable so now that we have this iterator what we're going to do is um simply return recurs and so what and then now we need to do the final step of actually implementing this freeze course method so this is going to return a tree node object and it's going to be our root node but first we need to find our base case the base case is going to be if or first we need to sorry yeah base case node equals next we'll also grab the next item from the iterable vowels and i'll just call this val because that's really what it is i'm going to say if val equals null remember up here that signifies that there's no child we can stop adding nodes to that particular path on the binary tree so in that case we would simply return right otherwise we're going to say node we're going to create a new instance of the tree node as defined up here and we will say tree node val and now we need to define what's this left child what's left child as defined in the periodic traversal is going to be the next value so we'll simply say recurse the right child is going to be the same thing because as you can see as defined in the period of reversal two's left child and right child are the next two values so then we'll say recurs finally we'll return node so let's give this a shot looks like it works for the first example case let's try an empty input it's always a good habit to go through various edge cases here works for the single element let's give it a shot last test case and if you want to be really thorough you can invent a few of your own however i've done this problem before so i'm feeling pretty confident i'm going to go ahead and submit and there we go boom shakalaka
|
Serialize and Deserialize Binary Tree
|
serialize-and-deserialize-binary-tree
|
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,2,3,null,null,4,5\]
**Output:** \[1,2,3,null,null,4,5\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
271,449,652,765
|
83 |
hey guys so this is problem 83 remove duplicates from sorted list right it is an easy problem and uh let's start with the problem statement so given the head of a sorted list so first of all the thing that has to be mentioned here that is mentioned here is that the list is going to be a sorted list so okay so delete all the duplicates such that each element appears only once right so look at the question look at the solution part so you are given with the list node ahead so a list is there whose head is given to you as a parameter of this function and what do you have to return so you have to return the very head of the new list that you'll be making right new list or maybe you can manipulate the same list also that is up to you of course in our case we are going to manipulate the same list right using some pointers or something like that so let's discuss this approach first so that you'll get a very clear glimpse of the question so see suppose this is our list okay and what do we have to return something of this sort that the element whichever are repeated only one occurrence of such element will be considered okay so one is repeated twice only once we have to count it again 2 is repeated four times so only one time it will be counted right three is only one time so in the result also it will be one time then 4 is repeated twice so one occurrences occurrence of four and similarly five is one time so in our final list also it will be one time so this final list is what we have to uh basically return right so what is going what is what will be the approach that we'll be using and let's consider that at the moment okay so let's remove this first okay so right now we are given with this head you know so this head has been given to us the very initial node so we're going to use two pointers here first pointer will be our previous pointer and the second will be current previous will tell us the part of the list which already has been uh the rules have been applied to and the current pointer basically will tell that what is the current node you're working on or you are checking the conditions for right so these two pointers are what we're going to use here so initially I'll make the pointers to point to very first node right so previous is also pointing here and current is also pointing here because the list is sorted so one thing is very clear that if there is a reputation then that has to be the subsequent element only it will not happen that two of the ones are here and then after the list also one is here it will not happen right all the occurrences will be together so if 2 is repeated every occurrence will be the subsequent occurrence only it will not happen that uh 2 times 2 is appearing at the first part of the list and then other twos are appearing in the last segment of the list it will not happen right because they are sorted already so this thing is clear now we can move on to the implementation or the logic that we are going to use in this question right so current and previous both are pointing to the first uh node right the condition that we have to check here is that if current dot next dot well is equals to current dot well or not based on this condition we'll be applying some rules here right so first of all we'll check so the first for first current we will check the first nodes value that is one the second node that is current dot next dot val is also equals to one this time this is equal so what do we have to do when the subsequent nodes are equal we have to just move the current pointer right will not move the previous we'll move current right again we'll check for the condition if they're equal or not this time they are not equal right that is 1 and 2 are not equal so first thing is that whenever the current dot next dot val and current.val are equal we have to val and current.val are equal we have to val and current.val are equal we have to Loop right we have to use a loop to check that how many such elements are there so just after finishing this Loop the arrangement that we'll be making here is that we will be setting previous right so I'll use a different color so we'll be setting uh previous dot next to be current dot next right so here after finishing the loop we'll be making some adjustments also that will be previous Dot next should be equals to current dot next right so this link will be set up here and then we'll see so this link is gone now and then we'll say that current dot next not current.next but current is equals not current.next but current is equals not current.next but current is equals to current dot next so now current will Point here okay again we'll check for the condition so this if is now over so first we checked for the if condition if it is true then we'll Loop through it like how many such elements are there that are repeated so if there are more than one more than two of the ones then we'll Loop through it that how many such elements are there we'll cover them all and after covering them all then we'll make such type of rearrangements right of the links then again we'll start with the same condition that are the current dot next dot well that is 2 is it equals to current dot 12 that is 2 yes it is equal so again you have to Loop through it right so change current to current dot next and then again check so right now we are just looping through it that how many such elements are there which are repeated so again we'll check for current and current dot next again they are equal to just move this current again you have to check for current uh you have to check for current dot next and such things so these two values are also equal so you have to move this current again you have to check so this time they are not equal so whenever these are not equal then you cannot basically uh you know you cannot move this current you have to stop here and now you have to again make the Readjustment so the previous right now was here right previous basically at the moment was here right we have changed the previous I have not written it but now previous is also equals to previous dot next this step has to be followed so previous at the moment is here right and again the same uh three statements have to be uh you know executed that is previous dot next equals to current dot next so previous dot next is equals to current dot next current is equals to current next so now current will Point here and previous equals to previous next so previous is also here right again you have to start comparing so this time we compared current and current next there they were not equal whenever they are not equal you have to just execute simple things that are current equals to current next and previous is equals to current so they'll be pointing to this on the same node so previous is also there and current is also here again they are equal so you have to Loop through the Elements which are equal right so current will be moved to 4 again you will be comparing they are not equal you will stop here so right now current is here previous is here now what we have to do is these three statements the previous dot next is equals to current dot next so this then current is equals to current next so current will come here and previous equals to previous next that is previous is also here now and of course now as the list is over so we can stop so after looking at the list you can make one thing very so you can basically now return the head which is basically is going to be the same head but now the because of this Readjustment of the links the new list would look something like this that is one is here then this rearrangement of the link has been made so now two will come next and after two this link was removed and the new link was set up that is three so three will come here then after three four and you can see that after this link this new link was formed this was removed so directly 5 is there this is our new list so the same thing if you'll come in the solution part wherein I'll be coding you'll see that how simple implementation uh will be there if you want to try or you can also try by pausing this video right because you have got a you know inside key how this problem has to be solved so you can try it by yourself also otherwise I'm going to implement it right now so you can check for it so first of all we have to need we need these two pointers right uh those were first one was current which was pointing to head again and second pointer was list node previous which was also pointing to head right these two pointer we need and afterwards what do we need now so basically a loop which will be looping on whole of the list so while head is not equals to null until then we can check for some conditions the first condition was this that is head if so we are traversing using current so we cannot use a head of course so until current is not equational till then we have to Loop through the list right so the first condition that we are checking is that if current dot next is not equals to null so this is The Edge case right and if it is not equals to null then we have to check for the values if current dot well is equals to current dot next dot well so agree condition if it is satisfied then what do we have to Loop through the list until we found a you know distinct element so while the same condition we can use for Loop also right so while this condition is being followed until then what we have to do is that we have to move this current pointer to current dot next so that's it so current is equals to current dot next right a simple incrementation increment is being done here and just after the that thing is finished then we can set our previous dot next to current dot next and the secondary Arrangement will be that current dot current is equals to current dot next and now you can move your previous to your current two right and if this is not the case right if this is not the case that is the values are not equal then what do we have to do then you can just simply say that current is equals to previous dot next or you can say that current is equals to previous wherein previous has been shifted to previous next so something like this right and that's it so the whole Loop will the whole you know Loop will work until you are not getting current as your null and after getting that you can return the head right which will be same as the previous head so yeah see we'll be returning our head and that's it now we will submit the code let's see if some test cases are there which are not following it so all the test cases are following it of course so yeah that's it so yes so basically after doing this problem you can jump on for the next jump on to the next problem that is problem number 82 which is also the same thing right we have just solved it in some other video also so you can take reference from there so you can start solving it by yourself first and afterwards you can take reference from that video I'll show you the problem number also so it is problem 82 which you can try right so it is also following the same thing just with a few changes so try for these both these two problems I hope that you'll uh you understood the concept well if you do so please check out for other videos also so thank you
|
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
|
1,189 |
hello let's do this easy question today uh maximum number of balloons are you given a string text and you want to find out how many times can you write the word balloon out of the characters from text and can use each character only once so like for example in example two you have a b you have two b's you have two a's you have four l's four o's and two ends that means you can make two balloons so i guess the maximum number of balloons i can make would be if i count the frequencies of each of the characters a l o and n and then i just take the min frequency out of all those i have to be careful because l and the o i need two of those per balloon so let's just count the frequencies of these letters and we have a vector of int frequency and initialize it 26 characters maybe have a string balloon is equal to balloon go through each character in the text and just increment the frequency of c minus a then you go through each character of the balloon keep track of an answer which i'll initialize to the max it max so something very large and say that the answer well let's here let's take care of the case where there's where for l and o we need two of those per balloon let's say the frequency f is equal to the frequency of c minus a if c is equal to l or c is equal to o that means i want to divide the frequency by two and then say the answer is equal to the min of the answer and the frequency and at the end return answer something like that cool let's submit that i yeah thanks for watching like and subscribe and i'll see you in the next video
|
Maximum Number of Balloons
|
encode-number
|
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only.
|
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
|
Math,String,Bit Manipulation
|
Medium
|
1070
|
103 |
today we're looking at lead code number 103 binary tree zigzag level order traversal this is a continuation on the series of level order traversal questions that we have in this playlist it's going to use the same exact pattern as we use for binary tree level order traversal 1 and 2 as well as n area tree level order traversal so anything level order we're going to use this template which is very powerful and here we're just going to make a slight modification that template and we'll be able to solve this okay so here we're given a root of a binary tree we want to return the zigzag level order traversal of its node's values so from left to right then right to left for the next level and alternate between so here our zeroth level is three nine and twenty we're going to alternate that we're gonna reverse that uh from 20 to nine here and then 15 and seven remains the same so we're zigzagging reversing on every other level okay and nodes are between 0 and 2000 and the values are minus 100 to 100 okay so what we're going to do here is we're going to use a q and we're going to use two while loops and then we'll just make some slight modifications that i'll explain in the code but i'll just go over the basic template and again if you're not familiar with this and it's still confusing after this video check out the other videos dealing with level order traversal just do a few of these it'll get solidified and then it'll be great you'll be able to solve all of these really easily okay so the first thing we want to do is we want to initialize a q okay we want to initialize the q and we want to set the root which is what we're going to get into that q so the initial value is just going to be 3. and we can see here we have level 0 1 and 2. when we initialize that 3 into the q we have the value for the zeroth level okay so now we have this we have these two while loops here and while there is something in the queue so while the queue is not empty what we want to do is check what is the length of this queue at that moment okay and we want to save that into a variable so the length here right now is 1. now because we have this in our queue this value in our queue for the zeroth level we just want to make a copy of that and push it into our result okay so we'll go ahead and take that three push it into our result and now we have our zeroth zero at the level now we're going to go into this inner while loop and we're gonna uh check what is the len here we're gonna do it len times and so it's one so now what we'll do is we'll pull off that three off of the queue and push in any of its children in back into the queue so for 3 on the left we have 9 and on the right we have 20 so we'll push in 9 and we'll push in 20. and then we break out of this while loop because we decrement this 1 to 0 and it will break out of that inner while loop and now we're back in the outer while loop okay and so now we can see that this 9 and 20 is all the values we need for our second level and so now we do the same thing we go ahead and save the length of the queue at that moment in len so it's going to be 2 we then make a copy of whatever's in the queue currently and push that into an array and push that into the result array so that sub array of 9 and 20 will get pushed into the outer array the parent array of result and now we go into our while loop our inner loop and we just run it twice okay so we you know we shift off this nine we check if there's any children there's not uh we just move it we go ahead and decrement this lend a one and then we pull off this uh 20 and we push its children back into the queue so we're going to have 15 and 7. and the len will now decrement to zero it'll break out of that inner while loop and we rinse and repeat okay so now we're back into our outer while loop and we have the correct level numbers 15 and 7 make a copy of that put it into our result we save the length which is 2 and then we go into our inner while loop 15 or 7 does not have any children so we shift off 15 shift off seven there's nothing that goes back into the queue and now when we get back to our outer loop the queue is empty so we break out of our outer loop and then we have our semi-result now all we want to our semi-result now all we want to our semi-result now all we want to do is make a slight modification is when we are pushing into the result we can creep we can keep a counter set it to zero and then just check if it's even then go ahead and put in whatever the order is at the time and if the counter is odd then just reverse it reverse when we push into here just reverse that array and so we just make that slight modification that's all we need to do to get that zigzag property for this question okay so let's jump into the code so as always first we want to check we want to address our edge case if we don't get a root so we'll say if root is null then we just return an empty array and now we want to go and initialize our cube and we'll go ahead and place our root into that queue and then we want to initialize our result set it to an empty array and then we want to initialize a count okay and we'll just set it to zero as an initial value so now we want to do while the queue is not empty okay what do we want to store the len the length of the queue into a variable okay and now what do we want to check if the count is even or odd okay so if count mod 2 equals 0 if it's even then we don't do any we just take whatever's in our queue and push that into result so we'll just do result.push q.map node q.map node q.map node.val the reason we're doing that is node.val the reason we're doing that is node.val the reason we're doing that is because this question wants not the nodes but the values in the nodes in our result and else we just reverse it do result.push else we just reverse it do result.push else we just reverse it do result.push q dot map node.val and then just do a dot reverse okay and then just want to make sure we increment our count so that'll take care of the zigzagging that we needed to happen and now we just want to address our inner loop so we just want to do y len minus it's just going to decrement on each iteration when length equals 0 it'll coerce the falsie and will break out of that inner loop so that's all that's happening there we're going to shift off our node so node is going to equal q dot shift and now we just want to do if no dot left then push that value into the queue okay and just same thing if no dot right we push that value into the queue okay and then we just return our result all right and that's it let's go ahead and run this and we're good okay let's talk about time and space complexity so here's the thing i know there's two while loops and it may be tempting to think that this is you know n squared but when you really think about it's not n squared it's actually linear time because you have to ask yourself how many times are we actually touching each of these nodes right we're only touching it once it's just that we're doing it level by level so we're breaking up these iterations level by level but if we're only just traversing it once so our time complexity here use yellow here our time complexity is going to be o of n on time and then space how big does the result get relative to the size of the input it's just the same size so it's n so if n is five uh the length of or the amount of nodes or the values in result is also going to be five so this is also just going to be linear on space okay so that's binary tree zigzag level order traversal i highly recommend checking out the other videos dealing with level order once you just kind of go through a few of these it just really gets solidified and it builds your confidence you can you know solve a lot of these types of questions really quickly when you have a pattern that you can refer to okay that's lead code 103 hope you enjoyed it and i will see everyone on the next one
|
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
|
382 |
The festival today we will discuss the network problem number is 382 problem is click please channel note what is it that we have the thing listed ok and what we have to do is to set a friend value and that random note why value Less than retaining I rental value this contingent back if and come back to my channel between Dhawan and its size which previous if advance and will ask means that which is 2019 that bank has to be returned from two to the bottom Amazon Value If Control Is Broken Return White If You Indulge In Fixing If You Like To Talk If Our Festival Is Okay Then There Was A Loss If There Is 6 Damage Then Return It We Will Clear This Question And Let Us Rest Like This Kundli property of one number is only difficult, it reaches only this, but within the edit question, all the alarms are set that we have to switch on friend mode to increase two functions. What to do in this matter said that whatever you see, you can do it. Remember that your thing is edit convert it into release friends and the exam of adam function is that it will print each number of calendar leaves and click on that thing and that is not physically present let's see so what we will do Whatever issue we will take, the administrator will make it clear to us, okay, let us make this issue above, challenge, it is ok, it is a style, see the teaser, we have placed it, we have converted it in between to say water, we have not given its name. I am right now daily we put viral why hey guys not difficult will be appointed until it red like is doing a point what will we do with this paste ear dar add it subscribe the channel like share Subscribe to the channel and subscribing will see this water in this regard. Will you subscribe to the cattle? Will you make them an assistant? Okay, now look, we will test it. Okay, today's point will test my name, here temple loop is needed, decision. Have done us dandruff function amazon you search this it got amazon right now I festival function in get up a platform what is the time that is a function in java I am chart friend that I am dot friends this companies 280 prohibits means thing absconded Till this will be a small off butt from the darkness, okay then it will quickly make the number karegaa2000 and our balance is our 10 mode, so what do we have to do in multiplying, how many Adams i.e. as multiplying, how many Adams i.e. as multiplying, how many Adams i.e. as many as on the side of Everest, we will put servi in it, many as on the side of Everest, we will put servi in it, many as on the side of Everest, we will put servi in it, we will always solve this problem. Repairs that in Japan we will know about typecast per liter hearing specific tank, set this Redmi, which roast to edit, is a friend, what am I, so I turn on some simple Thursday that if we If we talk about time compressed, then see here how much is its test and here is the quick and subscribe. Okay, if you talk about ghagra, then friends, we are porn books, it's too much time for us, and if this is done, then you and I are like that. People say if we watch it then subscribe and what happens in this piece but this minute whole thing is much better and it sticks lightly and there is option problem if our channel opens up gray hairs, it will be tightened, it will turn off and if it For us, if we do it with the best application, then its time is right, so how did it feel sweeter in Cardiff? If you want this problem option on the website also, we will definitely tell you through share quality. Thank you.
|
Linked List Random Node
|
linked-list-random-node
|
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
| null |
Linked List,Math,Reservoir Sampling,Randomized
|
Medium
|
398
|
162 |
everyone welcome to my channel so in this video i'm going to introduce uh how we are going to solve this problem called find peak element and before we start the content for this video i would invite you to help subscribe this channel because it can really help this channel to grow thanks a lot so let's get started a peak element is an element that is strictly greater than its neighbors given an integer array norms find the peak element and return its index if the array contains multiple peaks return the index of any of the peaks so you may imagine that nums -1 so you may imagine that nums -1 so you may imagine that nums -1 and nums and as equal to negative infinity so which means um if the uh element at zero or the element at the end of the array if it is larger than the neighbor then we are going to treat it as peak as well so um let's see so for this one nums one two three one it is going to return two because uh this one three it's index two is a peak element so let's see the constraints it says the length of the array is not going to be empty so it is between 1 to 1000 and the numbers uh within this input numbers array is within the range of in 32 and also it says that the num i like uh each of the neighbor like each pair of the neighbor is not going to be uh the same all right so um i think i pretty much understand the question and the currently the only edge case i can think about is what if the input numbers array only contains one integer then we just need to return 0 as index otherwise i think there isn't too much room for us to figure out the edge case but i would say the ash case i mentioned before can only can also be covered by general algorithm i think so there is a follow-up saying that can so there is a follow-up saying that can so there is a follow-up saying that can we implement the solution the logistics can we experiment the solution with log complex complexity the answer is yes and if there is such follow-up it makes me feel that we can follow-up it makes me feel that we can follow-up it makes me feel that we can use um binary search to solve this problem so essentially the profile solution is we do a linear scan on the input array but that would make this question to be too easy so since there is some follow-up saying we since there is some follow-up saying we since there is some follow-up saying we can use some log complexity so the algorithm is to change the original binary search and to apply uh binary search in new environment so let's go through this piece of code and at the same time i'm going to introduce a solution so the general idea is to use binary search to solve this problem and for binary search um the goal for us to do is only to find the local peak so for banner search we have the left and right pointer so we have the mate pointer um which is left plus right minus left divided by two so if um the maid nums at made is smaller than nums made plus one then it means that um this uh the midpoint is on the slope like from uh it's like a slope something like this right so like it's going if it is going uh going up so it's a slope going up otherwise it is a slope going down so if nums made a smaller the nums made plus one then it is a uh it's a slope that's going up so there should be a local peak within uh the right side so we are going to have left as you automate plus one otherwise if we if the slope is like something like this like the slope going down then it means that there is a local peak on the left side so we are going to set the right has made and finally just the return left so that's pretty much it and the runtime is going to be login and space-wise it is constant so that's and space-wise it is constant so that's and space-wise it is constant so that's it for this coding question if you like this video please help support this channel i'll see you next time thanks for watching
|
Find Peak Element
|
find-peak-element
|
A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.
You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in `O(log n)` time.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.
**Example 2:**
**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
* `nums[i] != nums[i + 1]` for all valid `i`.
| null |
Array,Binary Search
|
Medium
|
882,2047,2273,2316
|
1,046 |
hello everyone today we are going to solve a very easy problem which is the last stone weight so in this problem we are given an area of histones where strong eye is the weight of the ith stone we have to choose two heaviest stone and if mesh them together if their weight are equal then both stones will be destroyed and if their weight are not equal and x is a smaller than y in that case x will be a smaller stone will be destroyed and the bigger is heavier histone will get the weight of y minus x okay so at the end of the game there are at most one stone left it may be possible that there are no stone left so we have to return the smallest possible weight of the layer stone or zero if there is no stone left let's understand it by a example so in this example the heaviest right now two heaviest shown is seven and eight so uh we will smash them and seven and 8 will be our array will be 2 7 4 1 8 and this from this we smash this 2 and our array will become two four one and this will become eight minus seven one and one then we will smash two and four and our array will be uh this four will be two 1 4 minus 2 is 2 then we will smash this and our array will be 1 then we smashed these two and they are equal so we will destroy both of them now we have only one and this will be our answer okay uh let's understand the second example in second example if we have only one then our answer will be one okay so how we are going to solve this problem let's understand by the intuition first so how we are going to solve this problem is we have to manage we have to store this the according to let's say wait so we are going to use a priority we are using priority queue so what it will store the max the heaviest stone at the top of this so what is this is the max heap we are using max heap so let's understand with an example so first of all we are going to push all the item in the priority queue so it will be stored like first of all if we proceed to this so it will be one um two four seven eight then after pushing all the area element into the priority queue one by one we will post uh we will pop up uh elements until the size of this priority queue is greater than one okay so first of all we post pop two element eight and seven and check is are they equal or not if they are not equal then we will uh we will post the difference of these two so 8 minus 7 1 we again post 1 here so it will be here one then our then we put two element four and two and they are not equal so we'll pop the post the difference which is two so two will be push here now we will pop two and one and the difference of two and one will be one okay so it will be three one this is the priority right now we will pop again one and both of them are equal so we are destroyed both stones so we have only one as soon as the size of this priority queue is equals to one or is it equals to 0 we stop popping out so if it is 1 so we will return priority q top otherwise we will return 0 as our answer so let's see the code or our priority queue which is our max keep first of all we are going to post all the array element into the priority queue so that it store according to their weight then until our priority queue size is greater than one we are going to pop two heavier strong and check if their weight is equal or not if they are not equal then we are going to push the difference of their weight into again priority queue and if after operations there are a priority become empty that means we have no stone left so we are going to return 0 otherwise if there is one element in the priority queue we are going to return priority queue top element okay so the time complexity of this problem will be and logan because of priority queue it sort and the post and pop operation in the priority queue will be n logan and the space complexity will be off and because we are using priority queue so the space complexity will be of n so this is the whole solution if you and have any problem in understanding this problem so you can thank me in the comment section thanks for watching
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
246 |
hello and welcome to the next video of python bytes problem solving in this video we will see how to write a program to find all strobogrammatic numbers with n digits in this problem we are going to create a program that finds all strobogamatic numbers with n digits so what is a strobogrammatic number a stopogrammatic number is a positive number that appears same after being rotated 180 degrees for example if we write 16891 and we rotate it at 180 degrees we get one six eight nine one if we take 88 and we rotate it at 180 degrees we get 88. so you see that when a particular number a positive number when it is rotated 180 degrees we get the same number those numbers are called strobogrammatic numbers so now let us see how do we create a program that will give us all those topogrammatic numbers with n digits so if n was 2 the output would have be 1 8 nine six and six nine so there are four numbers if the out n was one we would get one eight zero so now let us start so there are two parts to this program one is when n is odd and when n is even so let us first solve n is odd so that for the understanding we will take n is equal to 3 so there are three positions and we start with the center position when we at the center we will we can assign the values 0 1 and 8 to it now once we have assigned these values we start going outwards so one step left side one step right side so we have 0 1 8 as our center digits so now when we go to these digits the one on the left and the right we start assigning the values so the values can be 1 they can be 8 eight so because this is a three digit number we are not assigning zero if it was more than three we could have assigned even a zero over here so now when we assign six we assign nine here and when we assign nine here we assign 6 and the similar way we will assign all the for all the numbers that has made 1 and 8 will do the same kind of operation and thus we see over here that we are repeating the operations thus we can use recursive function that is we can create a function which will use itself again inside the function so we can recursively like repeatedly do the same operations to get the list of numbers that we are looking to get the programmatic numbers if the n was even so for example i am going to take n is equal to 4 so there are four values that we have to add we will start with the second and the third because the center is no center so we will take the mid two digits and we can start assigning values to it so as there are four digits we can assign the center value as 0 1 so 0 will only come when we are not at the edge and we are in the middle of the number so we have 0 1 8 if it is 6 we use 9 the second position if it was 9 we use 6. so now we go to the next level and we go one step out that is left and right 1 steps and if it is not at the edge we use 0 but if now we are here at edge so we use 1 we 8 6 and then 9 and because it is 9 here it is 6 and we do these operations similarly for all the digits that are in the mid and thus we get the list of all the numbers that are there that are strobogrammatic so if we implement this we will get all the list of all the four digit numbers that are programmatic now let us go to the coding part and see how to implement these functions and get this list of tropographic numbers when we have given n as an input to the function let us create a program that will help us find all the strobogrammatic numbers with n digits so for that we are going to use a function called gets robographic numbers and argument is going to be n and we are going to output it with the result that we are looking and that result is going to be list so n is the number of digits and over here for example we have taken 3 as the number of digits in the numbers so let us for writing this program we are going to use a helper function so let us define that helper function and this helper function will help us you run the program recursively and it will have two arguments n and length so let us see what does n do n means so let me let us start with if n so if the end that we are given input was equal to zero what should be the output so we are going to return an empty string an empty list with only one string in it so i have to remove it here okay if n was one that is a single digit we are going to return the strobogrammatic digits so those are one eight and zero so these are going to be uh the digits if the there it was only one digit strobogrammatic number so now we will see the from so now in the discussion we had seen we start from the middle so what is going to be the middle so we start recursively going we as we start going inside the number so we are going to use the helper function to go inside so this is going to be n minus 2 because we are going to go one step in and then the length because we have to input we have to give the length over here so when we start we are going to use this helper function also over here so this is our main function so that this results is going to be a part of it so n comma n so n is the digits and the length is also n to begin with this length will always remain n this n will keep changing as we keep recursing into the function and now we have got to the middle and we are going to have a result of our inside function helper function and for that when we have so whatever this helper function outputs is going to be a list so for example initially if we started with 1 over here we would have entered 1 comma 1 and as soon as we have entered this function helper function we would have this condition would have been true and we could have got this as the list now it is 3 so we have when we enter the helper function 3 comma 3 so we start over here so none of these conditions are true so n is not 0 nor 1 so we go to this function this part so we recursively call it so now it becomes 1 comma 3 so when it will come here so in the second loop of the recursion that is of the helper function we see that we are able to fulfill this condition and we are going to get middle as 1 8 0 and this is going to be true for the center position so now we are going to recurse through this middle in middle and what we do so if for example the condition was n is not equal to length and that is why we have taken length what we do is we are not at the end of the digits end of the digit so we can input 0 over here so our result part will have this appended in it 0 plus mid zero plus mid plus zero because if we are not the end of those digits we can add zeros so now that was one condition but for all other conditions even if we are at the end we can keep appending these numbers over here and we know that what are the strobogrammatic digits so 1 8 6 and 9 which we can add so we will add over here and i am going to copy this three more times because there are three more conditions where it is going to be true so if we are going to add 8 we can add 8 on both the sides and if we are going to add a 6 on one side the other half side has to be 9 and if the one side is going to be 9 the other side is going to be 6. so these are all this is how we are going to create a number from inside out and this is at the end of our helper function also so if we now run this code and we add 2 over here we will get output as oh so it says results is reference before then scoping so we have to use this results so i am going to replace over here it results and now run it and we got it at none because we forgot to return the results at the end of our helper function we have to return results over here which we forgot so let us add that and now we have got our output as 11 88 69 and 96 if we go to three digits we will get output as one eight so you see that the second digit or the first and last digit were never zero but if you increment this to five we will surely encounter this condition and we will have a lot of numbers which will have the middle digits also as zero so this is where all the three digits are zero and there are alternatively 0's also but the last digit will never be 0 because that way will not have the enough digits that we want if it was 0 and 4 digits it will become a 4 digit number and not a 5 digit number so that is why this condition is very important to be added that if n is not equal to length then only we add zeros otherwise we do not add zeros i hope you understood what are stopper grammatic numbers and how to write the program to generate end digit programmatic number please like this video and subscribe to the channel leave your comments in the comment section with your feedback and questions find a link to the code in the git repository goodbye till next time keep coding you
|
Strobogrammatic Number
|
strobogrammatic-number
|
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:** num = "69 "
**Output:** true
**Example 2:**
**Input:** num = "88 "
**Output:** true
**Example 3:**
**Input:** num = "962 "
**Output:** false
**Constraints:**
* `1 <= num.length <= 50`
* `num` consists of only digits.
* `num` does not contain any leading zeros except for zero itself.
| null |
Hash Table,Two Pointers,String
|
Easy
|
247,248,1069
|
1,952 |
Hello hello everyone welcome to some tips on n Is device of in the resistance in more fuel like this soudians king david and returns through the big b positive and definition of multiple should that tubelight you can find only a 200 aa and is winfree device not that office number like this overview country or Fever numbers for positive number valve 125 12345 with a photo bihar having one and two advisors to be arriving today price photo the first three layer i will give one mp3 the festival is of tour but then behaving 120 400gr first positive integer width info on Don't Also Have In Interview For Preserving Exactly Free Device 100 Know What We Can Do Is So Come What We Can Do That Is Of Having A Great Literary Devices Like Craft For Number Three Do For Number Two And Equal To The Number Two And Number Having a wedding that is at least two devices is the stage of one and itself that your if you take the example of 2345 Every number two or to the number 138 Tours and travels have two desires for any number greater than or equal to And now we are having an option only to give that device and for one month divide numbers paired 200 real android we can do it will check back number is perfect square shape make it a number perfect square that And that not having any device adb and do n't forget to subscribe this video channel subscribe to yes or no then comment then coding part of first will check number is one and two expensive vansh and which I did yesterday 210 what we can do you Can directly in return for what we can check this number perfect square or not I just n that is a square root of man that exam must of square root of end of pimple to seal off is so common a devil game 90 number Perfect Saver Not Enough Power of Four Aa this directly aa return forms for one two disabled to I love you two from the my friend this is not devil that we commissioner Dr that this is to unmute alloy that Nepali equal to zero two the return gifts hai so a what way Are doing and is re default number laxative in the number is dividing number and videos thanks for watching this Video Anand on the soldiers were chatting half shooting and is and returning officer that and this all who has successfully in which can return on for sorry he Must be solid Surendra Court that this sweet accepted is so submitted or listen to the qualities of software and thank you for watching
|
Three Divisors
|
minimum-sideway-jumps
|
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Example 2:**
**Input:** n = 4
**Output:** true
**Explantion:** 4 has three divisors: 1, 2, and 4.
**Constraints:**
* `1 <= n <= 104`
|
At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane.
|
Array,Dynamic Programming,Greedy
|
Medium
|
403
|
458 |
hello everyone welcome to coding decoded my name is sanchez i'm working as technical architect at adobe and i am slightly unwell today i have mild fever and gold so i'll keep this video short and to the point so i'll be walking you through the question as well as the algorithm by the presentation so let's quickly hop on to it uber picks lead code 485 it's a hard level question on lead code and i don't feel the same also this question is based on mathematics and geometry so in case you don't understand this question or don't want to do it you can skip this up because the possibility of this question getting asked in interviews is extremely low for those who are still interested let's walk through the question first i am depicting the question by visualization so here in this question we are given n buckets and we are also given that only one bucket out of these n buckets is poisonous in nature so we are also given guinea pigs so whenever a pig drinks water from any of these buckets in case that bucket happens to be poisonous then that pig is gonna die we're also given two times one the time to test and other one time to die whenever a pig drinks water from any of given set of buckets that pig has to wait until minutes to die mints before drinking on the next set of buckets what it means is that let's assume this big drunk water from these three buckets unless we get the result of the drinking water or from these three buckets that pig can't be used further to drink water from any further bucket so this states that there is an observation period up till minutes to die means given in the question what we are also told we are told that up till minutes to test this is the final time the maximum time of under which the experiment can be done so as per the example it has given us 60 minutes that we have to do this entire experiment within 60 minutes the observation time or minutes to die time is 15 minutes and let's take a slightly different case wherein the bucket size the number of buckets that we have is less than equal to 5. as per the question the total experiment time is given to other 60 minutes and the total observation time is given to us as 15 minutes so when i divide total time by observation time what do i get 60 by 15 is 4 so that simply means there can be four set of intervals the first interval would be from 0 to 15 the second would be from 15 to 30 and the third one would be from 30 to 45 the fourth one would be from 45 to 60 and in case the pig doesn't die up till the first four buckets then what we can conclude that the fifth bucket happens to be poisonous in nature so this is another observation that you should analyze that in case 60 minutes have surpassed and the pig is still alive what we can say last bucket is poisonous in nature so we are going in a sequential manner we have considered using a single pig named p1 and that pig will first drink water from the first bucket it will wait until 15 minutes then in the second interval it will drink water from the second bucket in the third interval from this particular bucket the fourth interval this one and in case the pig doesn't die up till the last quarter then we can say that the final bucket that we have happens to be poisonous in nature what we can include from this we can say that whenever the number of bucket happens to be equal to less than or equal to five the number of pigs needed is only one that means five raised to bar zero now let's extend the bucket size further we have extended the bucket size to less than equal to 25 and we have also made sure that the bucket size is greater than 5 the total experiment time remains 60 minutes and the observation time is still 15 minutes we've also represented these 25 buckets in the form of a 2d matrix so what we are gonna do the first pig p1 will drink water out of the first five buckets that means from zero to four the next pig will drink water from the next five buckets that means from five to nine the next pig will drink water from 10 to 14 and the next pick p4 that is shown in orange color will drink water from 15 to 19 and the last pig will drink water from that is p5 from 20 to 24. and again we have divided the experiment time in four intervals the first interval starts from 0 to 15 next one from 15 to 30 next one from 30 to 45 and next one from 45 to 60 so what's gonna happen these pigs p1 p2 p3 p4 and p5 will be parallely doing the experiment and the first pig will be doing the experiment for zero to five zero to four buckets the next pig that is in light blue color will do experiments from five to nine buckets the p3 pig that is highlighted in green will do experiment from 10 to 14 buckets and p4 will do experiment from 14 to 19 p file will be doing the experiment from 20 to 24. so what's eventually going to happen we will be identifying the row in which this pick dies so with this row will be that b that row would be this one because this dark blue color pig it's gonna die by virtue of this bucket being poisonous now comes the question how can we identify the column in which this fig is gonna die so what we will be doing again we will be manipulating these same set of picks to drink column wise as well so what we are basically doing we are making sure that the pig p1 also drinks water for all the buckets that lie in the first column we have also make sure that the second pig which is p2 will drink water from all the buckets that lie in the second column similarly for p3 and p4 and p5 and eventually what is gonna happen two pigs are gonna die in this case the first one would be this one this dark blue color and the second one would be dark green color so using these two picks we can simply identify the exact bucket id corresponding to the poisonous bucket and that bucket id would be this one so if you carefully observe then the combination of each set of picks gives you the identity of each and every bucket so in case let's assume this bucket happens to be poisonous then what's going to happen p3 pig will die and p4 pig will die so we can identify the bucket id using the combinations of these five picks deep that representing rows and columns so in total how many pigs have we consumed or used for this experiment five now let's extend the same approach onto a larger bucket size so whenever the bucket size is greater than 25 and less than 125 now we can extend this entire algorithm in a 3d space so previously we did it till 2d space where we took 25 buckets alignment now we can take 125 buckets alignment using three spa 3d spaces one for x coordinate y and z how many pegs would be needed to do the experiment it would be equal to five raised to part two that means 25 picks are needed in order to conclude it up let's quickly walk through the coding section so even before i solve the question one of the subscriber of coding decoded so i have already raised the pr and he has been doing it for approximately three to four months that i am aware of and in total he has submitted almost 200 peers onto coding decoded github repo this has helped him be consistent while solving daily liquid problems and i thank him for providing these two solutions one which is a one-liner and the other one which is a one-liner and the other one which is a one-liner and the other one which is more descriptive so you can go through these solutions yourself it's very simple to understand i'm attaching its link in the description below and in case you also want to raise prs onto coding decoded github revo you are most welcome to do it people usually code in c plus and java and raise prs over here so i will be reviewing your pr's from an interviews perspective and why this you will also get to know your mistakes and you will become consistent so over to you guys looking forward to it thanks for watching you
|
Poor Pigs
|
poor-pigs
|
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
1. Choose some live pigs to feed.
2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time.
4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
5. Repeat this process until you run out of time.
Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_.
**Example 1:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
At time 15, there are 4 possible outcomes:
- If only the first pig dies, then bucket 1 must be poisonous.
- If only the second pig dies, then bucket 3 must be poisonous.
- If both pigs die, then bucket 2 must be poisonous.
- If neither pig dies, then bucket 4 must be poisonous.
**Example 2:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
At time 15, there are 2 possible outcomes:
- If either pig dies, then the poisonous bucket is the one it was fed.
- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
**Constraints:**
* `1 <= buckets <= 1000`
* `1 <= minutesToDie <= minutesToTest <= 100`
|
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test. How many states can we generate with x pigs and T tests? Find minimum x such that (T+1)^x >= N
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
399 |
hey everybody this is larry this is day 27 of the lead code daily challenge uh hit the like button to subscribe and join me on discord let me know what you think about today's problem uh today in today's problem is evaluate division okay so you're given equations a over b is equal to k okay no division by zero no contradiction okay so a over b is two b over c is three okay um number of equations is 20 and the number of equations.length is 20 and the number of equations.length is 20 and the number of equations.length is two okay so this turns out to be a graph problem and because of um because of you know these guarantees that there's no division by zero and the bigger one is contradiction we can actually figure out as a graph problem and the way that i would do that is from a to b uh there's an edge where a over b is two right and so fourth um and then you just have to figure it out in a way i think that's roughly right and the algorithm that i would use for this one um because n is at most 20 it's just void washer because then we can answer queries very quickly that's one of the benefits of foid washer in general so that's not actually n per se n is the number of unique things so yeah so let's do yeah okay let's have the names uh a dictionary and then for x y in equations um and now we just want to you know count the number of things so yeah if x in names or not in names of x is equal to index and that's one if y not in names so basically we just oh whoops uh you know this is right uh index so basically we're just uh mapping names to the a number survey but that's pretty much it name so basically converting um you know these inputs into uh an index uh by having this in the lookup table um mapping variables to indexes and then now we can go through the equation again and then now we have an n and is equal to the length of the names um and now we can create uh a graph pretty much so of um let's see what do we want to call it so basically right now i'm just trying to figure out what is a good signal value because basically we just want this times n for this man and because they're 20 equations at most they have 40 variables um so maybe i'll just call it none maybe i don't know let's see uh and then now we do the classic ford version um and definitely look it up if you uh if you have if you're not familiar with it uh it's pretty it's kind of a dynamic programming problem but yeah um i don't want to get into it because it's probably out of the scope of this um but yeah hopefully that makes sense um and basically we try to get to uh the closure of this uh graph uh and now we have to all appear shortest graph um and oh i think this should be okay because if it's if there's no contradiction then this should always be okay um maybe that we'll see if it's not then that's fine uh well i missed something which is that i need to go through this equations again to pause it so we want to say names of x uh names of y basically now we have these indexes right and also i'm missing some of these values so i actually needed to do that uh because then now we get the values of index right and then now for q inquiries uh or is it what is it uh a and b okay for x y in queries we just um you know let's have the results so i'm not explaining that well uh because i'm just coding it up i'll go for the code a little short while uh yeah if g sub x y is not none uh results dot append g of x y otherwise i think it's negative one right okay so that's not great because there should be this should never happen unless i'm missing something uh oh maybe the names of y accent name surviving as well uh oh i just have typo here whoops oh no still this indexes must be oh yeah i forgot to map this uh which is we have to map it back to the names because these are strings okay a lot of silly typos but that's okay maybe and let's also put in the other test cases while we wait uh oh no he is not in that's odd okay let's take a look real quick uh again i wish that this has uh you know a bun for me to import all the other test cases but i'm doing this live so i apologize for that uh oh this g may not be in the index okay that's fair uh so basically queries may include things that are not in equations okay that's reasonable so basically if x not in names or x not in oh sorry y not a name so we just have to uh you know add more um you know emerald things uh okay so that's not great that we all i mean it's not the worst thing but it's not the best thing either uh so how do we get point five uh b over a oh so okay so the inverse we have to do the inverse as well so that makes sense i just didn't think about it that much to be honest but that means that we just have to um yeah populate the inverse as well i don't think this is that tricky hopefully knock on wood because every time i say that i get in trouble um yeah so now everything looks okay because and the thing is that we would probably add more checks to make sure that it's consistent uh because a lot of problems uh a lot of uh problems will not give you that guarantee but because they do give you the guarantee here uh we don't have to check for it and the division by zero for example uh everyone looks okay i think don't i think i'm gonna submit just because i'm a little bit lazy on stream uh i would definitely add more test cases especially stuff around with like no edges and stuff like that um but yeah okay so this is accepted so that's great so what is the complexity of this right so we know that equations will have at most 40 different names so that means that it's going to be that's our n so that's going to be n cubed because that is the complexity of forward version and for each query we do all of one work so it is going to be o of n cubed plus q uh i think i said cube and q so yeah so running time is going to be n cube plus 3 or plus q man and the space is o of n cubed also plus q because you need one for each answer right so that's the time and space complexity so the idea for us um and i did hand wave a little bit because again we don't have to worry about the zero and no contradiction so that means that with it's in a way you try to figure out the transitive closure it's not quite that because it's not um it's not the boolean but basically if um i like you're given a divided by b and b divided by c you want to map a to over c right so that's basically what default ratio does for us in a way uh so it is like the transitive calculation of the problem and then we pre-calculated for every possible pairs pre-calculated for every possible pairs pre-calculated for every possible pairs and because n is equal to 40 at most uh this is not this is pretty fast right and we do some over one lookups here and that's pretty simple um but yeah but otherwise this is just mapping it to a graph problem um so first we map each name in equation into an index which is a number which makes it slightly easier for us so you don't need to do that if you are clever um and then we pre-populate um and then we pre-populate um and then we pre-populate um the values that we know to be true which is you know the values and the inverse of the value uh and then we just do this forward brochure and then at the very end we just respond each query by looking up in this table that we created from floyd washer uh cool uh that's all i have for this prom let me take a look at the hint oh yeah okay fine uh that's all i have for this farm uh let me know what you think hit the like button it's a subscribe button join me up uh on discord and i will see you on the next problem tomorrow bye-bye
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
46 |
hey how's it going this is computer red and in this video we are going to look at the lit code problem number 46 called permutations this problem will serve as an introduction to backtracking so the description of this problem is quite simple so given a collection of distinct integers return all possible permutations so we are given an array we call nums that will contain numbers like one two and three and we want to output all the possible permutations like one two three one three two one three one two so the description of this problem is quite simple so we can start thinking about the solution and so how can we build the permutations and the best way to find out is to look at different examples so let's start with one number and let's say that this number is a yeah i know what you're thinking a is not number it's a letter well nobody ask your opinion okay this is my video i do whatever i want i'm in control so if i want to use a as a number i use a as a number okay so if the only number we have is a well we don't really have anything to do we can just put a is the only permutation but if we have two numbers a and b we can start with a or with b and then we can continue if we start with a we then choose b and if we choose b we can choose then a and that the only two permutation we can build now with three numbers a b and c we can start with a or b or c and then we can continue if we start the permutation with a we can choose b of c therefore b it's b a or c and finally for c say ob and then we just only have one remaining element for each permutation so now let's try with 26 numbers so like the previous example we can start with a then b then c then yeah no just kidding you really thought i was going to do the 26 number do you think i've got that much free time hell no so yeah let's get back to the example number three and what we did was that we built a tree of all the possible solution and when we built that kind of tree we call it a state space tree so whenever we are able to build a state space tree and if we go back to the description of the problem we saw that what we really want is all the possible permutations all the possible solutions then when we have these two elements in a problem this indicates that we are in a presence of a backtracking problem so now let's talk about backtracking in backtracking we have what we call the three keys of backtracking and when i say we i'm talking about a certain youtuber and this trick is on the following the first one is choices we have a set of decisions we need to take and the decision the choice we make are limited by a set of constraints and we make these decisions in order to reach a goal in the case of our problem the different choices that we have is choose one number this constraint is that we only can use one number and we can't reuse this number later and the goal is to build a permutation and with the three keys we can define an algorithm the backtracking recipe so the backtracking algorithm can be defined by a recursive function that take a couple of arguments one of them is an array containing all the different solutions we find so what we want to do is build different solutions and whenever we deal with recursion the first thing to do is know when to stop and a we want to stop when we have reached our goal and when the goal is rich which mean we've just built one solution we found a solution we add the solution to the array containing all the solutions and then we just stop there if the solution we are currently building is not done then we need to keep building it and the way we build it is by going all the different choice we can make and if we can actually make this choice this decision if this decision is valid then we can take it and then keep going and we just recursively call backtrack and once this is done when this function is done it means that we either average the goal or we can't actually build any more solutions so we just undo this choice now let's try to apply this backtrack i'll go with them to our problem so we are given as an input the array numbers that contain all the number we will have to use to make permutations and the result array is a list of all the solutions so res is already in the argument list but we need to add nums to the list of arguments now let's talk about the goal and the goal we want to reach is build a permutation so we'll have to have a way to store the permutation and when the permutation will be the same size which means it will contain the same amount of number that the input numbers then the permutation will be finished so we can just add this permutation to the result and because we will need to keep track of the permutation we are currently building we need to put it in the argument list now to be able to build this permutation we need to go through the choices we can make and any of the choices we have to make is use a number so the thing we have to do is look through the nums array like this and now the constraint is that the number we are choosing wasn't already used in the permutation so did we already use nums index i and there's two way to remember if we already use this number here the description of the problem state that we have distinct numbers so we could use a hash map or we can just use an array of booleans and i think the array of volumes is just as simple so we are going to define an array called used and used index i will be true if nums index i is used otherwise it would be false and because we defined a new array we need to add it to the argument list now let's talk about the choices we have to make the choices it's just well we're just using this number so we have to say that this number is not used so we just put true this number and once the backtrack will be done we'll undo the choice so we'll put it to false and because we are building permutation we actually need to add this number to the permutation and what the backstroke is done we removed it and that's pretty much it we just solved this problem so let's take a look at the sleepless plus implementation of this algorithm so we have the result array that's just a vector of int then we got the numbers which is the input we got another vector that contain the permutation we are building and then we have our array of use to know if we already used the number at index i then we check if we have reached our goal which mean we've built a permutation if that's the case we just had it to the result otherwise we just keep building the permutation so we got through the list of numbers if it's not used then we can choose it take it put it in the permutation and keep building this permutation once it's done we just undo it and we're good and if we look at the beginning so what we give it we just build an empty res vector of vectors we init this used vector with false and we create an empty permutation array and we just give all of these arguments to our backtrack function and we return the result and if we submit it just works and we're done so i hope you enjoyed this video goodbye
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
220 |
That's a hello hi guys relation side so today we are going to do the difference of balance in patience between in that manner as quickly as possible 09 that the difference of the balance on which the difference is lying should be the loosening point and the temperature of the Indians is useless. Should I do something to one or two? Two cash deposit values and different should be different. Subscribe to Ghaghra. Which one did I get? They had gained theirs. Gujarat can be in two element police station, meaning the least is 54811. It is good that one. And this one is the difference of both of them together in the campaign which is garlic equal to two drops soon Independence Day that if let's not make it then I have a note of hanging I could not have been disgusted if here instead of the place of this note But if I were here in my place, what would have happened? Loot, call, play on the phone, loot everything and after that, what can I do? I am following the example of A.R. Rahman, I do? I am following the example of A.R. Rahman, I do? I am following the example of A.R. Rahman, I will make it for the village because all this is nothing. It is meant for this line, this one is not for any work, so how far can I go, it should be meant to share all your missions and when it becomes regular, it means just subscribe because for the element. There is a range, okay, so subscribe to this, you will take 94598 according to taste, I have put it forward from the pole, it becomes the exam center, so man, what do I think if I have just and just from the current of every element. Life would have been better if one had to become elder but now how will one be taken out, after this the accused will be brought to the court, the age is approaching, will you be taken out in this way, so think about it, we will make a date, this means that the elder brother is the one who saves from the one who kills. The above has made a yes, only then we do it and see, now I have considered the window as the second acting, from here I start thinking, till now, which is the 996 element, how much difference was he able to make, moving towards it but eight. Isn't it how much I wanted, 90 is big, there is fuel and make this mistake, 901 is a little healthy inch 5.5 and 901 is a little healthy inch 5.5 and 901 is a little healthy inch 5.5 and how much did I increase the difference and made it how much I wanted, small work is not a big difference, so I am here. There is no element, okay, now it's time to kiss the window, if you feel like kissing it, you will have to remove it, this reminder can be another, it happened, but when they and the window take their own, the window has come here, now we have to store the medical here. Now the element is considered, how will we become good to the forest and share it? Brother, accepting the forest that we are not only descendants of the village but also our own, then it was time to eat again, as the fiber became smaller and smaller than the fiber. Subscribe, it will come and along with it we will build the defence, and that means brother, we wanted a difference piece, we wanted three, it is not working, then what to do with five, now the time has come to add it in winter, if we add it to these favourites, then how to fill the form of minutes. If I go, I will have to lift it from behind, I thought this in my mind, made a plan to connect my pipe to see Adityanath's rain or the world, Nine said, brother, make the message shorter, tell me, Jashoda, how much has been made of Nine Five Lines of Evidence, I was able to make more with him. So I and again there was three, the work should be increased to nineties, no, now the time has come to normally take it in, but in this meeting, how will the window size increase, we will have to lift one side, and how was the window, what did it go next, no. Marked semester, only then, what were you saying while making 90, press 90, name given in the window, now whose turn is it, say stomach egg or Mrs. Chhota Banda, tell me, 1658 f5 reference, how much was the thrill, how much was the difference, how much was the three, that much of yours. In that way we got a small amount of good humor. We Mishra friends had kept it as 8 always add meaning look at this one then how far away it is from this one and if we ever check the distance on this person then I think. Which is quite a that now our how this speed example has been taken fun 159 You are the one who considers your partner sex that English 4 on, then again Hui ke to keep it CO, keep that we will start absolutely on this in the last minute. I will put it in Delhi now, let's not even do this, let's start first, come first, world rider, okay, who is there, what is there in the current window, nothing is there in the current window, Vansh total, nothing was found, off, one big mine, nothing was found. One was made to Delhi within the last minutes, life came inside the toe that Bankoda Ajna Binu was sitting inside the innings of I5, okay, it is just sitting in Delhi, got 151, okay, Deputy, friend, I will increase it a little and Neither will that solve the question and you must have promised to spoil my mood. On the side of A, it is okay, just a smaller element than five, saw the adulteration element in the current window, how much is the difference, and on your side, not that much free work has been made, brother, okay again. Increase it, dear friend, now it is the turn of the window explanation, people said brother, we are coming friend, 91 part is good or did you cause an accident with the size of the window or no, you do not have to do anything, free download will check the size of the window, then element. Will you get up? Okay, now it's my turn. 9 messages in the small element. Who said I? We calculated the difference. How much is the difference? How much do we need? How much did we need? Less than 10 inches is not enough for 3G passengers. Is it okay? Is this the limit of the interview? In Bigg Boss minutes, we have done it. Ok yes Window 8 minutes time has come Window-eyes were doing good employment How did window-eyes get bigger What happened Window-eyes were doing good employment How did window-eyes get bigger What happened Window-eyes were doing good employment How did window-eyes get bigger What happened brother if you don't put it or remove it then what would have happened if you did n't keep it then go for Al Hasan Jafri One consider for free It would be fine if I could not remove the right part of the window and the last ball of half the limit was the head and at what distance is the forest? One means it is at a distance of one, two or three portions from the screen, which is saying in the planning that the time has come to fight. My powers were misused, mother finally came forward to teach the second one who seems to have ascended, but did not get anything connected properly, then it must be element 5353 subscribe to yo honey singh ka alam ne difference hai to apne kitna chahiye There are 350 companies included in this entry, your meeting will be quite easy, direction, sub discussion, did you understand this, tell me, subscribe, if this is a little BSC, then I am fine, now we will add aloe vera in it, no, it will take the time of commission lock. Judge in roasting any element, it is difficult to find the small one, big one, it will take time to lock it, please remove it, we will use it does not mean that it is not understood, it is printed that it sets the property, it is the property because it became limited to just increase, how much time will I have to take? We met during the lockdown in people's time and what kind of prank have we played that we will increase it for us also, if we make it in a way not like saffron, then we will find time, just observe, failing to be fast will take time, ok brother, so you said something good. Do it too, we get into such a logical meeting where we get looted by sitting in oil, we pick up the name of the son of truth and this is the name of top-10 tears and this is the name of top-10 tears and this is the name of top-10 tears and alarm set, this is equal to new hundred, it is okay, yes, for that. This is equal to see your isolation start length is A plus B good-good or will remain and set 193 then I will tell you in an interview interviewer what is the meaning of one then what will you wear modern will take just small and big will take out neither intact color business model guild Treated water in the awards function and does this or melts the hatred? No, when the just larger husband, daughter's lion, we will come, then this way of making me just bigger is fine, now why is the test molar not A? In which we have not got long revenue and the name FIR - Just Small and the name FIR - Just Small and the name FIR - Just Small Place in Quality has been found that this small bandha has been found and from the person on whom we are roasting, we have got just small bandha, that brother, his involvement is 180 or less. The work is not done like this, let's check the changes models, it is like with filter, if there is no tap, then there were 10 class results, that is, they were doing it at the current minimum, when the person comes, they just tried to become bigger than him and It's just red chilli, its difference has been made. Hey brother, you have come without laces. Daily vomiting has happened. Do the return through. But neither did you decide in the end that brother, you have to get Redmi 2. You have to get it in the set. So if we have to come, we have added it in the back, so alas, then what did we talk about, friend, if by setting the size had become bigger, we will have to remove the element, then if the size of the T-shirt was decided more, then the we will have to remove the element, then if the size of the T-shirt was decided more, then the we will have to remove the element, then if the size of the T-shirt was decided more, then the truth of our window was never that of a weapon. If you do n't want to be big then how does it get bigger, will you throw it away from the third or not? Will you give clarification - I can do IS position, I can get the clarification - I can do IS position, I can get the clarification - I can do IS position, I can get the position, go back, isn't this a business of pizza and so take it out and throw it away 110 Tha Bada Pyara Vara Unique Splendor Nothing happened in the end Return Forms Na Doge MP3 Man Ka Pyaar Let's run it and see if it's done It's great Now I'm coming In this case there is a ship's mindedness which can make a mess but if there is No, if you like this video, then it is our festival, tomorrow falls in the state, the department would have been big, when we would have had a difference, it could have been possible for both of us, that means this subscribe Video - means this subscribe Video - means this subscribe Video - - If it happens, then I have - If it happens, then I have - If it happens, then I have invented maximum, subscribe this Video means like this. Understand that plus something is two table spoon number, further plus two power is number 20 - - I am the number 20 - - I am the number 20 - - I am the biggest number of India, then everything is there, after some time I am, so consider that the biggest number of India is five. And the teacher's smallest number would be 5. Let's say interior. Tell me two interviews. The five biggest number could be 50. The smallest mobile number could be 5. Very tired for master's union. If both these wires are lying there, it could be a museum of these two. If there is a difference calculator then come 10 which is when there is maximum business something or the other falls into these 10m air india air max pro vitamin will be bigger if ever the difference of both starts coming then what happened investment looks different WIFW goes away one plus minus It happens because it is a part of India Not Matter and Join. New I have taken this as my friend, I have made it a voice mail on tap, all the brothers will give long type of love, while doing it, I will have to type in the bills. And while doing it, Bheem killed me in long, meaning of type, we are installing here, we are killing here, there is typecast in long and we are removing, while removing, I will get sick on the day, so I am typecast, I am yours, what happened to it, Rang Coat on Jhal phone. Where is the lovely, you can write ' phone. Where is the lovely, you can write ' Hey friend, this has come to me, then I remain ill, it does n't come, even if the love has been submitted, then the preparation of the mad people, have you understood the question? You are challenging the light at home, friend, please help me. I want you guys to share the video, like it and comment, otherwise you will get the application, I will try to provide more good quality in the side of the video.
|
Contains Duplicate III
|
contains-duplicate-iii
|
You are given an integer array `nums` and two integers `indexDiff` and `valueDiff`.
Find a pair of indices `(i, j)` such that:
* `i != j`,
* `abs(i - j) <= indexDiff`.
* `abs(nums[i] - nums[j]) <= valueDiff`, and
Return `true` _if such pair exists or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,2,3,1\], indexDiff = 3, valueDiff = 0
**Output:** true
**Explanation:** We can choose (i, j) = (0, 3).
We satisfy the three conditions:
i != j --> 0 != 3
abs(i - j) <= indexDiff --> abs(0 - 3) <= 3
abs(nums\[i\] - nums\[j\]) <= valueDiff --> abs(1 - 1) <= 0
**Example 2:**
**Input:** nums = \[1,5,9,1,5,9\], indexDiff = 2, valueDiff = 3
**Output:** false
**Explanation:** After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.
**Constraints:**
* `2 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `1 <= indexDiff <= nums.length`
* `0 <= valueDiff <= 109`
|
Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.
|
Array,Sliding Window,Sorting,Bucket Sort,Ordered Set
|
Medium
|
217,219
|
867 |
on everyone so today we are looking at lead code number 867 it's a question called transpose matrix these matrix questions can be a real headache sometimes but i think if you go step by step on this one uh it's not too bad and it's good to know this one just know the pattern underneath it because there's another a lot of other questions that build off of this so here we have a 2d integer array matrix and we want to return the transpose of the matrix so here we can see that 2 4 minus 1 is good there they are the columns and they're going to now be the rows so you have 2 which is starting here minus 10 which is you have 2 10 18 and now you're going to have 2 10 18 on the columns on the transpose matrix so here you have 1 2 3 4 5 six and you can see now we have three rows with each column being uh the rows on the input matrix so these questions can be a little confusing i think it's really important to map them out and think through them okay so here what we're going to do is i'm going to take a look at the second example and what we want to do here is we want to create a result matrix okay so what we want to do is go ahead and create a result matrix and we want to invert the rows and the columns so what we want to do is we're going to have the rows we'll call this the rows and then this is going to be the column 0 1 2 and this will be the columns okay what we want to do is create a new array where the columns equals rows in the rows equals columns okay so we're going to have a array and we're going to go ahead and create three sets of rows okay that map to the columns and two sets of columns that map to the rows okay and we can just fill them and initially with zero you know we can just have zero here okay so now we have our result matrix and now what we want to do is iterate over our input matrix and just go ahead and fill in the respective values so what that's going to look like is we're going to go ahead and iterate so we can create a for loop here and we can say row is going to equal zero row is going to be less than um matrix dot len and then we'll increment row okay and then we'll have a second for loop here for the columns and we'll start columns at zero where columns is less than uh matrix at row dot length sorry matrix at zero dot length and then we can increment column okay and so now that we are going through each one of these here what we need to do is as we go through each one of these we need to fill them up here okay and so the way we're going to do that we're just going to set our result at column row equal matrix at row column okay so what's going to happen here is we're going to get to this number here where our row is equal to 0 and our column is going to be iterating from 1 to 2 0 1 2 when we get to this second for loop here right and we're going to go ahead and set this to one this right here to two and this right here to three okay then we're going to increment over here in our outer loop and then we're going to go ahead and traverse through these numbers and we're going to fill them in here with 4 5 and 6 okay and that's what we're doing on this line right over here okay so what is our time and space complexity for this approach well our time complexity is going to be o of n squared because we're going to have to iterate over both of these uh arrays okay so whatever the length of the array is we're going to have to iterate over the inner array so it's going to be uh it's actually going to be o of m times n okay so that can reduce down to o of n squared on time and then what about space complexity well we have to create a linear amount of space dependent on how big the input is so we can say our space complexity is going to be o of n okay so let's go ahead and jump into the code here so first thing what we want to do is go ahead and create our result matrix and this is just going to be array.from and what we want to do is have it the opposite so we want the length to be this is going to be the rows to be matrix at 0 dot length okay and now our columns is going to be a new array and the size of that array is going to be at our matrix rows and we can just do a dot fill of zero okay so all we're doing here with this line of code let's remove this const here uh all we're doing here with this line of code is creating this second empty grid here okay and then what we're going to do next is we are going to have two for loops so row is going to start at 0 where row is less than matrix dot length and we're going to increment row whoops and then we're going to have our inner loop where column is going to equal zero where matrix at zero dot length and we'll increment column okay and now all we have to do is update our result okay so we can just do result at column row is going to equal matrix at row column and then all we do is return that result okay whoops let's see result r-e-s-u-l-t let's see of undefined ah where column is less than matrix of zero dot length there we go and we have success and we got pretty good performance relative to the submissions okay so that is lead code 867 transpose matrix hope you enjoyed it and i will see you all on the next one
|
Transpose Matrix
|
new-21-game
|
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.
The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `1 <= m * n <= 105`
* `-109 <= matrix[i][j] <= 109`
| null |
Math,Dynamic Programming,Sliding Window,Probability and Statistics
|
Medium
| null |
167 |
all right this is 167 to sum the second version where the input array is sorted already it's sorted in non-decreasing already it's sorted in non-decreasing already it's sorted in non-decreasing order meaning ascending order and you're supposed to find two numbers that add up to a specific Target and you're supposed to return the indexes and you're supposed to add one to that index so essentially if it's at zero and then one uh you want to return one and then two so you add one to those two indices um and then two and seven they add to nine so then you return those that's pretty much all you need to know for this question and to solve it we want to use two pointers for this particular question we want a left and right pointer right we want a left pointer a right pointer and then we want to set the left pointer all the way to the left right and then the right pointer we want to set it to all the way to the right so length of numbers minus one that would equal to in this case 15 right uh let's use this is an example let's do this so that's our array right that's our input array right now and our Target is nine right and so what we want to do is we want to keep running this we want to Loop through this until we find the Target and how we're going to do this is while the left pointer is less than the right pointer right so that they don't in this case the left doesn't go past the right and then we have an index out of bounds so we keep it until they touch each other um well first we want to check if the left pointer and the right pointer are equal to each other or equal to the Target right so we do this by if um numbers and then let's do this we copy numbers at Left Right plus the numbers at right at the right pointer and then is equal to the Target if it is then we just return the indices Plus plus one as we said at the beginning so we return uh we return an array of numbers right we're returning a list of integers so numbers at left at the left pointer plus one right and then we return numbers at right actually we're just returning we're not returning the actual value we're just returning left + one value we're just returning left + one value we're just returning left + one and the right + one right CU we're and the right + one right CU we're and the right + one right CU we're returning the indexes not the actual values and so now we have numbers so essentially we have the left pointer here oops let's do we have the left pointer here and then the right pointer here now if you add these together 15 + 2 it's 17 so add these together 15 + 2 it's 17 so add these together 15 + 2 it's 17 so it's greater than this what do we want to decrease the right until we get to the actual uh value so now 11 + 2 is 13 and then 13 is still now 11 + 2 is 13 and then 13 is still now 11 + 2 is 13 and then 13 is still greater so we want to decrease this now 2 + 7 is equal to 9 and that's correct 2 + 7 is equal to 9 and that's correct 2 + 7 is equal to 9 and that's correct so essentially we want to keep doing this but if it's in the case that it's too small then we just increase left right we do the opposite so how we do this is if um oh let's just copy this if numbers that left plus right um greater than Target right then we decrease right so right minus equal 1 and then else we just increase left so left plus equals 1 and that should be it because then we just do this check and then it Loops back here um and then checks if it's equal to the Target let's run it there you go oops um let's get the result here well that's how it runs it should run correctly there you go that is 167 to sum uh the second version and here's the code so you can look at it uh thank you
|
Two Sum II - Input Array Is Sorted
|
two-sum-ii-input-array-is-sorted
|
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`.
Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._
The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice.
Your solution must use only constant extra space.
**Example 1:**
**Input:** numbers = \[2,7,11,15\], target = 9
**Output:** \[1,2\]
**Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\].
**Example 2:**
**Input:** numbers = \[2,3,4\], target = 6
**Output:** \[1,3\]
**Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\].
**Example 3:**
**Input:** numbers = \[\-1,0\], target = -1
**Output:** \[1,2\]
**Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\].
**Constraints:**
* `2 <= numbers.length <= 3 * 104`
* `-1000 <= numbers[i] <= 1000`
* `numbers` is sorted in **non-decreasing order**.
* `-1000 <= target <= 1000`
* The tests are generated such that there is **exactly one solution**.
| null |
Array,Two Pointers,Binary Search
|
Medium
|
1,653,1083
|
863 |
200 Hello everyone welcome to my channel so in this video I am going to explain to you this binary free problem of all notes distance which is a very good problem and was also asked in one of the interviews so first we will discuss the problem a cup of this We will add semolina and we will quote, then basically in the problem, give me a target note and keep the wells. Okay friends, in this example it was asked that I have target nodal five and value of k is two, so I will get as many notes as possible from this note. I have to print all the notes on the distance which is 14813, so it would have been a very easy problem if I had been asked to print only the distance below, then I have no problem in printing it below, just the target motors and then its Print the distance below but the problem comes when I have to go up. Okay, so for this problem we were asked that if you have to go up and solve it, then how will you do it? So it is simple. This is to connect with your parents, okay so what I mean by connecting with penis parents is that there should be some way to go to the parents subscribe here, so for this we have to use an aap, okay so this way I can take a subscription, if anyone wants to note down and print the distance, then they should subscribe to it, otherwise if I go, then the distance of going, it means the school will ask at this time that it is okay, it is also from 30 to 25. So should I print it No if means like if I come to 1 left then I will be making a video and set for this to avoid this thing which will tell me that okay if I have done this then I do n't want to go back in the direction, I have to go in some other direction. Okay, so how much on 13 seven distance and any hair note, this is only Vansh, so in this way my 741 will be printed, so let me explain it to you more clearly. So first of all, two and 129898 were under the tree, 9 notes were started, this is a very simple problem, I will take the connection with my parents once and after that also they keep it in making a blind map MP4 Nodal whose name is free. Mode start subscribe now it will be useful so first of all I will take care of my result and interest 2229 so in this case I will return the result meaning if not then there is no point in doing 15 years now what is my next right? So that I have to connect with my parents, for that I create a transition Connect with Parents Subscribe to Connect every note with its parents, like if we have root and sugar, then initially the root node has a parent, so initially tap it. If I write then let me write more avoid connect with thread in paris alter note star root kill tree node star unvote pants today's tweet that your parents are [ __ ] so I your parents are [ __ ] so I your parents are [ __ ] so I made this function so the first thing I will do is tap this two roots okay If you get angry then I will return simple in that case and if one route is not null then what should I do MP which is the route which is the parental 12% of the traffic route and then I will go to which is the parental 12% of the traffic route and then I will go to which is the parental 12% of the traffic route and then I will go to connect its left children connect waste Ronit Here my route will go left route with parents dead and similarly which after this subscribe to connect the right side subscribe now see this I have set this quit now let me put more difficulty on the distance then the next part will be very easy The one is fine, how to do it, so I come up with an option, deficit target is fine, we can write this in small size because I have to go to the market, the end result is fine, this is my function and all the notes, click on me and see the bank. I will return the result if it is ok then if you want to make amazon moment then how will you make tiffin boy DSS Katrin Dheri ke liye target hai but hona hai this source but any me target and quantum of vector in temples and traffic jam I addressed the ignore meaning result Okay, so now what do I have to do? Now first of all there is a target national, this target is equal to null, so what should I do for this, I do not have to do anything, you have to type, then okay, this is how to attend and in which one, subscribe. Video Subscribe Target meaning why am I writing in school which I have not explained here, I have not subscribed then please subscribe, I was subscribed, that is why I had scheduled this visit soon that subscribe is ok, what should I do now then What do I have to do now what do I have to do its equal to zero k equal to zero means I have reached the decision on that which is k distance away so what do I have to do arrest posters pack in President Bush quiet target market value and remind me It's okay now scar difficult I have to subscribe left and right like I was so I have to mean that if I want to go there then subscribe it a target left ko ma ke minus one comedy ray ok deficit target right ko mar ke minus one Congress and things important, dips in comments, that's why I have written all this function, connect with sequence, then that is it, quite MP, target, Maa Kamakhya, minus one waist, this is so direct, so what is basically happening with this, subscribe and subscribe from below. It's working on how to adjust the respective and devices percent okay so basically it's submitting and white station on milli second point in this can throw a mean logic in this is to let me connect to the premises and ignore that further So it's a very simple problem, subscribe will solve the problem with a note, so if you like the video, please subscribe the channel. Thank you, have a nice day.
|
All Nodes Distance K in Binary Tree
|
sum-of-distances-in-tree
|
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._
You can return the answer in **any order**.
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2
**Output:** \[7,4,1\]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
**Example 2:**
**Input:** root = \[1\], target = 1, k = 3
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 500]`.
* `0 <= Node.val <= 500`
* All the values `Node.val` are **unique**.
* `target` is the value of one of the nodes in the tree.
* `0 <= k <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Graph
|
Hard
|
1021,2175
|
36 |
hello everyone welcome back and today we are looking at question 36 which is valid sudoku now instead of reading the description of the question i will go straight to the blackboard explain what sudoku is and explain the rules of the game and finally show you how simple this question can get alright so let's get straight to the blackboard okay so here we have a sudoku board now what is sudoku okay so it's a game we have a board and this board is nine by nine which means we have nine rows and nine columns now each row and each column will have numbers one through nine okay also this box is divided as you can see into nine smaller boxes here we have a box etc as you can see each box is three by three now as you can guess these boxes also have numbers one through nine so we have rows we have columns and we have these small boxes each one of those will have numbers one through nine so what are the constraints of the game so basically for any row and any column we cannot have any duplicates okay also for any box we cannot have any duplicate for instance if we have a five here let me ask you can we have a 5 right here well 1 we cannot do that why because we have a 5 in this row so we cannot have another 5 in the same row so what if we remove this five okay so let's say we have an empty spot right here can we have a five here well no again why because we have a five in the same column right here if we remove this five now we can have a five right here same thing for the boxes let's say we have a 9 here can we have a 9 right here i know 1 no because we have a 9 in the same row but also no because we have a 9 in the same box so for any number in the sudoku board we have three questions we need to ask hey can we find this number in the same row can we find this number in the same column can we find this number in the same box right and of course we need to answer no for all of those questions with which means this number is unique in that role in that column and in that box so um we know we need to traverse through the whole board and check every number in the board and ask those three questions but as you can see some spots are empty and the question is saying we can have or we will have a dot in these empty spots indicating that there is no number right there so if we are traversing through the board and we see a dot we can just simply skip that spot because we are not interested in empty spaces right we just want to check those questions regarding each number on the board okay so now how can we do that okay so let's say we are at this five right here so we can say okay um for any number we want to see if it's unique in the row column and the box so we can say hey we have this five at row zero we can also say okay we have this five at column zero and we can say we have this five at oh what should we put here how can we say in this box right here how can we identify this box or that box or any box on the board right we need a way to identify to uniquely identify each box so let's think about this if we know this right there then we will solve the whole problem so easy so let's see let's look at the indices of the sudoku board we have 0 1 2 and all of these numbers are belonging to this box right here ok we have 3 4 5 they are belonging to this box we have 6 7 8 they are belonging to this box same thing here zero one two for this box three four five for this and so on so a group of three indices are belonging to the same box so we can have okay we can have a zero index for this row okay and we can have a one index for this row and we can have a two for this row right same thing for the columns we can have a zero we can have a one and we can have a two right so how can we get these indices from these zero one two three four five six seven eight you know etc well since we said a group of three numbers belonging to the same box well we can divide each index by three right we can use integer division so let's see what happens if we divide the column by three and if we divide the row by three what happens well let's see we have zero divided by three is zero okay now what is one divided by three well it's zero point three etc but we are using integer division which means we will take the integer part only so one divided by three is zero same thing two divided by three is zero okay now what about three four five well three by three is one four by three is one point something but again integer division so it's also one five y three is one now six by three is two seven by three is two eight by three is 2. so now we can uniquely identify each box by the following this box is 0 comma 1. same thing as rows and columns this one is 0 comma two etc so this five we can find it at row zero at column zero and at box zero comma zero we can put a comma we can put a dash anything you want but this 5 is xbox zero okay good so now let's see this three we can say okay this three is at row zero this three is at column one this three at box zero so now okay once we know all of this how can we compare the numbers to each other let's say we have a five right here we're gonna say okay this five is at row zero but we cannot have duplicates but how can we check if we have duplicates well we need something fast and of course we need something that does not allow any duplicates now i would think what's a good thing to use for these constraints okay well we can use a hash set the lookup time in the hash set is constant we go off one and the hash set does not allow any duplicates so we can put all of these information in a hash set now when we go to this three and we say okay let's add the following information into the hash set we found three at row zero it's not a duplicate we found three at column r one not a duplicate we found three at box zero not a duplicate so what if we have a five right here okay we will say we find the five at row zero oh we have a duplicate right here it won't work what about if we have a five right here we can say okay we find the five at row one not a duplicate we don't see it yet we find five at column one not a duplicate but now look we find five at box zero we have a duplicate right here so not valid to docker board so that's it this is the question for each number we need to store all those information in a hash set which means our hash set will contain strings and these strings will identify each number okay so let's now look at the code and it's straightforward once we understand this so we said we need the hash set of strings so let's create that so we have set and this hash set will contain we said strings so we have string and let's call it scene which means these are the characters that we see it in the board so new hash set now what well now we said we need to traverse through the whole board so we need a nested for loop because we have the sudoku it's like 2d array right so we will say okay for int okay so for into i equals 0 i is less than 9 because of course we have 9 rows and nine columns then i plus then of course we will have okay for in j equals zero j is less than also nine because nine rows and nine columns then j plus all right so now what well now let's store the character that we are standing on in a variable right it will make the chord easier to read and i said character so character of non equal on board of i and j so here's i and here is j okay so in this case we have a five now what should we do with this five well first thing first we said if it's an empty space we don't need to look at it we just skip it right so we can say hey if this number is not an empty space then we are interested in it so and we have a character so we need a single codes and if it's not a dot then it's a number and we need to check if the number belongs to the conditions we just described now what will we need these three information about the number so we can store to the hash set we can say okay sin dot add that num plus which row we found that so which we can say at row plus just add the row okay and now we can say we have seen dot add we have that number and we can say on which column we found that right so plus at and this should be a t not an r so add column and then we add of course the column and finally we need to say on which box we found that number so cn dot add that number at box so we have at box now how should we identify the box we said well we said hey we have the column divided by three and the row divided by three now what is the row well we said i so i divided by three we have plus i don't know we can put a comma we can put a dash anything you want so and we need the column divided by three so j divided by three okay so now what we have this information that we will store in the hash set so we said if the number is not a space we need to check those conditions okay so we need an if statement right so if what well let's see if we cannot add this number to the hash set if we cannot because we have a duplicate in the row or if we cannot add it to the hash set because it's a duplicate in the column or if we cannot add it to the hash set because we have a duplicate in the box it's not a valid sudoku now it's important to note that this add function returns a boolean so now we can say okay if let's see if we cannot add this one to the hashtag because we have a duplicate on the row we need to return false so or if we cannot add it to the hash set because we have a duplicate in the column we also need to return false so or if we cannot add it to the hashtag because we have a duplicate in the box we need also to return false okay so let's put them right here we have them and we need reset to return false we need to return false okay so now if it's not an empty space we check all these conditions if we cannot add the number to the hash set because it's a duplicate on the row in the column or the box we just return a false so now we need before we forget close the bracket for this if statement and that's it if we finish the for loops and we did not return a false then we have a valid sudoku so just return true that's it okay so for instance if we have a five right here let's see what happens so we have five right here we go to the if statement is it an empty space no so we go right here we have this five we have the five at row zero now we are trying to add it to the hash set since we have a duplicate this add function will return a false now we have a not a difference so we're not false will become true since we have or statement the whole statement would be true and we will execute this false and we will return false now if we have let's look at this three we are saying okay we have three at row zero we don't have a duplicate so we have three at column one we will not have a duplicate and we have three at box zero of course we do not have a duplicate so we just go to the next number and that's it okay so before i run the code i just removed the extra spaces that i put when i was explaining the duplication in the row column box so it's the same code i just removed you know an extra spaces and such so now let's run the code and let's submit okay so now let's look at the time and space complexity now since we have a fixed sudoku board with fixed you know number of fields and we know it's always nine by nine it's fixed the time and space would be constant we go off one but if we have maybe a changing input and it's the board is not nine by nine anymore let's say we have an arbitrary number n we are looping through all the fields of the board and assuming that the length is n of the board we have n rows we have n columns the time complexity would be big o of n squared same thing for the space complexity if we have a valid board and it's filled with numbers we need to store all those numbers into the hash set so assuming we have n by n board this space would be a big o of n squared but again since this board is fixed we have a nine by nine board you can consider the time and space to be a big o of one i hope you guys enjoyed the video best of luck to you and i will see you on the next one
|
Valid Sudoku
|
valid-sudoku
|
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.
**Note:**
* A Sudoku board (partially filled) could be valid but is not necessarily solvable.
* Only the filled cells need to be validated according to the mentioned rules.
**Example 1:**
**Input:** board =
\[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** true
**Example 2:**
**Input:** board =
\[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** false
**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit `1-9` or `'.'`.
| null |
Array,Hash Table,Matrix
|
Medium
|
37,2254
|
201 |
hello everyone welcome to Mayu programming club today we will be solving another daily code problem and the problem's name is bitwise end of numbers range so the problem statement goes like this given two integers left and right that represents the range of uh left and right both inclusive return the bitwise and of all the numbers in this range inclusive okay so let's say the r left and right numbers are given to be 5 and 7 then what you have to return is bitwise end of all the numbers in the range okay so this is what you have to return okay so five and 7even both were included in the range and let's see the constants so left and right can be ranging from 0 to 2 to^ 31 - to 2 to^ 31 - to 2 to^ 31 - 1 okay so you know if we consider Brute Force way to Sol this particular problem then we can just you know loop our left and right okay turn a loop from left to right in this range and do bitwise end of all the numbers in the range okay but you know uh the number of numbers in this range is equal to 2 to^ 31 minus 1 okay so it is of the order 2^ 31 minus 1 okay so it is of the order 2^ 31 minus 1 okay so it is of the order 2^ 31 - 1 okay or you can say 2 to^ 31 - 1 okay or you can say 2 to^ 31 - 1 okay or you can say 2 to^ 31 so these are quite High number this is a quite High number of operations that you will be requiring if you are deciding to uh run a loop from left to right okay so the number of operations required will be of this order but these number of operations are significantly greater than the operation limit which is 10 to^ 8 limit which is 10 to^ 8 limit which is 10 to^ 8 okay so these this is a operation limit if the number of operations required by your program to solve a particular problem xce or become equal to 10 to^ 8 then you may get a to 10 to^ 8 then you may get a to 10 to^ 8 then you may get a t and your solution will not be accepted T is time limit exceeded so your solution will not be accepted so this makes this only this particular thing that the constants are so large that uh a linear solution will give you know uh time limit exceeded is the tricky part in this particular question so we should be uh devising a method so that we can come around this limitation of running a linear Loop so we need to make some observations here first of all let's see the binary representations from let's say first 20 numbers would be sufficient to make some observation okay so binary of 1 to 20 okay so these are binary representations so uh thing here uh which you can observe is like see the numbers which are having same number of digits okay so let's say we you know try to concentrate on this particular part okay from 4 to 7 let's pick this part okay let me try to yeah take it here so it's fine now okay I guess this should be working now okay yeah I guess it's visible enough anyways I'll be writing it again also here on this left right part of the screen so you know this is a number and its binary is on this side so 5 0 1 6 1 0 and 7 1 so if you see a pattern here that if let's say the range was from 4 to 7 okay both inclusive so if the particular bit is uh set in four which is the leftmost bit and it is also set in seven then all the numbers in between we have that left Mo left most bit set okay uh this is the observation here which you can make so uh what we can say if left part of binary representation matches in first and the last number of range then this left part is as it is present in all the numbers of the range all other numbers of the range also okay numbers of range also okay so let's say there was a pattern something like this and here also it was repeated so this is your start and this is your end then all the numbers in between should be having this particular pattern at least we cannot say what things will be present here all the numbers will be in between but we can say for certain that at least this one1 will be repeated in every number that is there okay so this is a observation that can help us to you know arrive at approach that can solve this particular problem uh other than that you know why we are considering this common left part okay so you can say this is common left part okay or more specifically you can say that common prefix similarly if you want to extend your observation you can do so if let's say we are considering all the numbers having equal number of binary representation bits so if we consider till here also so you see that uh in 8 this is set and in 15 let's say uh range is from 8 to 15 so 15 this particular one bit is set so in all the numbers that are there at least this part is set okay you can see all the numbers that are there okay so indeed our observation is correct so let's try to use this observation to come up with the approach that can solve this particular problem so what we'll be doing is uh we will be finding the uh common prefix find the common prefix so to find the common prefix we have to somehow you know delete uh whatever part is not matching in these two numbers so let's say if you were to end four and S all the numbers between four and seven range so you have to remove this part which part I'm talking about this part because you know this part is not matching in four and S so this part should be removed this part in four and this part in seven so what we can do is we can use a so those of you who are not familiar with binary operator binary operations there is a I'll also Pro I also try to provide an link of an article where you can read about binary operations okay so I'll try to find some something on this and then what I can tell you is uh there is a right shift operation which shifts the bits towards right okay so let's say we apply uh right shift operation and uh we shift every bit one by one till uh two numbers become equal what I mean by this is binary representation of 4 is 1 0 and 7 is uh 11 1 so till both numbers do not become equal we keep binary shifting uh their bits by one place why only one place because you know we want to just stop at point where these two numbers become equal so let's do that uh after first binary shift towards right okay uh these numbers will be four will be something like uh this okay and your seven will be something like this okay and you will be counting how many times you shifted them their bits towards right okay so after second binary shift your four will be this and your seven will be this so right now what we can say is that you know these numbers are right now equal so how many times do we binary shifted them so it was the first time and it was the second time so uh we do the binary right shift two times okay so what we will do when these two numbers will become equal we will pick either of these two numbers and uh see what is the binary representation we are having and so two was the number of binary right shifts number of right shifts so you will simply do number of left uh shifts uh these number of times number of right shifts okay do a left shifting operation by shifting bits these number of times number of right shifts so what you will uh end up is end up with this uh this particular number okay so it was two so it lead to this particular number and this is your answer if you ask me what will be the answer since uh there is a property in end that let's say there are some binary numbers okay and we have to do the end operation here so the result of uh end of any two numbers will be carried out with uh the entire end operations that are there what I mean by this is let's say all of these are one okay and you do binary operation here only so it resulted in zero now see uh this zero will uh do binary operation with one zero and one and will be zero only and this zero with this one so Z only so this Zer with this one Zer only so uh this is how this thing will keep continuing uh so the effect of a certain bit is spread throughout uh the you know end operation that we will be having so if these bits are not equal so they will anyways cancel each other out and whatever will be the common prefix between the first and the last term of the range that will be our answer okay so this will give you common prefix so this is the common prefix and what will be the equivalent uh decimal uh representation okay what will be the ual number corresponding to this binary will be our answer so let's find the common prefix okay and that will be our answer for sure and if you ask how many uh times this particular Loop can run uh okay first let me write the logic here then we will discuss the time complexity also space complexity wise we will not be taking any anything so it will be a constant space solution so what you will be doing is you will be counting the right shifts so right shift count while left and right are not equal so last and the first number of the range okay you will right shift your left by one bit and similar thing you will do for your right which is the last number for your range okay once you are done with it you will increase the number of right shifts that you have done right shift count okay now once you are out of this Loop so left and right both will become equal so you can pick either of them let's say I'm picking right here so you will be returning this right left shifted by right shift count number of times okay this will give you or let me take it in a variable and let's say common prefix okay so we'll be returning this common prefix let's try to submit for sample test cases whe seeing whether this is getting accepted or not so as you can see it's getting accepted for at least sample test cases let's submit for the final evaluation so this is getting accepted for final valuation after final evaluation also uh so that is how we'll be solving this particular problem if you are still having any doubts or any queries in general then you may ask them in the comment section thank you for watching have a great day ahead and uh yeah before ending the video I forgot uh completely uh I'll be telling you what is the time complexity here since in is a 32bit data type generally it's the case in Java or at least in C++ so there are 32 bits so the number of operations that will be required will be of order 32 okay so these will be the number of operations that will be required so time complexity if you take this as a constant is you can say approximately constant but if you are concerned with a particular threshold then it's order of 32 and for space complexity this thing is of constant extra space we are not using any space here okay so these are the complexities so thank you for watching again and have a great day ahead
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
764 |
Scientist A Hello Hi How Are You Hi What Are You Doing Good Welcome To The Record So City Will Do The Largest Per Sign In This Is It Is Given That You Have A Matrix Of Band Se Will Show You To Find The Maximum One You Wish You Can Make Show Apps Please Mention In This One So In This Day That Someone Else Becomes 100 Ko First Let Me Personality Member Man Question And A That And Like You Can See That They Have Been Or 21 Maybe Now In Which is you can make complex matter of Mother in 200 words meaning of more than two of the meaning is not meanings and f5 one 000 can see you can make that youcam makeup plus natives ke dushman dhan dushman ke adhishwar 200 dushman ko dushman vacancy der is after two years of order hai tu That and you can't make mode on in educational makeup plus that is mode on of the two english case daughters that nursery is to a doctor is of three daughters reel and order is of this is to and sis and trees to loot this of order the One 's Marriage Se Jo Power To Egg Vacancy Episode 's Marriage Se Jo Power To Egg Vacancy Episode 's Marriage Se Jo Power To Egg Vacancy Episode 482 That I Because Of Development Issue Will Take Left In The Reserves To Take You Can Take The Crime Ares 2nd Year To One Saar Present It Will Take Right The Two One Saar Presented Soon To One Saar Present Jai Hind this case will take up the Russians Left Section 370 Section 310 Right side the Ativan including the video descendants and 3041 friend like no success but 1301 Effigy in Delhi Government sources of water for this Vikram of water for but nine this after 354 Should How Will See How Will Get How Will Find A Disease After How Much For Men At Work Should Approach For The Cockroaches Early In The Morning Will To Show Will Make To Research 1514 Left Alone For The Day Lu Ne Rough Theek Hai Sunil Shetty Adhikari Rampal All Will Make A Complete Matrix That And Will Start Beta Testing Will Start Doubting OnePlus One From Left To Right From Left- Right From Left To Right From Left- Right From Left To Right From Left- to-Right to-Right to-Right Shoaib Vacancy Yes Yaar Iss Band Se Ribbon Ones went into the three and 435 again gas 12345 year counting one that they accounting one give knowledge 12345 to 0123 liye 45 youth work to navinagar me ke zero big boss fazinil me account isro day again specific in the * in same manner E Will Count From A Bride From Right To Left Member Right To Left From Right To Left Member Vikram 19223 Liye Bikram 45 Inch M & B 19223 Liye Bikram 45 Inch M & B 19223 Liye Bikram 45 Inch M & B Switchgear Four Initials Three Little Two Little One Slow Dispur Roy Bank & Ullas - Slow Dispur Roy Bank & Ullas - Slow Dispur Roy Bank & Ullas - Shiv Will Go to medium to day speed is zero 15209 Vikram Bantu a prophet account for the lion that take sorry bill account from your direction from top down from top students tremble into the three men for more than 500 12345 to 1234 9045 two three four five 2018 option will count from bottom problem button to love oo hua hai members vikram 1234 5252 ki rishi 12345 1000 152 dish well 10 vikram thakur no 12345 to 13745 this father for the time major for matrix now The Now It's Time to Get the Two Get the Maximum Order One Which They Can Make Some Will Simply Take No Minimum of One Can get a minimum this vansh of minimum of laptop is DJ hai kamar right off kariye a comedian off kariye ka kaam aaa apache se hai so itni hi-fi ko mujhe yaad hai so itni hi-fi ko mujhe yaad hai so itni hi-fi ko mujhe yaad vacancy December described in this life way kam one kam 851 kam 500 Vikram Vansh That Minimum Plus You Can See A Raveena Place Which They Can Get Is After Order I One And Will Take Kam Acts Which And Will Take Of Medicine Maximum Vacancy Ita He The Order And Minimum Plus A 200 Special 05261 One Max Swift A Swad Research Organization Swept 18 every point will have to be the absolute minimum but see later to come forum after and can we can only make a place which after paying them again will get one will go thriller 2108 you can see the match made again will get a good this Points Apne Switch Off Water 155 Dushman Diya 20500 Again Will Get One And You Will Get One And It Also Two Not Possible In Which They Can Get There Discretion Of You Can Go End Points Dehri On Son Effect Exit Point No vacancy but we can make a plus a we can make a plus that enemy that they can make an enemy we can make this place that a this cutting we can make this place so 2424 hundred buses crossover tickets that they can simply get harder A minimum of to come off and work to kapoor dated 2nd so the show that is mean plus notice under orders max off me dabi laugh light off now it's two souls welcome to new vacancy dabi can get only place witch after To Know Your Welcome Edition You Can Also You Can Make Play Services And A To Z This Point 423 124 Problems To Again You Will Get To The Point You Can Not Make Any Dar Place So 5124 Vacancy Date No Vacancy But You Have Got A Maximum Plus You can say place after which is no one knows you will get exactly one action of two is the order e agri collector and research to 9 - manner you will go on and you can find what agri collector and research to 9 - manner you will go on and you can find what agri collector and research to 9 - manner you will go on and you can find what you can get the order S2 even S U CAN GO AHEAD THIS POINT 0 CAN NOT MAKE ANY PROBLEMS YOU CAN NOT MAKE ANY DARE PLACE SO THAT YOU WIFEO WELCOME HER SO WHAT WILL DO YOU WILL CHECK CHIEF TECHNICAL GANG KA MAJAR MEIN ZERO WICKET NULL DELICIOUS YOU WILL GET PLUS WISHES Assigned to prof nested if implemented limitless solution is vacancy dot muslim suicide note is global weeks fight must morning app related wear install bones now they have minds which indicates that you feel dowry position of tools for is this what is the role antigen vacancy date Feb 06 Manor is also field dowry making the two shoulder i.e. no dowry making the two shoulder i.e. no dowry making the two shoulder i.e. no fare for matrix left right now an album Hafeez is also a gift power grid is of these women everywhere in understanding current position tiffin united 9th class is vihar phase simply amazed account is zero And certification in the same manner behaved in this in the same manner which has often here in the same manner Bhairav shoulder hair Soviet absolutely Bhairav shoulder hair Soviet absolutely Bhairav shoulder hair Soviet absolutely maximum plus in the morning traversing and mix it is become if it is off day it broke absolute minimum of left right up and down subject But Current Plus Certificate Max Vikas Mein Bhi You Have Previously Found The Maximum Plus Sorry For That You Are Less Than Happy 108 Good Returns From Time you can see there you can see the place has taken the final match time love oh so you can not so you can stop you should forget you ft one examples which you have already seen some braver traversing the matrix shoulder only ₹ 50 can Simply Tag shoulder only ₹ 50 can Simply Tag shoulder only ₹ 50 can Simply Tag Minimum And Jasvir Approve Tenth Maths So That You Can Return An Answer Ayurveda Nurses And Do Nothing Else I Bhai Baba Make For Education Logic This Logic How You Can Say If This Updater They Can Make Haddi Maker Plus Fennel 125 Ka 2018 With The help of measurement subscribe school union ka 1828 subscribe 6 hair to the history subscribe the world will be from top to two but what is possible from which you can make a 133 iffiko sirf mohabbat do apk file account of one-two days that is the apk file account of one-two days that is the apk file account of one-two days that is the Bigg Boss You Can Take To Record Switch Of Three Languages For Then Egg This Difficult Three Languages For Then Egg This Difficult Three Languages For Then Egg This Difficult Motor For Indian Model 252 Self Pure Minimum Switch On This Fact Which They Can Make No Appeal For That Bigg Boss This Is Baby Position Minimum Requirement Developed Minimum Thick Now I can not make any of the plus 20 after order mode on two because you have left side have only Assam Bihar Only one that is account to like this point issue will account for the good night so every point I have account to so that is ours Order Suditi Global Logic Nirbhay Bhaiya Minar Is Acid Bases Day Welcome One With Content 1510 Know It Will Meet Again 150 Is Account Baby We Are A Tata Zero Because When Say Dad Already Fan A Andhero Sudhir We Can Not Make Any Place Which Consists Of Fun In The Morning Can Simply em 108 speed hai aa abhi hai he minimum plus because active on ki bihar plus ladies ko bhi too so they can see but they have only one plus hai mp board 10 white irony only other is vikram 2318 only ko 180 shocked by this Position 220 Can Take In This Manner They Can Take Him He Went For Reading Answer Will Story Of Values For Division Feel Happier 10th Maths Values For Division Feel Happier 10th Maths Values For Division Feel Happier 10th Maths Dayan Ne Suicide In This Video With Amazed E
|
Largest Plus Sign
|
n-ary-tree-level-order-traversal
|
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`.
Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`.
An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s.
**Example 1:**
**Input:** n = 5, mines = \[\[4,2\]\]
**Output:** 2
**Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown.
**Example 2:**
**Input:** n = 1, mines = \[\[0,0\]\]
**Output:** 0
**Explanation:** There is no plus sign, so return 0.
**Constraints:**
* `1 <= n <= 500`
* `1 <= mines.length <= 5000`
* `0 <= xi, yi < n`
* All the pairs `(xi, yi)` are **unique**.
| null |
Tree,Breadth-First Search
|
Medium
|
102,775,776,2151
|
69 |
in this video we'll go over leak code question number 69 Square < t x given a question number 69 Square < t x given a question number 69 Square < t x given a non- negative integer X we need to non- negative integer X we need to non- negative integer X we need to return the non- negative s otk of X return the non- negative s otk of X return the non- negative s otk of X rounded down to the nearest integer we also can't use any buil-in exponent also can't use any buil-in exponent also can't use any buil-in exponent function or operator so that means we can't raise x to the 1/2 power or use a can't raise x to the 1/2 power or use a can't raise x to the 1/2 power or use a built-in square root function so for built-in square root function so for built-in square root function so for example if x was 100 then we'd return 10 since the square root of 100 is 10 but if x was 8 then we'd return two since the s < TK of 8 is around 2.83 and we the s < TK of 8 is around 2.83 and we the s < TK of 8 is around 2.83 and we need to round down to the nearest integer now one way to do this is to just check every number 1 by one so let's say x is 16 we would start at 0 and check if 0 * 0 equal 16 it doesn't and check if 0 * 0 equal 16 it doesn't and check if 0 * 0 equal 16 it doesn't so then we check 1 * 1 and we'd keep so then we check 1 * 1 and we'd keep so then we check 1 * 1 and we'd keep repeating this until eventually we reach 4 * 4 which does equal 16 so now we know 4 * 4 which does equal 16 so now we know 4 * 4 which does equal 16 so now we know that 4 is the sare < TK of 16 and we can that 4 is the sare < TK of 16 and we can that 4 is the sare < TK of 16 and we can return four now this works and since we start from zero and we would only have to count up to the square otk of X this runs in O of < TK of X time this is not runs in O of < TK of X time this is not runs in O of < TK of X time this is not bad but we can make this even better by using binary search let's say x is 16 again which means that we know that the square root has to be somewhere between 0 and 16 binary search starts at the number in the middle which is 8 * 8 is number in the middle which is 8 * 8 is number in the middle which is 8 * 8 is 64 which is too large so we know that the square root has to be less than 8 so we can eliminate all the numbers greater than or equal to 8 then we'll check the number at the midpoint of 0 and 7 which when rounded down is three 3 * 3 is 9 so when rounded down is three 3 * 3 is 9 so when rounded down is three 3 * 3 is 9 so now it's too small so we can eliminate all numbers less than or equal to 3 and we'll go to the new midpoint 5 * 5 is 25 we'll go to the new midpoint 5 * 5 is 25 we'll go to the new midpoint 5 * 5 is 25 which is too large so we can eliminate five and anything greater and now we finally reached four which is the correct answer now binary search runs in O of log n time and as you can see from this graph an algorithm that runs in O of log n has a better time complexity than one that runs in O ofare root of n so binary search is the better approach now why exactly does binary search run in O of log n time well with each iteration we eliminate around half the numbers until we Converge on a single number so the question is how many times do we need to divide n by two until we reach one let's say k is the number of times we need to divide n by two to reach one then the equation is n / 2 the reach one then the equation is n / 2 the reach one then the equation is n / 2 the K power = 1 and we need to solve for K power = 1 and we need to solve for K power = 1 and we need to solve for K let's move 2 to the K power over to the right side and we can isolate K by using logarithms meaning that we can rearrange this to be log of n with the base of 2 equal K so now we know that it takes log base 2 of n steps to complete the algorithm but in Big O notation we ignore the base so we say that this algorithm runs in O of log n time now let's look at the code and solve this in Python let's say x is 9 so we know that the square root is somewhere between 0 and 9 we'll establish two boundaries left which will equal zero and right which will equal 9 we'll use these two boundaries to narrow down the range of numbers then we'll enter a loop that'll keep going as long as left is less than or equal to right so first we'll calculate the midpoint number by doing left plus right / 2 then rounding down left plus right / 2 then rounding down left plus right / 2 then rounding down so here it's 0 + 9 / 2 which is 4 .5 so here it's 0 + 9 / 2 which is 4 .5 so here it's 0 + 9 / 2 which is 4 .5 then rounded down is four we're then going to multiply mid by itself to find its square and at that point three things could happen the result could be less than x greater than x or if neither of those are true then it must be equal to X now I'm going to add a quick note here in Python we don't have to worry about integer overflow but in other languages such as Java or C++ doing mid languages such as Java or C++ doing mid languages such as Java or C++ doing mid * mid may lead to overflow So to avoid * mid may lead to overflow So to avoid * mid may lead to overflow So to avoid that you could write this condition like this if mid is less than x / mid so we this if mid is less than x / mid so we this if mid is less than x / mid so we just divided both sides by mid and the condition is still the same but now there's no risk of overflow and the same thing goes for this line here where we do left plus right but since we're using python here we don't need to worry about that and we can just leave it moving on Mid * mid is 16 which is greater than x Mid * mid is 16 which is greater than x Mid * mid is 16 which is greater than x so we'll jump to this e block and update right to be midus one which is 3 now we know that the square root has to be between 0 and 3 so we'll repeat this process mid equal 3 / 2 rounded down process mid equal 3 / 2 rounded down process mid equal 3 / 2 rounded down which is 1^ 2 is still 1 which is now which is 1^ 2 is still 1 which is now which is 1^ 2 is still 1 which is now less than x so let's update the left pointer to be mid + 1 which is 2 next pointer to be mid + 1 which is 2 next pointer to be mid + 1 which is 2 next mid equal 2 and 2 * 2 is 4 which is mid equal 2 and 2 * 2 is 4 which is mid equal 2 and 2 * 2 is 4 which is still less than x so let's increment left to Mid + 1 which is three now left to Mid + 1 which is three now left to Mid + 1 which is three now left and right are equal to each other but we still need to do one more iteration to check that number so mid equal 3 and 3 * check that number so mid equal 3 and 3 * check that number so mid equal 3 and 3 * 3 is 9 which is finally equal to X so we can go to this else block and just return mid and we have successfully found the square root of 9 now let's do an example where X is not a perfect square let's say x is 7 this time again we'll set up the left and right bounds to be zero and 7 and now mid will be three 3 * 3 is 9 which is too big so three 3 * 3 is 9 which is too big so three 3 * 3 is 9 which is too big so let's update right to be two next mid = 1 and 1 * 1 = 1 this is too small mid = 1 and 1 * 1 = 1 this is too small mid = 1 and 1 * 1 = 1 this is too small so left will now be two mid is also 2 and 2 * 2 is 4 which is still too small and 2 * 2 is 4 which is still too small and 2 * 2 is 4 which is still too small this means we'll have to update left to be three and now notice that left is now greater than right that makes this Loop condition false which means we weren't able to find any integer that is a square root of x so at this point we know that the square root is somewhere between 2 and 3 but since the question asks us to return the square root rounded down to the nearest integer we can just exit the loop and return right now why do we return right and not left well if we've gotten to this part of the code that means we've reached a point where left is greater than right so if we return left then we would be rounding up the square root but since we need to round down the square root we're going to return the smaller number which is right so the square OT of 7 is around 2.6 2.6 2.6 and 2.6 rounded down is two and as you and 2.6 rounded down is two and as you and 2.6 rounded down is two and as you can see right equals two so we return two and we are done
|
Sqrt(x)
|
sqrtx
|
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.
**Example 1:**
**Input:** x = 4
**Output:** 2
**Explanation:** The square root of 4 is 2, so we return 2.
**Example 2:**
**Input:** x = 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
**Constraints:**
* `0 <= x <= 231 - 1`
|
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
|
Math,Binary Search
|
Easy
|
50,367
|
1,466 |
hello friends so today we gonna discuss this problem from the it quote we click on test 191 problem number one four six reorder routes to make all paths lead to ct0 so you can read the statement but the statement actually states that there are n cities with numbers from 0 till n minus 1 and they are directional which means there is a connection from A to B and all the connections are given the main thing you have to remember in this question is it is a network of 3 which will help us to know that there is no cycle in it which will help us to understand that if there is a path from 0 till 1 or 0 till 3 there should not be another path from 0 to 3 also there is only one path from 0 to 3 you cannot optimize it so you cannot run like you can say that you can also read 0 from 3 to this path and also through this path this should only be one path with ok and then these are by like these are directional in which 0 is directed towards 1 and 1 is the attitude towards 3 which is given in the question now you want to change the direction of some of the know some of the edges such that every city will be directed towards you what it means is because if we started you know you can say that if we start at 0 or if we started any node there should be a directed path from dot go towards 0 and you can easily start there is a directed path from every node toward 0 so you have to switch some of the directions minimum number of directions such that you can always reach every city from every city to 0 I hope you understand because as you can see in this there is a H from total one but so you have to flip this so that you can reach from one till 0 this is clip this is crossed this is also this edge is also not valid so you have to flip it this is valid because you can empty the flip you go through this part this is also valid because this is dated from four to zero but this is not valid so you have to flip it so the number of flips is equal to three so same for this question so what you can easily do here is I take it to a triangle I have used BFS here you can also use some other method I have not seen the solutions of other submissions but I have used PFS so what I have done here is that this is the first graph which is given in the question this is dieted but to travel to every node be for us make it bi-directional we node be for us make it bi-directional we node be for us make it bi-directional we make it by directional but then if we make bi-directional we will lose the make bi-directional we will lose the make bi-directional we will lose the information of which like big city is directly towards bit city - we can make directly towards bit city - we can make directly towards bit city - we can make a map in which people store all the information we have get that desert dated edge comes little one there's a two acted edge from one till three and so on so this is stored in the map or you can use estate okay so now I have user set here so this is sent there and I have made this bad directional girl now I am using a queue and just am pushing everything into queue in a BFS manner so because everything should die attitude toward zero is our starting point you will first giro in the cube now we will go towards the children of zero because zero is not visited we are only going to move it to the children which are not related okay because one and four are not visited you can make a visited array pop out of this tube zero push its children in the cube which are one and four and see whether it's children are visited or not because if children are not visited now and we can check what is the direction from 0 till 1 because this is the first path we can easily see to reach to the 0 every children should point towards experient because let's see if this is a children of one if it points towards this node which is its parent and one is pointing towards its parent so zero is the ultimate parent because it's a tree which can you assume to be a rooted tree rooted at zero so every one should point towards its parent this is not pointing to verges parent it is pointing towards this so you should flip it for this is pointing towards its parent so this is fine okay so for every children of any parent which we are processing in the queue we will check what I its children and whether they are pointing towards its parent if they're not pointing towards its parent then we have to flip them because this is not pointing towards our spirit so we have to flip so we will count the total Muslims and how we can check whether it is not pointing or pointing we can check whether this path which is zero till one if zero to one path is present in the set which means that there is a path from zero to one and it is present so we have to flip it if there is a path from 1 to 0 as present we don't have to flip so that's why I said comes handy so we will just do the BA PFS in which we first push 0 then we will push its children and whether we will check whether there is a path from 0 till 1 yes there's a path present from 0 till 1 so we will flip that this will become first flip then we will push the children or 1 which is 3 then we will take out the next children so we will push the children of 0 and 4 okay now we will push out the first children which is 1 and now we will check all the children for one because this is a by dextran there are the children for one will be 0 and 3 but-- okay so because we will be 0 and 3 but-- okay so because we will be 0 and 3 but-- okay so because we have said already check 0 and 1 we will not check this again so that's why we will check only for those cases of the children which are not visited because with respect to 1 3 is not listed us so we will only check for those edges between the parent and the children all the children which are not visited so because three is not visited we will check whether there is a road or there is a path from one till three yes is a path from one till 3 so we will make this outlet and then we will push three and because there no other children we will come out and then we will take out four because there is a path to four children are zero and five because this is a bi-directional graph we will check is a bi-directional graph we will check is a bi-directional graph we will check we will only process which are not visited so that no one will treat children will be four will be filed and we will check whether there is a so do you go and four we will check the children of this is this and these children so this is also will be checked earlier I have not actually written down here for four will consider whether the children of 4 which is 5 is pointing towards the parent or away from the bed so because it is pointing I'll cook it this is not this is there so this is pointing away from the bend so this is considered this is 3 and then 5 expose in the cube then we will pop out 3 and same we will do for 3 will pop down push down 2 and 4 5 because when we are 5 there is no children so we will and 5 is the children for pipe but because it is visited we will not do anything and say important and then we will come out of this Q and Q will become empty and we will do this until the queue is not empty I'll tell you more through the code so you can make that essentialist the visited array and up set for the peers to store whether this path that it path exists or not so you first memset the whole with stated it to be false because everything is not visited then make the decency matrix I essentially sorry you filled that make it bidirectional and also insert this information that there is an edge from u to V which is this okay now make a cube push that you doing that total in slice to be 0 then we will do until Q is not empty take out the first value from the cube which is 0 then Q dot 4 then B we will only process this if the element is not positive so if it is not visited we will first make it a visitor then we will iterate over Silman push them in the queue and now what we have to do we will check whether this Silvan is visited or not because what we are told you the children of 4 is 0 and 5 and we have processed this edge when we are on 0 because two children on 0 or 1 and 4 so we have processed this as before we will don't have to process this as before again after 4 and 0 so we will only process the children of any node which are not visited ok so if it is not visited the children because we are treating with the children if the children of this parent is not visited and we are counting that whether there is an edge from key till this key means the parent and this means the children so if they if this is present then we increment the total okay so now what does this means that there's a edge from parent to children which is not wrong we have to find a edge which is from children to parent if they saw H then we'll increment account and then we will come out of this while do till this M it become empty and then we just print out water so this is accepted you can also increase the speed by making the set unordered you can also do that but this is accepted also I hope in this and logic as well as the code if you still have any doubts please mention not in the comment box thank you for watching video I'll see you next time bye
|
Reorder Routes to Make All Paths Lead to the City Zero
|
jump-game-v
|
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.
This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.
It's **guaranteed** that each city can reach city `0` after reorder.
**Example 1:**
**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 2:**
**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 3:**
**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0
**Constraints:**
* `2 <= n <= 5 * 104`
* `connections.length == n - 1`
* `connections[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
|
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
|
Array,Dynamic Programming,Sorting
|
Hard
|
2001
|
93 |
right so we have given to the equation is a restore IP address and we have discussed about this so I will recommend you please go for the first part of this video and uh understand how we have implemented the uh backtracking okay so in the backtracking what we have taken a list right that is a list of string and we will contain all our current IP that is possible you can see possible uh IPS we will store there right here like you can see we are storing right so we will store on the result by joining the uh dot right all the uh we can say uh with the all the segment we will add onto the string and then we will add on to the list right and then we are doing that so I will recommend you please go through so that you will understand these three uh things that we have discussed right so if that is it having a three digit having then we will we have to check what is it uh having three digit right and they will check the 255 not so not more than 255 as well the first character so uh if more than one length is more than one right so we should not see what uh this one right is to know the first character should not be 0 to write so those are those things we have already discussed right so I will recommend please go and see this video okay so we have not discussed here uh the complexity I'm sorry we have not discussed about the complexity so let me give you one given it I'll take another pin yeah so what we have given string is right we have given a string s and uh it's uh if you represent that string into but uh what uh integer sides so if a string s we are going to represent in what integer n right so for each integer what will happen at most M digits we have right so if we'll talk about the all the possibility uh for the uh segment right that will take what M into n right and for all those possibilities we'll call M to the power n minus 1 because total what how many uh digital there any integer will be there right so positivity will be m to the power n minus 1 will be there right so we have to check all the uh integer all the digit all digit of n like let's see we have four digitized so in the four digit we have to check with the one is one have one digit right so we will check for one digit right all the possibility segment possibility will check right so that is that will go to O into MN to enter it and if we'll talk about the total complexity so it will talk m to the of n minus 1 and M to the power n and then we will return m to the Over N into n write this one but if I'll talk about the space complexity so all the uh all the current IP right before putting the result it will take o of n right because we have to we are using what current IP we are talking taking you'll see here uh here right we have taken current IP see so these will before adding on to the list right it will take what o of n size right of n size so that we have talked about right and you will take on one size and for all the for each element right for each calculation you can say for each solution it will take what M into n that we have already discussed right and here we are already first and uh for all the operation like it will take M for all the digits you can say m minus 1 it will take and so it will come M into n or you can say okay now we are talking about iterative approach if you're not understand please bring me the comment okay I think this is very easy question right so let's go to the iterative approach right so in this we will take three uh checks right first check we will take through the length check if length is equal to one so it will give true or false right here second check we will check is 0 at the first CAD in the segment so we'll check through my segment will take and if the segment have start not equal to 0 right if that is not equal to zero means it will return true then third check will check is less than 225 right that we have seen so we'll take condition 3 right and we will say this name my segment start and length will pass so we will check first the length is less than 3 right or we will check if the we will take the substring of start index plus length we will go and we'll compare with the 255 if less than equal to 0 that means we have right then it will return to otherwise it will return false right so three conditions will check these three condition right length check e0 at first in segment and is less than length 225 right I think you have understood right so uh let me represent this segment let's suppose we have yeah you can see here right we have this one uh this string is given it so I'll take the first 255 okay so this is 255 first uh let's see first we have 255 right we are considering then we have to 55 then what we have 11 we have and then 135 let's consider this one so this is valid why we are getting value this was valid because the first check is a length is equal to 1 right if length is equal to 1 then it will return true right so next we have e0 at the first card so these two conditions are not having these things and it will say it's true now it will come to uh is less than 225 right uh these two are giving true right now we are less than 225 so we'll check that condition so in the condition you are saying we have to check 225 right so it is a 225 but not more than this right so it will also give true right so three functions that we have created lens check is Boolean care and easy less than right so is three these three will give our uh we have the Boolean checks and these Boolean checks will give true then what we will do we will come to our uh this in this condition and this uh this is our function in which we are passing string s length so here if you'll see we have answer right and we will return this answer finally right so what we have to do for each answer we will add the answer right so if we'll talk about here we are adding so till we will reach here first we will go through all the steps right so if this string is given right this string is given s right so first of all what we will do let's suppose we have 2 5 then I have one and three five correct we have so what we will do uh we will start with this for Loop right so we will start length one we will take and we will check one we are passing one and comma s dot length minus nine so we will check the length right so what is the length we have given 0 1 2 3 4 5 6 7 8 9 10 right we have given ten so what we will do here first we will start with the length uh from the max will get we are passing Max we are giving Max and sorry Max we're passing 1 and 10 minus 9. which one is Max right so it is coming what 1 and 1 only right so it is given one so we will start with one okay so it will go to less than equal to length three so if you will start with the length uh this one right so it will go to what uh 0 1 2 3. so okay so it is counting from one actually this is thing correct so we'll start from here to here right this three length will go and similarly this is saying the length should be less than equal to this and then minus will go right either this or this if length is a string is less than right so in that case we will go to maximum its length minus 3. and plus so what we will do we'll pass the first uh first segment we will pass and we will say s 0 and this link right will pass so first length it is going segment so we'll check in into the uh e segment thing so first segment is uh okay you can say 255 is okay that's why we are getting in the first output we are getting 255 it was okay next we will check for this uh another length right so this like this one only so you can see what we have one we have then we are passing length is what uh 10 we have right 10 11 whatever we have given 253 3 and 2 okay 9 and 2 11 total 11 we have right so now we have length previous length we have right so previous length was what uh 11 minus 9 we had right we have did 11 right minus 9 it is 2 now we are doing what uh we are doing plus one right so the minus 6 we are doing more so total length is 11 minus we will do what uh length is 2 we have and then we will do six so is eight so we will start with five right so 1 and 5 will we have to start with the fifth position right uh we'll say that so it will start from there and then we will move to its uh what length right so this is this length is 11 we are doing what length is previous length is what we have given uh where is the application here this one this length for each length we will start from there right so we'll move to from here let's see we are starting from here then we are starting from here right so till that we will go to the its next position right one two three four five we'll go to here first time like that we will move each time we will move to each time we will move right like that and then we will check the segment we are passing another length right we are passing another link so we have started with the 0 to length now length one is what uh we will replace with the length one and length here will be length two right there so what is this length one is what start index and length is power that we are passing right in the length starting index will pass and the length will pass so always we have to see the starting length and the previous length right so if this is our starting length right so how much length will go we will move right then we have to calculate right and similarly we will go for with the next one in which we get this starting length we'll get and uh the another what we will say the length right so like that we will calculate so in this we will do link that we have uh 11 we have then we will do whatever the length we will one two three five view whatever we have that will pass and then length 2 will pass similarly will go there okay and in the last if all everything is done right everything is working so we will add on to the length how we'll do through the join and we'll pass zero to length one this is the length one and this length one plus length two like this and these are the substring we are calculating so four times we will do and we will make our IP right okay so it can it may come like this one first time it will come this one then it will join with the two 255 again right then we'll do with triple one then it will be 35 like that four times we will do so we have starting from 0 to uh from 0 to its length right then we have started with another length that we will to length we have gone through here right next is what this length right and so we'll do this length plus another length right this one we'll do L1 plus L to L3 like this we will do and it will calculate finally we will return our answer right now if we'll talk about the complexity we have already understood right in which we have taken all the string into integer right and if all for each integer we have to go for m in digit side so there is total M minus 1 a possibility we have what here total M minus M possibility we have for each checking right and validating right so whole segment is valid so it will take o m into n and similarly what we have time complexity if we will calculate so we will multiply this one so o m to the power n minus sorry omm to the power n this will come now uh similarly if we have the curve like the current IB we have so we will take here on uh other value we are taking right so that will also take o of n to before uh adding into the answer here we have answer and then and we'll do M into n and M minus 1 will do and it will take all m in into n times right so I think uh if you have any doubt in this question please bring me the comment box I will help you there thank you so much guys
|
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
|
869 |
hello guys welcome to algorithms made easy today we will be discussing the question reordered power of 2 in this question we are given a positive integer n and we need to reorder the digits in any order including the original order such that the leading digit is not zero we need to return true if and only if we can do this in a way such that the resulting number is a power of two in the first example as we can see that number one is a power of two we return true in the second example the number given to us is 10 and any permutation of 10 does not give a number which is a power of 2 and that's why we written false in the third example we see that the number is 16 and the number itself is a power of 2 so we directly return true in the example 4 we have the number 24 it is not a power of 2 and its permutation which is 42 is also not a power of 2 that's why we return false in the last example we have 46 is not a power of 2 but 64 is a power of 2 and that's why we return true in this example the given note with the problem states the constraint that the number n will be in the range of 1 to 10 raised to power 9. so effectively we need to check that if it is at all possible to have a permutation of this given number which is a power of 2 or not so we can always find all the permutations of the given number in check which one is a power of 2 if at all that exists then we return true otherwise we return false but that will be higher time and space complexity in order to reduce that what we need to do is we need to find all the power of two so what we can do here is as we know there are a limited number of power of 2 till 10 raised to power 9 which is less than 30 so we can check these 30 numbers and their digits with the number given and check if the number matches or not so we'll directly jump on to the coding part and we'll discuss how we can do that we need to find what all digits are present in the given number so we'll have an integer array which will hold the count for n will create a method which will take the value n which will give us the count of digits present in this number let's implement this method first so it will return an integer array the name will be count and we are providing it a number will take an array which will be of size 10 as there can be only zero to nine digits and we loop till this n is greater than zero we increment the value for the last digit and then reduce this n by removing the last digit at the end we simply return this array now we have the count of digits present in this number n and now we need to take care of the digits that are present in the power of 2 between 0 to 30. so we'll have a number which we can say as initially 1 and now we loop from 0 to 31. now for each value we need to check if the two arrays are equal or not now the first array will be the count of the digits in the number in and the second will be the count of the power of two that we are checking so that will be num if the two are equal that means it is possible to have a permutation which will give us a number which is a power of 2 so that we can directly return true over here otherwise we increment the num by doubling it every time if even after this loop we are not able to find any value that means the permutation is not possible and we will return false now let's try to run this code so it ran successfully let's submit this so it got submitted successfully the time complexity is locked square in while the space complexity is login thanks for watching the video see you in the next one
|
Reordered Power of 2
|
similar-string-groups
|
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**Example 1:**
**Input:** n = 1
**Output:** true
**Example 2:**
**Input:** n = 10
**Output:** false
**Constraints:**
* `1 <= n <= 109`
| null |
Array,String,Depth-First Search,Breadth-First Search,Union Find
|
Hard
|
2276
|
859 |
Hello hello bigs today in this video will be the big spring problem of the year so give me two strings and video up lower case letters written true if you can set up two letters in a solid gold ruby opposite return letters in a solid gold ruby opposite return letters in a solid gold ruby opposite return forms swapping letter s defined s c taking two in more than directions and not where is not equal victory and shopping also character set a gradual for example white 2012 abcd dismil vikram cbmd suddenly saw her example1 this is pay in this way e MB in the distic mba and which e request oo to string beans so Friends Patent Truth No Inch Example Such Web History Amazon Subodh Singh Equal World Can Any Situation With co-operation World Can Any Situation With co-operation World Can Any Situation With co-operation And Have Not Taken To Be Happy Return Forms In This Case Very String In The Schools But Very Hybrid SIM Character Any Two Times Were Amazing to her and she can come to this will also on students wanting Video then subscribe to The Amazing Same in the easy words tree and in need to be in we will get one to switch on improve and discuss like length or PNB notification do anything straight Forward Falls So How Will Solve This Problem So Let's E-Content Consent As Length Of The Let's E-Content Consent As Length Of The Let's E-Content Consent As Length Of The Springs Maximum To Impotent To The Power For Too And Consoled Ignore The Character Of Hardcore First Forward Cases Like Don't Like This And Not Equal To A Be Don't Like it or not interested in the wealth tax return forms A pass case decision Switzerland considered in the country is possible if e capsules v typical semi-solid straight example over v typical semi-solid straight example over v typical semi-solid straight example over 120 b but they are not able to this world but in this case e v Have to character add this sequence like more than one frequency subscribe The Channel and subscribe the alarm set new is straight line width resistant characters in one of the spring late this dat to an android app the effigy handset already which is more character wear processing Which in this man has been found dead at least two characters in Noida Distributors Same characters in the form and one of them can return hair proof withdrawn after doing for profitable All characters can be divided due to create actors and actresses and subscribe the Channel and subscribe the first all characters in to-do list of intense pain characters in to-do list of intense pain characters in to-do list of intense pain in new delhi on the point is record 208 यौनिक point is record 208 यौनिक point is record 208 यौनिक झला plus झला plus झला plus that in here I will check if water in is not equal to B.Com tractor in the mid not equal to B.Com tractor in the mid not equal to B.Com tractor in the mid term in To-Do List Play List liked The term in To-Do List Play List liked The term in To-Do List Play List liked The Video then subscribe to the Ki An If Hindi Induction Se Zor Se Intact One Should Attract Index Beach List Start 200 To The Character Of Birth Which Character In B.Ed Index 160 Characters Which Character In B.Ed Index 160 Characters Which Character In B.Ed Index 160 Characters In This Book Also Honored With Which Were Sleeping Should Be Alive After Rape In Beating And Schools And Angry Birds Case Like Character In Exams One Should Also Equally True Character Of But Iss Zor Dal Cash Withdrawal ₹3 Dashrath Raw One Feels So Let's Like Cash Withdrawal ₹3 Dashrath Raw One Feels So Let's Like Cash Withdrawal ₹3 Dashrath Raw One Feels So Let's Like Subscribe And check that they are in the distic 118 so let's see her widowed queen not acid channel subscribe software testing one wrong answer for this third subscribe this Video Here's the mystery I don't like flirting but its contents provided in the mid-day that flats compile and satisfy singh all details how share distance for watching submit record hai kuch sudhri ja raha hoon answer for this task abcd bldc subscribe 1234 200 hair checking se well country-foreign hair checking se well country-foreign hair checking se well country-foreign condition list size reduce in to-do list condition list size reduce in to-do list condition list size reduce in to-do list character tab school 1234 Subscribe button and Subscribe Yes 200 g Tasking True Qualities Witch Falls Near This is the Biggest Tons of More Vitamin E This Text Update Far On Tap and Destroy MY Show Suna Time Complexity of Dissolution and You Can See Over Agro Processing Time Complexity And subscribe like share and subscribe my channel thank you
|
Buddy Strings
|
design-circular-deque
|
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._
Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`.
* For example, swapping at indices `0` and `2` in `"abcd "` results in `"cbad "`.
**Example 1:**
**Input:** s = "ab ", goal = "ba "
**Output:** true
**Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'b' to get "ba ", which is equal to goal.
**Example 2:**
**Input:** s = "ab ", goal = "ab "
**Output:** false
**Explanation:** The only letters you can swap are s\[0\] = 'a' and s\[1\] = 'b', which results in "ba " != goal.
**Example 3:**
**Input:** s = "aa ", goal = "aa "
**Output:** true
**Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'a' to get "aa ", which is equal to goal.
**Constraints:**
* `1 <= s.length, goal.length <= 2 * 104`
* `s` and `goal` consist of lowercase letters.
| null |
Array,Linked List,Design,Queue
|
Medium
|
860,1767
|
879 |
hey everybody this is Larry this is day 21st of the April legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm I'm still having some allergy things so have you uh catch me like pausing of it is because um my mouth is very itchy not gonna lie um okay so yes I'm always on this page sometimes if you look on the upper left there's a claim secret reward you click on it you get 10 lead coins and maybe sometimes you have to get you add up to get a um Lego t-shirt or something like this all Lego t-shirt or something like this all Lego t-shirt or something like this all right today's problem is 879 profitable schemes there is a group of n members a list of various crimes they could commit the ice crime generates a profit Supply and requires groups of eye members to participate in it I don't know how they're talking about crime I'm gonna get like tracked by the FBI or something and or also demonetization or something and come on the code why are you trying to get my YouTube in trouble anyway I ever remember to participate in one client that member can participate in another climb which is actually a five minute a good strategy in general because you know you don't want to do two times at the same time that's just like asking for it right so uh but if you do only one crime then maybe they don't trace it but anyway okay we don't have to talk about this part okay anyway that's quite a probable scheme of any subset of these crimes generate at least Min profit and the total number of members participating in that subset of climbs is at most and within the number of schemes that can be chosen since the mod right the first thing we do we sing the mod song because I always forget otherwise especially during a contest I'm talking right now because I didn't actually sing the song as usually goes over like my mind uh if I have to guess and it's gonna be less than 20 or something now a hundred I was actually surprised I don't know it's going to be um I thought it was gonna be a bit Mass DP to be honest but okay let's actually read it uh oh I see I thought that no okay maybe I misunderstood a little bit but basically you have a groups of I okay and the people are fungible I guess right that's what I that's the part that I guess I didn't realize for some reason I thought there'll be like distinct people um uh and yeah Okay so um so I mean that's still going to be okay basically the idea behind each um crime yeah each climb each scheme would be better is um so I'm trying to think a little bit or I'm trying to be make sure that I'm very precise and also maybe I'll just get it wrong and that's fine but yeah basically each scheme you just decide whether you do it or don't do it right so basically that uh just by saying that impose um a structure or an ordering which allows you to just go from left to right is the big part um because most these are only these are independent right each scheme as independent only in the sense that or they're only dependent in the sense that they share n and uh the number of people or the number or M and a sort of a profit right it's okay um so the first I uh the first thing I'm gonna think about is that um you know we have X people left right so maybe people we have index which defines the uh the things that we have to process going again left to right um and then the current profit say okay maybe or profit left maybe right um someone like that and that should be good enough if you're a little bit slick with it and what I mean by that is that um it's very easy to make silly mistakes um because I say this as first as a as someone who has made many of these mistakes before right this is still to end right clearly um so first thing we should do before we fill out this uh function or just is try to figure out whether this is feasible right so here um dynamic programming so total time complexity is going to be roughly speaking time per input times number of inputs right so now we have to calculate the number of inputs people can go from zero to n index would go from zero to I don't know G for group right uh or scheme maybe it doesn't matter I mean they're the same right uh and then profit left well profit left is this is the one that I wanted to um uh kind of put an emphasis on um because naive a naive writing of this could go basically you know each profit object each scheme can have a private 100 it could be 100 of them so then profit could like if you write invite it um from that bottom up just counting up right it could go from zero to a hundred thousand or ten thousand sorry 100 square right um which is n oh no G times uh Max profit right which is ten thousand um and of course if you do the math then this is gonna be 100 a hundred and ten thousand that's going to be 100 to the fourth which is what a billion is it hmm 100 million so still too slow uh right so yeah but yeah the other thing you can do which is what I you know just a mini optimization is going down instead I mean you've got to still go up it doesn't matter but going down means that here foreign by Min profit right so just going down from Min profit to zero will now go down to 100 which allows to have 100 cube in the number of inputs right so number of inputs is equal to 100 Cube now um because now we're going to zero uh from kind of a hundred to zero so then we can kind of do the constraints that way you could do still counting up um by compressing everything over 100 or everything over profit or everything of a Min profit you can just do like you know compress it that would still give you the um the same answer but you know it depends how you want to write it but that is the key thing to note is that you can just like naively add profit you have to like do a little bit slightly a little bit better okay thank you um and then now this is uh this is a million which is going to be a little uh more reasonable to do of course then that means that we need everything else to be all of one right so each input has to take off one time so this is basically how I would think about it and then now we just throw it out um as fast as we can going left to right and just to make sure just people left maybe that's a little bit clearer um yeah and then here maybe we said um what do we say G as you go to the length of groups coupe right and then basically if index is equal to G then we count if profit left we don't have to use everybody right okay I don't think so private left is equal to zero then we return one that means that there's one way to do it otherwise we return zero because that means that we still have profit uh requirements that we have to make right and then now given scheme index we either um you know used I don't know if uses to it like but use the scheme or not right so let's say a number of ways that we can uh we can resolve the issue using the scheme right num so I'm just going to write nums using scheme is equal to okay so count right so this scheme will use people left minus group sub index uh index will be plus one because you move from left to right as we said and then profit left will be also minus uh profit of Index right I mean we're going to do some extra things uh as an if statement but I mean all we could just put it here we're just with people left is less than zero oops we return zero if profit well I mean this part is fine the profit left is great less than zero then profit left we set it to zero just basically a set of four to it so that we don't get into the negatives too much otherwise this should be good um and then nums not using scheme it's just can't people left well we didn't change anything index plus one we didn't change anything and pop it left we also didn't change anything and then so there just these two ways so then now we just have to add these two ways and of course uh as we know there is a mad thing to this so let's just do this to mine um I will implore you if you're using a non-python uh be a little bit careful a non-python uh be a little bit careful a non-python uh be a little bit careful on the uh on the possible overflows I think something that I mean I'm way well aware of but in general not all the time sometimes I'm sloppy but in general I'm way well aware of it but I do forget to mention it even when I'm aware of it but the idea here is that if this number is going to be less than mod and this number is less than mod this can only be two times smart right something like this a little bit less than two times one obviously but like two times might or minus two or something but so that this will at most be too two times minus 2 which is still fits in an INT that's it you know still have to be careful okay and then that will now we just have to kick it off we start with for the number of people zero for index and when profit for how much we have to profit let's give it a quick run see if it's fast enough it looks good for the inputs which maybe it's not speaking that much but of course we have to now remember to memorize uh core part of this sort of dynamic programming a key part of it is that the two things I guess I always mention uh I don't always mention but I should always mention is that uh noting that this is a dag right meaning that there's no cycos in the core stack or the core graph rather right um yeah there's no Cycles in the core graphs so it should be pretty good um let's see yeah and then the other thing is just that well yeah we already did the input things so let's do it uh what do we have I always the ordering is a little bit awkward but uh but still uh what is the second one oh G keep us one say just a week lazy or like I don't want to think about it I usually also convert it to the Pick N but this time I'm a little bit lazy a little bit too late anyway yeah all right so now we set these to match these dimensions and then that all we have to do after that is just add it has cash as you could achieve it shouldn't matter though uh people left index perfect left right hash uh we return this thing oops uh looks good that gave us some red hopefully I don't have a typo or anything weird and there we go apparently I did it last time in C huh oh good old past Larry and I guess I did it about the same way uh wow that was that four years ago now almost three and a half years ago I've been on Deco for that long and that's actually kind of I don't know how I feel about that now to be honest but in any case uh yeah it's more so it fits on one screen uh that's what I have for today let me know what you think and yeah and you what oh yeah stay good stay healthy took a mental health I'll see y'all later and take care bye
|
Profitable Schemes
|
maximize-distance-to-closest-person
|
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`.
Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\]
**Output:** 2
**Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
**Example 2:**
**Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\]
**Output:** 7
**Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
**Constraints:**
* `1 <= n <= 100`
* `0 <= minProfit <= 100`
* `1 <= group.length <= 100`
* `1 <= group[i] <= 100`
* `profit.length == group.length`
* `0 <= profit[i] <= 100`
| null |
Array
|
Medium
|
885
|
257 |
how's it going guys today we're gonna be going over another league good question today our question is from Amazon and it's called binary tree paths alright guys today our question is called binary tree paths again it's a questions being asked by Amazon and a problem description says it's given a binary tree return all root to leaf paths it tells us as a note that a leaf is a node with no children so if we're given this example here a tree that has one two three and five we want to output the strings one arrow to arrow five and one arrow three and the reason for that is because if you look at every single brand for basically taking the current node adding its value to a string if it has a child we're adding an arrow and then we're you know constantly recursively traversing this tree or somehow traversing this tree going to the children of the current node and adding its children's value to the current path so the explanation says all routes elite paths are 1 2 & 5 & then 1 routes elite paths are 1 2 & 5 & then 1 routes elite paths are 1 2 & 5 & then 1 & 3 so how do we actually go about doing & 3 so how do we actually go about doing & 3 so how do we actually go about doing this problem what we're kind of talking about it out loud now so let's think about what we're doing so every single instance we're taking the current nodes value and then we're moving to its children if it has children right so if it has two children we're going to move to the left and the right child if it has one child we're just going to move to that child and if has zero children then we're done right once we actually have the path we need to make sure that we add that string that represents the path to some sort of lists because that's what we need to return so I think a good way to probably do this problem here is we can basically start at the root of the tree add the current nodes value to the path that we're on and then kind of constantly traverse its sub trees and it has children constantly adding the next child's value to the path that we currently have so a good way to do that is just with like a simple BFS or DFS so today we'll do a DFS and so you guys kind of know this but I like to write shell functions that kind of just do simple work at the very beginning and then we call a magical recursive function that will do our work and then we just return whatever we need from the problem so let's start that now so the first thing we need is a list of strings that's going to represent our path so let's make a variable called paths so lists of strings it's gonna be called paths and it's equal to a new ArrayList and now again this is the shell function so we're just gonna do simple error checking so for example if we don't have a root right so if a root is null we have no work to do so we could just return our paths so if our root is null then we could return our paths and otherwise this is where we have some sort of work to do right so if we have some sort of work to do we said that we're gonna call a magical recursive function that's gonna give us our answer and then we're gonna return our answer so let's write that recursive function now so we're gonna say DFS that will be the name of a recursive function or calling a DFS because we're doing a depth-first search on our tree and what depth-first search on our tree and what depth-first search on our tree and what do we need for our DFS well we need our root of our trees so we always have a reference we're gonna need a string right because that's gonna represent the current path that every recursive call and then we're also going to need our paths ArrayList so we can add any path we find fine to that paths ArrayList great and so now once that recursive function returns to the shell function all we should have lis hopefully have to do is return our paths great so now that's it for our shell function and now we just need to write a recursive function so let's do that now so he said public it's called it's not gonna return anything right we're just gonna add the path so we find two our paths variable we called it DFS and we're taking a tree node called route for taking a string that's gonna represent our current path so we're going to call it path and then we're taking a list of strings and this is going to be called paths great so now let's go back through our example and let's think about how we can actually write the code to solve this problem so the first thing we need to do at any given iteration right if we've reached this recursive function we definitively have a node because we had this error checking right so now if we're inside this recursive function we could definitely take the value of the current node which we definitely need right so first we're going to be the root of the tree and we need the trees the roots value all right so we can just simply first and foremost just take that value and add it to our string called path so that's as simple as saying path plus equal roots value great so now this is like the interest cases and we need to start thinking about so you V in a couple different cases right we could be at the beginning of the tree we could be in the middle of the tree somewhere we could be at the end of the tree so let's think about it kind of where we're just at the beginning or the middle of the tree right for at the beginning actually lets thing about our base case first because this is a recursive function the first thing we want to think about is our base case so when do we actually definitively have a path well that's when we reached a leaf node right because it wants all root to leaf paths so if we're at a leaf node we just need to add our path string to our path right we're done we have no more work to do we have no more nodes to traverse so let's check that case so if our roots left child is no and our roots right child is no then that means that we're at a leaf node currently so all we have to do is take our current path and add it to our paths array so we could say past add path and then we could just return from our function because again we have no other children to diverse because we're at a leaf node great okay so now if we're not at a leaf node right if we're at the beginning of the tree or anywhere in the middle of the tree we're not at least node what do we need to do well we need to traverse both the left child and the right child if they exist right so if they do exist let's traverse them and we could just have quick checks to see if they exist right so if root dot left is not equal to no then that means that we need to continue traversing that left subtree so that's as simple as just doing a DFS on that left subtree right so again this is going to be our recursive call so we could say DFS of the roots left child we want our path but we also want to add to our path an arrow right because between every single nodes values we want an arrow so we can add an arrow and then we also need to pass our paths great and so then the same thing right for any given node that we're currently on we need to make sure we also traverse the right sub child if we have a right sub job so we could do the exact same thing so if root that right is not equal to no we want to run a DFS on the current nodes right child we want to add to our path the arrow because that's what our problem wants we also want to pass our paths great so now hopefully when all this code is done and when all these recursive bubble back up to the top recursive call in our shell function here on 17 we will actually populate it all the roots all these paths so now let's quickly talk about our runtime so runtime me of all these recursive calls right we're gonna traverse every single node in our tree so we can say this is o of n for our runtime where n is a total number of nodes in our tree and then in terms of the space complexity we'd also say that this is o of n right here's our recursive stack could go as deep as the height of the tree in the height of our tree could actually be the entire trip so our runtime is going to be all of N and our space complexities also going to be able VIN for this problem so let's run this code and make sure that it works awesome in of those so guys that's how solve binary tree paths in Java again it's a questions being asked by Amazon right now if you guys enjoyed this video and found it helpful do me a favor and leave the video a like and subscribe to the channel for more and I'll see you guys
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
1,046 |
hello everyone welcome to day 7th of april challenge and i hope all of you are having a great time my name is anchor deja i'm working a software developer for at adobe and today i represent 650th video solution of lead code daily challenges the question that we have in today's last stone weight here in this question we are given an array of integers that represents the weight of various stones that we have we are playing a game in which what do we identify the two heaviest stones and in case the weights of these stones happens to be equal then both these stones get destroyed in case they are unequal then one stone gets fully destroyed and the new stone is born with the weight of y minus x the game ends as soon as there is one stone left or zero stones left we need to identify the smallest possible weight of the left stone so here they have provided us with few examples i'll be walking you through this example as well as the algorithm to go about it why the presentation so let's quickly hop on to it lead code1046 last stone weight it's an easy level question on lead code however in case if you have any doubt or want to ask any questions from me please feel free to join the telegram group of coding decoded or the discord server both the links are mentioned in the description below now let's get back to the same example the question itself gives you this is the biggest hint that we need to identify the heaviest stones out of this entire lot because uh in case the their weights are unequal uh the difference that gets created the new stone that gets created will be of minimum value as a result of which we should always look out for identifying the heaviest stones that are present in this entire array and what we are going to do we will use the max heap concept in order to solve this question so i create a max heap and max heap is responsible for giving me the maximum element that is present in among all the elements in that heap so let's get started we create the max heap and we add elements to it so here i create the maxi and i'll as soon as i'll add elements so let's keep these elements in sorted order so we'll have 1 2 4 7 and 8 max sieve internally maintains all the elements in sorted fashion and will always return the largest element when elements are pulled out from it so let's get started what we're going to do we'll pull out two elements from the maxi so eight gets pulled out seven gets pulled out and since eight and seven are unequal in nature what will happen uh a new stone gets created that would be of size eight minus seven so the new stone size turns out to be a one and we will push this stone back into the max heap so one gets added back to the max heap and these two are gone so let's proceed ahead and let's again do the same thing and this time will pull out two elements 4 and 2 gets pulled out since they are unequal in nature 4 is not equal to 2 a new stone gets created the weight of the news one would be equal to y minus x which is 2 again as a result of which will push this 2 value back into the heap so these two are gone and 2 gets added to the heap and it will be added at this particular position because heap internally is responsible for maintaining the sorting order of all the elements so two will be two gets added over here and let's proceed ahead next again let's do the same thing the max two elements get pulled out which is two and one since these are unequal in nature what is going to happen a new stone gets created of size one so these two are gone and a new stone gets created of size one we are gonna add it into the heap so one gets added now heap has three elements all of them are equal to one so let's pull out two elements and both of them will come out to be equal since the weights for both these elements are equal no element would be created no new stone will be created and these two can be simply declared dead so both these stones are gone and in the end what is left there is a single stone left of size one that becomes the answer as soon as the size of your heap goes beyond two you simply return the last standing element in the heap and in case there are no more elements the size becomes zero you simply belong zero in those cases now let's look at the coding section and conclude the approach so here i have defined a priority queue that is actually acting as my max heap and remember to appropriately add the comparator over here a minus b points to b minus a and this b minus is responsible for declaring it as max c i go ahead and add all the elements that are present in my stones array on to this heap p q dot offer stones and i have written a while loop while pq dot size is greater than zero i extract the largest element the second largest element in case both of them are equal in nature i simply continue the process otherwise i go and identify the difference between them and i create a new stone with weight equal to their difference and priority queue is internally responsible maintaining the elements in sorted order the maximum one will be pulled out in the next iteration always by virtue of this max sleep declaration once we are out of the loop if pq dot size turns out to be 0 then we should return 0 otherwise we should return the topmost element that means a single element is left so let's try this up accepted 98 faster which is pretty good the time complexity of this approach is order of end login i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more update from coding decoded i'll see you tomorrow with another fresh question but till then good bye your catalyst your friend your mentor in this journey of yours signing off sanchez take care
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
310 |
hello fellow engineers it's luke here um today i'm going to be doing leak code problem 310 i chose this problem because i was just looking over it for uh looking over exercises that i could give to one of my students and i found this problem and it jumped out to me as one that i have no idea immediately how i would solve usually when i see a problem like an idea occurs to me about how to solve it pretty quickly but this um i don't know about this one so you can sort of see what it's like when i struggle against a problem see what techniques i use to struggle against a problem like this and hopefully i'll um you know actually solve it that would be best right so let's get started first thing we're going to do is read the problem and understand it and grapple with it and make sure we have a really deep understanding of the problem so a tree is an undirected graph in which any two vertices are connected by exactly one path okay so these are all trees yeah given a tree of n nodes labeled simply an array of edges okay indicating that there's an undirected edge between two nodes you can choose any node of the tree as the root okay so like one could be the root and then these three would be children or zero could be the root and it would have one child and that would have two children yeah when you select a node x is the root the result tree has height h among all possible rooted trees those with minimum height are called minimum height trees okay return a list of all minimum height trees root labels you can return the answer in any order okay so um the height of a rooted tree is the number of edges on the longest downward path okay so one uh zero oh i see so this is all the same tree or all the same graph and we consider it a tree in three in four different ways and so then this one is the minimum height tree okay that's easy enough um oh so we're given a tree not a graph uh so we know that it's gonna be a tree no matter how we configure it um and then this example is three zero that's two and two so we're supposed to output both of these nodes and we don't output 0 because that's there's that longest that long path there which is height 3. and let's just review the constraints um 20 000 nodes um ish edges.length edges.length edges.length is n minus 1. there's always n minus 1 edges okay that's interesting it's not immediately obvious why that's true um and all the pairs of edges are distinct and there will be no repeated edges okay i think i understand this problem are there any corner cases or anything that um i'm worried about right now uh i can't really think of anything i think uh the problem statement is pretty clear great so yeah i understand um now i'm gonna go generate some ideas and to generate ideas i like to just sort of play with examples so let's make ourselves some graphs or some trees hello why isn't this okay now it's working um so one idea that comes to mind is what if we have this it's really good to start with simple examples so zero one two um so i mean i guess there's a really simple way to do it which might not be very efficient that occurs to me which is that we just consider each uh root in turn and find the um i guess the longest path from zero to two oh okay i just had an idea of all pairs shorter shortest paths which i know is a standard algorithm i'm pretty sure it's n cubed um i don't really know how it works but that's a possibility depending on so i think we can if we find all pairs shortest paths then i should be able to look up uh we have the shortest paths so we like this would be um one and then this is two so we have all these things then we should be able to uh look that up and then find that all the paths starting from one are below a certain number which is um o of v times e and since e is on of the order v it's o v squared so that algorithm all parashares paths and then um looking at uh and then finding the one with the minimum shortest paths is v cubed plus b squared which is v cubed not great i would like to do better if i can anyway so let's keep looking here so we have some tree like this and if we consider this one as a root zero one two if we consider zero as a root um then we need to sort of walk through the tree and find the minimum distance it's a tree so just the distance just find the depth of the tree so we find the depth of the tree for each root uh which is o of n where n is the number of vertices so v as i said earlier so it's oven to find the depth of the tree and then we consider each vertex uh and for each vertex we find the depth of the tree and we just find a minimum okay that's so that's squared and squared because we look at each vertex and for each vertex we find the height of the tree uh that might be as good as we can do and the algorithm is very simple um i could code that up pretty quickly i think um as long as uh as long as we internalize this list of edges into some more convenient data structure like a um a hash table otherwise we'd have to look we'd have to do a bunch of array traversals so this could come up to n cubed if we didn't internalize that data structure um okay so that's cool i'm i feel like n squared is like maybe we can do better maybe okay so how could we do better suppose we can do better what would be that way um well i was going to say all pair shortest paths because i don't know this is what's occurring to me but that's n cubed so that's no good um we're already we already have n squared which is better than that so we can stop thinking about all pairs shortest paths um what would we do so we're probably not going to be able to do it in o of n um but maybe and so the next one be n log n i don't know sort of seeing starting complexity first i've never really done that so what information could we use to simplify the calculation of the depth of the tree i think we need to like look through each node in turn in some way or another and find the depth of the tree but is there some way some indexing structure or something that we could find the depth of the tree more easily let's make a more sophisticated tree and run an example so we have a tree that looks sure why not it's an upside down tree like this and that's a classic tree shape um let's put another note over here why not okay so the depth of the tree starting from here is one two three four so i'm just gonna say the depth here the depth of tree is one um it's not this way so one two three okay so we already counted this depth and since this one was shorter we don't necessarily need to count this again but finding the structure to memorize that might be hard uh this is two and two yeah and then this is one two three and one and then each of these are four so yeah i sure noticed counting um counting things over and over like to count the depth of this we count the depth of this and for that we count the depth of this um so that's interesting so what if we labeled edges um with their depth i guess they would have to be directed so let's in order to capture this structure the my idea right now is to sort of consider this graph this undirected graph as a directed graph and label each edge each directed edge with the depth of that edge and that would be we could probably do that in o of e time so um let's try that so all right here's this example again and we know it's a tree so it's going to have a shape a tree-like shape like this have a shape a tree-like shape like this have a shape a tree-like shape like this not necessarily binary but and then i'm just going to use arrow i'm going to use how about this let's use colors no uh fine so we just make edges in both directions make sure to have a pretty diagram to work with it's good for the mind okay so um the depth are we gonna say this is depth zero or depth one let's say it's depth of one right because this ends here and then um so i'm imagining the algorithm is going to sort of recurse and it's going to go pink what's the depth i don't know think what the depth oh we got to a root so it's one or a leaf so it's one and so then we go and then that's one and then thing it's the max of these two plus one so that's two and then we go down here and so that's one and then we come back up and that's two um and so now we have that and then we do the same thing it shouldn't matter where we start we should get the same answer so let's do the same thing starting with this is the root why not so we go bing great so we got that so that's wait uh we already had that so ding go down any edges that we don't have already so this thing okay so we already have this downwarded so we know that's two so that we know this is three this is working well i think and then ding come back there and then uh we know this is one already and that's three so we know this edge is four um yeah and so i guess we have to sort of start okay so this is the sort of structure of the memo table i think this is going to work and we can find the depth just because it's the depth of this outgoing edge i guess i should have called this zero for cleanliness i don't know it's sort of i just have to be consistent so yeah so the idea i have is that um these edges are bi-directional these edges are bi-directional these edges are bi-directional and it's sort of a memo structure so they can be null or filled in and then each time we visit a node we recursively calculate the depth but rely on that memo structure so we don't end up recalculating anything and so then um it's only going to be o of e we only need to traverse each edge once and each node once so that's just of n plus some recursion overhead and stuff uh which is also going to be of n that's definitely as good as we can do so yeah i think that's my approach great let's do python because c plus is annoying oh with types i've actually never seen types in python huh cool um so do a class why does it need to be a class there's no classiness here um so what do we need we have this list of edges i'm going to change the list of edges into a hash structure so we say um edge from into and then fill it in so edges equals empty list and for wait um edge memo edge and edges edge memo of edge zero uh so the idea of edge memo is it's gonna be like uh edge memo of zero of one is none if we haven't filled in the depth yet and then it'll be some number and it'll be like two if we have so edge memo of edge of zero uh fill it in wait how does this work set default edge zero um empty of edge one equals nine so we initialize the memo structure x-memo structure x-memo structure x-memo set default edge one nothing at zero equals nine so yeah this is bi-directional so yeah this is bi-directional so yeah this is bi-directional and so we look at the depth going each direction and i'll let's not call this edge mode let's call this depth memo um this also this depth memo also is a more convenient data structure uh for edges so it can sort of uh double as that we said we needed to do that to speed up traversal of edges and this will do that for us so great um let's make a new function find depth of a node should it be of a node um itself is literally doing nothing like if they gave us this in the constructor that'd be more convenient for the class um find depth self and an ant why do we even need that can be inferred from here okay uh enough criticizing the problem find depth and so what we're going to do is look at all the edges the outgoing edges from n and calculate their depths i think this needs to be find edge depth for cleanliness and one and two or let's call it uh source and target why not spell it out um and so if source and oh and we are we're also going to need depth memo um that's my haskell putting parameters like that up front depth no okay um if source is in depth memo and target in depth memo of source then um if depth memo of source target is not none return um depth memo source target so that's the memo and then here if uh let's invert this so that we can follow the like main path is unindented principle so if the source is not in debt memo or the target is not in depth memo source then we shouldn't be considering this race should not consider this edge okay and then we unindent this and then now we know that death memo source target is there if it's not none then that's the death and then if otherwise it is an edge but we don't know the depth yet so we say um what do we do so like we're looking at this edge then we find the node depth yeah so there's going to be two helper functions this is fairly common i think for graph stuff find node depth self node and let's do that later so then we just find depth memo of source target equals find no depth of target and that the node depth of the target is going to be the depth of the edge so i think the no depth here i'm changing this so i'm subtracting one from all these numbers because i just think that's cleaner so this is going to be zero that's going to be zero it's gonna be three i'm writing over so that i know which ones i've changed um yeah so that's that and then return depth memo source um so that finds the edge depth in a certain direction and then finding a node depth is gonna mutually recursively call find edge depth so they'll call each other back and forth um so for find no depth we say um if source not in-depth memo if source not in-depth memo if source not in-depth memo yeah there can be um no there can't be any nodes assert source and depth um every node has got to have at least one edge attached to it and so we know that depth memory will have source depth memo of source four targets in depth memo of source um edge depth equals find edge depth oh i forgot to say self. find edge depth of um wait source let's call this no find edge depth from oh and we're also going to need that memo here node to the target for target uh and pass along that depth memo tree edge depth and then max depth we're finding the maximum depth uh wait so the depth of this node i see a problem this is uncomfortable when i see a problem this leading to the game we're trying to calculate the depth of this node why don't we look here when we do that why like the depth of this note is zero that's why we knew this was one but how do we know that we're not supposed to traverse here go back and add this three and things uh oh um so we're going down two and then oh wait we go so we're recursively doing this go down two go down one and so intuitively the reason is because we've seen this already in the traversal that we did but because we're not traversing from a single point we're traversing like sort of in this weird on-demand way weird on-demand way weird on-demand way are seen um we don't have a good way to say what we've seen i don't think unless yeah let's think harder let's do it again so starting let's say here go down here and i mean can we just mark this i'm gonna mark this as i'm gonna put an x in every scene node so we mark this as scene and then we go down here mark this as seen and then there are no unseen nodes so we know that this has depth zero i'm using the new thing and so great um and then we go here mark that is scene you know this is depth zero think mark that as seen that's depth zero and so then this is depth one and then finally this is depth two and then that makes this step three wait no we didn't do that one we were starting from we're starting from here and so we've traversed that and now let's say we want to find the depth of this node well we know the depth of this edge but we already have these scene markers and so this has been seen already and so its depth is just the maximum of these two depths plus one three that is incorrect it's one it should be one because this is zero we don't we shouldn't come back the way we came i don't like this at all i do not like this is this approach just fundamentally flawed did i like what's the essence here it's like there's a depth when you're going a certain direction um if you're going this direction you have a certain depth and you don't come back the other direction so from here go this direction that direction this direction but how do we know not to consider back edges i'm worried that this is just this isn't going to work at all and i have to do a whole new approach and that seems like i don't have time for that i guess technically we have 20 minutes left i don't want to let go of this yet i thought i had it here go down and then don't come back go down don't come back each time we traverse we shouldn't come back but coming back depends on where we started okay where'd we come from we got this idea by looking at this sort of shared subproblems right that in order to compute the depth of this we have to compute the depth of this and so that we can reuse the depth of this when we're computing the depth of this for example and so how many subtrees are there we have that whole one and that then that's a subtree and then um this is a sub tree what a mess and then right like that it's subtree i think it's probably going to be n squared sub trees just intuition um and really it's the depth of a sub-tree and really it's the depth of a sub-tree and really it's the depth of a sub-tree that we're looking for and so if we consider it that way if we can if we look at the depth of a sub tree instead of like of a directed edge because i think a directed edge doesn't have enough information to know the depth of it because you have to know not to come back or i don't know is it enough just to say don't come back don't reach a verse and edge that you've terrorists have i already explored this so if we're starting here we go down and we say like we've explored this edge already so let's just say don't let's just try don't come back along an edge you've already explored so down here and then we try to go back and we're like oh no we've already explored that maybe there's a there's like a question mark state before we know the answer and we'll hit don't go back and so now we know that this is um zero and then go down here i'm just going to use question marks informally question mark try to go back okay that's def 0. this is a question mark uh this is a question mark try to go back can't go back that's zero i think this is working tips one depth two and then now we want the depth of let's say this and then the depth of this note would be two or three because it's one more then the depth of all of its edges now let's say we want the depth of this node well we've already seen this so we don't need to explore that this we don't know so that's question mark this way is question mark and we've already explored these two so we don't need to do that and this we're this is a question mark edge so um we don't go back that way and then that's everything okay i think this works i hope this works i'm not super sure but i want to try it so what's the idea when we traverse an edge and so that's when we go here when we define node depth we say depth memo of source target equals cute little token unknown or it's not none is unknown it's like um let's say in progress and then when we go through here when we go through all the edges if depth memo of target if the reverse edge of target back to node is um is that how that works this instance unknown that's a terrible uh that's a really terrible way to do that i don't like this way of doing that um let's make it a string something you can only do in python it's usually a number but for now it's a string uh in progress then continue don't consider that one and so um there won't be we'll notice that there won't be any progress nodes in between traversals because anytime we set in progress node uh we immediately will after we do some recursion and then after the recursion we set it to something else so there's not going to be any in progress is left which is a nice little invariant and then find the edge depth and then if edge depth or let's just say h max depth is max edge depth max depth and then we need to add one somewhere um let's say return steps uh maybe this isn't necessary actually um i'm going to call this i think actually what we're going to do is we're just going to pass the parent let's call it source um and then we just don't if target equals source continue so we don't so i'm changing the algorithm on the fly not a great idea but instead of using these question marks i'm just adding some context for the traversal saying where we came from because that's equivalent because these question marks only last for one traversal uh it's equivalent i think it's equivalent just to pass where we came from so we came from source and then if we're going back to the source don't do that find the max death find no depth and then if we want to find the depth of a tree completely like from here it's enough to say we didn't come from anywhere so we should try both yeah i think that works great i this is going to work and then for node in range um n um we need to find all the minimum so let's well it's really trivial once we have the memo table so let's just calculate the min and in depth equals i don't know a big number i want to say infinity how do you say infinity in python float in um for node range n min depth equals min depth find node depth self dot find node depth let's make sure we have cells everywhere we need to of node coming from nowhere and with our depth memo good and then again we're supposed to return it right so min roots um let's do a list this comprehension to show off our stuff return uh node for node in range n if self.find self.find self.find node depth of node none depth memo equals min depth um so we do this twice but um i mean it's i think it could be done better but asymptotically it doesn't hurt us at all because we already have the memo table built so like we already have all these numbers filled out and so we only need to look at the immediate edges it's uh it's not great but and now the part where i need to find out if i've made any bugs i don't nothing is occurring to me let's just try it crossing my fingers no oh good small errors in an interview setting accepted yes no node in-depth memory so we did find no depth on something that's not in the depth memo when there's one node and no edges that's awkward yeah i guess that's technically within the freaking requirements but yeah that's this is the only case where this fails i think this is the only case where this fails so let's just make a special case if n is one return zero okay sorry turn zero okay so it's failing on big inputs or it's being too slow on big inputs but i think this is of n unless i failed at the memoization like this is like the maximum size input and so maybe i think in leap code the like maximum size um input is like did you do it the best way like not only asymptotically best but like did you it's like tuned so if you like really coded it very efficiently and i didn't i like this for example is not great um so let's cache the depths instead so we don't need to call this again let's just see if we can optimize this a little bit depth table of node equals that and then uh min depth equals minimum in depth at depth table node and then here we just replace this table now that's not a huge uh improvement this definitely needs to be two pass let's see i mean i doubt that makes a significant difference i'm worried that we made some logical error like not memoizing so let's just double check our memo table logic yeah because this would work because of this check this would work even if our memo table completely failed if we so no you're not getting this exception that's great if source target is not none then we already know and then we set the memo table so that's a classic memo pattern yeah i think it's working i don't see any opportunities for improvement really i mean i guess there's like some really minor stuff like i'm repeating look ups here i could probably make this more efficient a like tiny bit but it's not gonna matter we're talking like one percent improvement is there anything that we're doing really expensively or like that's what i want to ask is there anything we're doing a lot like over and over again what's the fast path it's all or what's the yeah fast path it's sort of all the fast path like this is just going in this mutual recursion here and i mean maybe the recursion itself is the problem honestly i don't see anything and i'm gonna stop here like that's my solution hire me if you want if you thought that was good enough i thought it did pretty good let's look at the solution and see what lead code says toppo sort interesting approach i don't understand it yet it is clear okay so there's some math that is by no means obvious to me okay they have a proof great so this is for geniuses um interesting totally different than my approach trimming out so we delete everything with only one edge i guess and then that leaves oh wow and it's ov the same time complexity and space complexity is mine but um but better i can just feel it's better uh it's the same complexity but it's more efficient cool well i didn't find the official solution but i did find a solution which was um same complexity and i'm pretty happy with it uh so yeah i hope you found this um informative watching my problem solving strategy uh just to restate my principles which i use for coaching oops uh just notice how much time i spent up front i spent 15 minutes up front exploring the problem without writing a single line of code i was like sketching and like trying sketching algorithms i was working with a an example on paper and doing things in my head and ideating over here and i only started coding when i had a pretty clear idea of the solution um after 15 minutes of exploration uh i like to say 10 minutes is a good rule of thumb for exploration before coding um but this was longer so there you go um and then i there was a problem in the middle uh that i didn't notice the first time and uh fortunately that problem was easy to fix i just had to realize that i needed to pack needed to pass where we were coming from as a parameter but um i should have noticed that in my initial exploration phase because if that problem had been fatal which i thought it was for a minute uh all the code i had written would have to be scrapped and i'd have to start essentially all over again so i should have been even throughout more thorough during exploration phase because like once i understood the problem coding didn't take that long right i probably spent we'll see but i probably spent like 20 minutes total coding right and the rest was thinking so yeah i hope you found this informative um i do interview skills coaching um so i do mock interviews and um study help and like uh if this was sort of bewildering to you and you don't know where i got my ideas or you don't think that you could come up with them yourself um just check me out uh there's a link in the description to my codementor profile um and we can work together these skills are absolutely trainable and it takes practice and also um just having somebody else watch your problem-solving process and give you problem-solving process and give you problem-solving process and give you feedback can be really helpful uh to sort of guide your mind it's all really about where you put your attention and how you're allocating your time and your mental resources so yeah check out the link in the description like and subscribe for the algorithm if you found this was helpful and um i'll be posting a video every weekday for at least the next week and we'll see how it goes from there all right um so like and subscribe and see you next time bye
|
Minimum Height Trees
|
minimum-height-trees
|
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs).
Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**.
The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
**Example 1:**
**Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\]
**Output:** \[1\]
**Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
**Example 2:**
**Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\]
**Output:** \[3,4\]
**Constraints:**
* `1 <= n <= 2 * 104`
* `edges.length == n - 1`
* `0 <= ai, bi < n`
* `ai != bi`
* All the pairs `(ai, bi)` are distinct.
* The given input is **guaranteed** to be a tree and there will be **no repeated** edges.
|
How many MHTs can a graph have at most?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
207,210
|
1,005 |
Hello Friends This Youth Welcome to our Channel Ko Def YouTube Channel Please subscribe and press the Bell Icon Student Union More Videos Without Going Video Start [ Video Start [ Video Start Hello Friends Talking Questions in Today's Video Maximum Favorite Song Chapter Key Negation OK So let's open the question maximum verification. The questions given here are of India size and number. You must modify it exactly as per the time. Click on OK and that means do n't forget to subscribe and subscribe, it will be fine. If you want to open then look comfortably, you will not turn them upside down, neither will you turn the pipe of the ancestors - Our Ghaghra is done, if you subscribe here, then you have taken its sticker from here, you can do this, if you want to subscribe then Why do I do 2345 here I don't do that okay then 5 - 12345 3333 Subscribe okay then 5 - 12345 3333 Subscribe okay then 5 - 12345 3333 Subscribe Here I tell you guys and I what I do that I take the place of five okay for what will you do will do you will do - They are appointing us that if we have not subscribed before then we will have the right to subscribe here, then we will appoint him - - - and this will fill the gap of our village that I am fine, I request. So the first one will remain the same - 250 will go to - 155. Now I have remain the same - 250 will go to - 155. Now I have remain the same - 250 will go to - 155. Now I have started it, now I am thinking that doing small things is over, either the maximum is contained but if you use it, then mark it only. - - - - It happens and this positive life which was given earlier has to be started so that we will start clicking on the minimum elements, at that time it will be done OK if our knife number becomes positive in the sense like here itself. It was doubled, now I show people that our Ghaghra that if you subscribe to our YouTube channel, please do not subscribe this channel, do not forget to complete and subscribe, click on it and Geeta will be saved, operate on it and table. If this is our Ghaghra, if this is our Ghaghra, it is okay, now let's come quickly, so I have to subscribe it and use our channel, click on it and do it under the bridge and subscribe my channel. Don't forget and 12345 okay bad skip appointed people for this type Fakir became the top - was that see what I - was that see what I - was that see what I did here now this is our ghagra - 50 did here now this is our ghagra - 50 did here now this is our ghagra - 50 subscribe and don't forget to subscribe to again dip the atmosphere use we If it has been done twice by flipping then remove the simple one. I have subscribed once before and subscribe to my channel. Thank you Shravan Chahiye, time has passed, it is okay to come back and if we are appointed here for the space tiger and If you guys here subscribe channel subscribe video come [ video come [ video come [ appreciate] that a appreciate] that a
|
Maximize Sum Of Array After K Negations
|
univalued-binary-tree
|
Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it in this way_.
**Example 1:**
**Input:** nums = \[4,2,3\], k = 1
**Output:** 5
**Explanation:** Choose index 1 and nums becomes \[4,-2,3\].
**Example 2:**
**Input:** nums = \[3,-1,0,2\], k = 3
**Output:** 6
**Explanation:** Choose indices (1, 2, 2) and nums becomes \[3,1,0,2\].
**Example 3:**
**Input:** nums = \[2,-3,-1,5,-4\], k = 2
**Output:** 13
**Explanation:** Choose indices (1, 4) and nums becomes \[2,3,-1,5,4\].
**Constraints:**
* `1 <= nums.length <= 104`
* `-100 <= nums[i] <= 100`
* `1 <= k <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
1609
|
40 |
Hello Viewers Welcome Back to Channel Commission Setting Extremely Well City Will Be Solving Key Problem Combination Sham to Front This Seat Per Before Moving Onto Key Problem This YouTube Channel 30 Ukraine Subscribe and Channel All Problems Status Bank Collection of Candidate Numbers Will Also Be Given no target number and your task is to find all unique combinations in that egg candidates Vedic candidates doon samadhi bin target na tera something the journey to take care of between numbers hindi candidates can only be used while making combinations in next office the solution set must Does not contain duplicate combinations so you can see the red ribbon candidates are specific n12 765 says 100 grams possible combinations can give one six gather possible combinations can you want to 500 bad intentions basically everything hindi short and order and obligations and getting all the in all The Missions Being Elected To Graphical Short And Need To Return The So You Can See Mirza Combination 125 Said Life In This To Make This 500ml Greater 125 And Here Pick Divine This To End Speech Which Can Be Also Another One To 511 Multiple Combination Chicken Just Once Slide Problem White Is Example Test Find Difficult Depot's Permission Suvvar Yadav Combination Will Be 2012 Now You Can Not 7.2 Come Onez Combination Are 2012 Now You Can Not 7.2 Come Onez Combination Are 2012 Now You Can Not 7.2 Come Onez Combination Are Not Warid Because Combination Is Ashwini Started Swans i.e. Sonth Is Ashwini Started Swans i.e. Sonth Is Ashwini Started Swans i.e. Sonth Order Will Only Get B Two Combination This Is Roti How To Return Again Vishwavandya Swanand Is Token 512 And Enemy Country Shivanand Stuart Can Form A Given One Two Hundred Thousand Maze Tourister Diwan Combination The Giver 1212 Duplicate Combination Member Problems Basically Second Year Notifications We Solve This Problem In The Brute Force Date Will Be Following Will Be Inspired By Seeing Part One of the Combination Some So Let's Discuss Drut Posts 121 Recent Rush Video Posting of This Explanation You Should Seedhi Combination Samman Video Dhataav Already Met Se Yeh Vinci Ne Bigg Boss This Video Launches Attitude And You Can Come Back FD Na Video You Remember That Were Last Pick Element Once Active Verification Element From Index Also Always Free Dow Chemicals Which Can Feed Email Once Mode And Wherever Dadi Adab's App Not Packing Which Can Move In Next This Index Plus One Such Transactions Like This In Combination Respect Bodies Combination Marine Questions Page Can Not pick element more than once painting also element will loose there descendants of this is not you will free next indicator will make distance index plus one will make you status index plus one and only china thul in order to get all the combination laddu method capability Get From Indexes Date Mukund Express 101 Se Pick And You Cannot Repeat You Cannot Be Fixed Vansh That Laddu Index Plus One Should Be Alloted For Combination Samman Diya Only Change Pathetic One Billon Bhaiya Plus One Mobile Ticketing Almost Day Next Induction Syrup Stuffing If Same Intex That Visible Tell Me Something Since the Person Erring List of Lists Will Not Avoid Duplicate Effects This Set Up List and Pass He Don't See the Question of Despair Can Give Water Can Be Converted Into Now List Play List You Can Return Subscribe Now Middle the Missions Notes Time Complexity While Solving Combinations For Respect Subscribe Into Another Opposition Now Events For Time's sake Log In The World End Also Because It Putting A Distance From Chuke Thek Length Ke Reported In To Set New's Quantity Extra Log In This Way You Can Shake You Follow this matter the time complexity of brute force limit power and indulge in * brute force limit power and indulge in * brute force limit power and indulge in * log and religious of something if set size suji interview will not like that extra locked tractor will have to remove that too modified as per request but different way will see How are you into like this time is the prime concern not make your comment for every topic word sequences neurological staff suji and function 100 azeem starting with 300 research and here target for three to make india mp district 100 woh bewafa aashiq kyun can you start With Due To This Appears When You Start With Different Inductees Agyeya Will Be Yes Thank You Start With This Content In Your Senses Can You Start Bill Yes Thank You Start Baikuntha Start With His First Element Missions 12232 Decided To Give You Can Decide To Solve Exercises 100 index and possibly can differ for different kind the economic direction conduct and similarly it can also affect wheat products and again going by the control shopping for this adhi five possibilities that it can pick as its first element and miss you want in your thinking of. Making Someone Else You More Than First Element More Crop Me And Posting Dad Post Element And Width Post Element Which Ultimately King Kshuva Went Your First Combination A Mixture Duplicate Combination Not Make Sure You Will Understand This Entry Is Designed To Give A Give Me Direction Sub Pick 20 That Salman 15x And Might Get Wave Reduced To Beat VN Data Structure Will Half Element One Na Will Not For This Question Similarly All Started With A Starting Point Is Repeated Combination Index Starting Element So I Can Stop Midst Of This Element To You Are Quite Combination Must Not Know Comments Chanod Sumit Saunf Vote For A Debate You Used For 1020 Start Preparing For Donations For Every Question Is That You Only Get Decontamination In Solid Object Certificate Up-to-Date Looking For Sorted Certificate Up-to-Date Looking For Sorted Certificate Up-to-Date Looking For Sorted Combination Youth mode on pickup anything from the left over so see you will decide pick elements from a right relationship between float in taxes are very and deposit key pick also third intex cloud burst element president elements clerk moon right now will up defaulting let's get started element in Office not because she already extent respect 2002 one thing starting index on festivals a member oil add also pick fennel now is now to receive new updates reviews and subscribe that nutrients test this standing deposit in the recent and this target key to make over again This option of packing whose adopting between sexual development dominance in under looking for distinctive development so if cancer is difficult to decide candidates for the third and fourth electrification interviewer has asked the candidate to have elements of obscurism and wants to first and second elements in the first instance you Will be the next target roadways by one set of berth to na and data structure will have something like this na chan new pic which contacts Owaisi not because they want a good wallo in the water contamination of doing something in restriction in addition to This is the contents of Ujjain in today's * 10th Chaggi Vidhi Same of Ujjain in today's * 10th Chaggi Vidhi Same of Ujjain in today's * 10th Chaggi Vidhi Same Combination Rights Will Want To Birds Play That Sandesh Will Not Take Bigg Boss Big Guide First Saw The Current Affair Pic Sham We Only Not More Than Ones Acted On Which Person's Third Index Ajay Second Element Reach Third Index for Development of Video K Let's Get Selected Students Acting Destroy Value FD Third Index Hundred Percent Difficult Third Index Next Packing Will Begin From Different Index Laptop Gets Reduced By Two Cigarettes Bidi Laptop Is Vansh Data Structure Milna Hai Want To The Means First Element one second elements to assure combination till now will be default index question again no problem once pack is due to containment now again previous report index after this pack enrollment don't want actor will avoid doing sanjay raturi question calls and vinod it left request pod taxi If then sink meanwhile quote 10 Navi Superintendent N Shifted rough combination British bishop of something like this and function is one among the person Next9 extinction Next in the third front will be reduced by one because with upon its status wave in data structure with time will give one and one boat 's new perspective Third in next 's new perspective Third in next 's new perspective Third in next question because yuvvraj first couple of elements difficulty 3D animated live wallpaper decide ok quantity third index rapid diagnostic at once acted as food distance from 2051's sim taken person's deposit index noida shift in next this game same combination member withdrawal contemplated Elements like subscribe and the third element of scientific dont a subscribe avoid multiple se combination stop this is a nadia replication calls on this day will and in no that electric question call reacted post from 051 selection looking for someone in the fourth report element dried newspaper 3DX OK New Pickup Deflated Same Effective Work Pickup This Too Will Not Be Able To Take Off At PM Target Value Is Vansh Find Diwali To You Can Not Wake Up Sid Can Not Pickup This And Similarly You Can Not Wake Up Before This Award PCS Lecturer Value Superintendent Elements These Days Everything Bright Of Between Sexual And Always Go Into Being Read Topic Soapy Dress v9 The Call Request Desktop And Discrimination Nearby Forest One So Is Reception Call Is Over Country Didn't Give It's About It Combination Loot This Love You Riched Tower 2004 So that what we discussed was called you can actually things like jobs help must equations call the means data structure scan in information which gives us a few can save first as a first combination the word using distinct must similarly half the assembly members complete requirement collapsed In A Laptop With Devotion Oil And Gas Index And Will Not Be Able To Take Any Thing You Will Not Be Questioned For Not The Question Cigarette Is Darkness Index Recording Pure Shri Krishna Kaul This Happened At This Reception Call Chest Left To Be Accepted Current Year Deposit in India Waste Target Is Too Which Left And Shoaib Your Data Structure Has To Sleeping For Skill Development Funds For This Also You Can Pick Up Report Index Swift These Dates Difficulty Of View From A Nation Will Become Rookman To So What If Cancer Is Beneficial combination can extend a text five and difficult out a specific doubts so i can see put you will be 0n editor choice good condition rukman to and ultimately is the question call was called for winters that i can see this data structure also contains combination elements Which 2.2 and can even no combination elements Which 2.2 and can even no combination elements Which 2.2 and can even no comments happened so this opposition favorable will also be done in spending t-20 golden lyrics in spending t-20 golden lyrics in spending t-20 golden lyrics in call vitamin E saw a distinctive question's answer day were initial reaction college and Dinesh every question college over the world of what They Combination Switch Give Me So That Depot And This To My And They Must Be Thinking All Like How Is Going To Write The Question Tree Itself Will Remember One Thing All The Problems Have A Cup Of This Defect In Description Combination Same Problem Traffic And Want To Discuss The Method for Solving Brute Force of Difficulties Patent to Solve Problems Reduce 900 Reverse Entry for Any Problems Which Involves Reservation Should See The Sudhish Show I Can See Initially and Starting with Azharuddin Bade Sajjan Hindu Samaj Starting with Tweet as I am Starting with the Desk Jim All Discriminations of Tourism Data Structure and Whiteness in the Last Four Decades Career Sensor Always with a Steady and You Can Stores Its 5 Officials Data Structure Will Be Stored in Advance for the Career Times Did Not Know What You Are Doing Main Pyar 800 Unit Certificate In that in this technique on vulture one 1615 16000 wedding first night from first to last for class third floor from this basically from dec-2012 dec-2012 dec-2012 and when it's possible amazed as possible they will be a couple of this right what is the possibility of factories Where is not possible dr does not possible edit footer notification calls for deposit effective to-do list from zoom and combination deaths to-do list from zoom and combination deaths to-do list from zoom and combination deaths of lakes follow up being run by some is visible pregnancy care of i will be and records after bj yaad i will be one and Bittu So A Revival Beelid Awadhesh Yadav Dheeraj Question Calls Made Speaking Now Zero Phone Shipping Dab-C Right Seven Motor In Phone Shipping Dab-C Right Seven Motor In Phone Shipping Dab-C Right Seven Motor In Next Indisv Basically Lakshmi Taken Upon Request Hoti Next Index For This Is Nothing But I Say Calling Defy Plus One Correct Developed Movie 3 Active Spokesperson Beta Kaun Very Simple Takhi *Reduced By Are Five Simple And Say But Now I Am *Reduced By Are Five Simple And Say But Now I Am *Reduced By Are Five Simple And Say But Now I Am Back Ki Back Please subscribe this Video plz subscribe Video Ko like and Share and subscribe this way One Act 134 And Stop Doing So They Can Adhesion Over It And Mukesh My Remedy Time They Are After Aaye Ikshit Stock Swarga-Baikuntha Suvairi Se Bigg Boss Stock Swarga-Baikuntha Suvairi Se Bigg Boss Stock Swarga-Baikuntha Suvairi Se Bigg Boss Peeth No Deep A Third But You Will Not Be Able To Take Any Thing And If Life Is Known To Check For Fourth Class Third Are Not Able To Pick Any Thing If fourth's did not no tension checking and pride 24 June note checkor sorry can prevent advantage of nations that we can make a that 20 December 20 2008 against the target beans zero so they can simply right left any 's target fix weakness comes The 's target fix weakness comes The 's target fix weakness comes The goodbye let combination shipyard to your friends where they are and observed as martyrs day speech on independence day well body and all the combination school stored in your and gift 10 times increase and recognition for this problem seven death cases along with the recognition transactions and Debris Print 1.5 How They and Debris Print 1.5 How They and Debris Print 1.5 How They Wanted To Win Or Question Call Me A Very Simple Effigy Bunrat In Next End 151 Packet Removed This One Is Equal To Dushman Ne Bigg Boss Enemy Solid Enemy Relationship Top Sexual Lipstick Jis First One Website Wrapped U Suggest Backward To-Do Next To U Suggest Backward To-Do Next To U Suggest Backward To-Do Next To Will Not Be Picked Up Simple Is That You Want To 10 Soft Active K Seven Right And Without Any Code For Relaxing Time Complexity Ajeeb We Put Elements Of Unique Shape All Elements Of Unique 100 Office Unit Number You Sub sequences in number softventures because debit the power and requires very office weather and unique elements in number of different combinations of different clear sequences it must have different predictions on journey to the power and sexy time complexity of and reporting on one question this flying returns no deduction Sting operation suddenly strange minute's this now crotch length of every combination time complexity British to this piece complexity against chief vigilance's managing director that combination of this stranger's * access the that combination of this stranger's * access the that combination of this stranger's * access the space compulsory for this white ignoring chief engineer space use verification system discuss Javat Solution Fati Approach So They Can See But You Will Stop List Of In Tears And Even A Candidate All Document Target To Achieve Swift Videos Tree List Of List In Teachers And Staff Will Be O Ultimate And So Died Just For The Related Entries Baikunth Sorted Nominations Light of the equal requirement that 30 pass dark password target is choice senses and also observe the data structure of which is initially MP Visheshgya that combination safe functional can see your or index of the target and S&Ds index of the target and S&Ds index of the target and S&Ds Chauhan Awadhesh case is very simple body Discuss Get Started Gyanpeeth Kulti 10 Simple And Noida West Indies Or And Animal Return Now Will Win From Index Stood Up And Others And Minus One So Let's Check The Guide In The Next Few Minutes At Midnight Mid Day In The Voice Of Greed And A Person Sandwich Subscribe Dividend For Subscribe My Channel Busy Chal This Is Not Previous 181 Ki Aavva Bhi Mix And Difficult And Specific Post In Next Day They Will Impact Respective Of Leadership Not But They Didn't Get First In Sacrifice After Starting To Decide Weather very one induced into the forest please make sure dated check device grade one index developed 10 pimples element regarding the difficult not political domination snacks element gorakhpur distic and worked for duplicate check and difficult to get amit very much you are the any bank will right Take Off But Should Celebrate And What Benefit Can Pick Up The Depositors Children Qualification Simple Set Par Movie Extended Till 2019 Electronic Media Explanation I Plus One And Just One Vihar Phase Barf Aaye Other Works Data Structure And Friends Yes Mere Bhai Uttam Background The Central Question Dissected Ya To Remove Dirt From A Distance From Kumar Deputy District Governor Center Equation Is Been Quite Yashwant Center Equation Has Been Called Line Number Twenty One Being Cheated And Service To Ring Olive Combination Scan0 Sensor Is Ultimate End Jab Sandwich C Plus Quotes For Irrigation And Discussed Mon Initial Or Govind Is Of Candidates Factor And Went To Get You Need To Achieve Swift Wino It's Too Short To Give Beneficial As Well As Malefic Combination And In Lexicographical Chord Really Awesome Tuesday Candidates Related Questions Everything Comes In Resort And Order After Two Years Pet Desk Introduction Basically Going To Every Few Combination Dan Sadism Some Android App Dahej Chowk West Apna User Tiny Question So Basically Generate All The Combination And You Can Cause Request Representative Shivling Call And Jobs In Next Target Area And Friend At Song 2016 Already Discussed In The Target And Times Protect 369 Deep Study Shipley Update Into Your And Send It Can Break Heart And Written About What Is Mask Slide Inaccuracy Transition For Your True Form In This Earth To Diy And Minus Instant Relief And Actions Which One Can Affect Next Element Of Days Back To Avoid Sitting After Semester Wise And Doing So You Will Be Updating Of Duplicates Is Minimum Samudrik Jyotish Chaudhary Famous Writers Building Speaking Of Elements Like One Chiffon Vansh Acid Element for Someone Did n't Wake Up in Next One Assistant Element in Subjects for That Was Amazed and Explain 100 Can See The Means Liquid 150 Element Support You But You Never Stop This and This Last 10 Test by Check a Graph Came Total 2328 Puberty It Means 16 This Is Equal To Back 509 Packing This Is This Backpacking Third Difficulties Difficult Notification Subscribe District Matak Hai Maine 2014 Next How To Depict District That Bigg Boss Previous To Shri Navagraha You Comedy Support Index This Condition This Time Light Weight Reduce To Is equal and tourists half cup deposit rajasuya mix it and this dish starting index deposit next arvind starting this johnny to pickup elements 100w baking soda first time snack repeat safe pickup district tyuther indexes a effect requested that states were there in vidron graph on agni samadhi Stand Up To Date Your Pan Continue Basically Singh Don't Like This And Poverty Line Number 1091 Basically Say Gift Aadhe Limited Scientific Kunwar In Target You Not To Indicate Anything In The Right Choice Andhaan Shot Free Account Are Playing That In This Element And Picked Up Selected Top And all the recognition and e also request you to i plus one note index fund acting classes element kata gets reduced and jerry data structures and witty time baseline number fluid comeback line number 302 profit for this and every question will be deleted and will make for the All The Combination Generated Everything In This To Hindustan Safed Depend Units And Will Be Or C Plus Code For This Solution Activation And Pointed And Explanation As Well S C Code Required Please Like Share Like This Video And Can You To My Channel Printed Gherdaar Subscribe Button 100MB Left Video With Meaning Of The Video They Will Be Discussing Samadhi Solution For SC St
|
Combination Sum II
|
combination-sum-ii
|
Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30`
| null |
Array,Backtracking
|
Medium
|
39
|
44 |
one will come to above the training the coldest solution if you want the best a software engineer market interview experience in North America feel free to check out us check us out at paltry needle org we're here to help you and also you know I just realized we have this very cool awesome videos on our show pretty nice video anyways so okay so feel free to just remember to check us out or subscribe to our we check blog so I'm trying my best nowadays to at least publish one video plus like one blog about leak code and then later on I'll also publish more like a system architecture tons of type of questions so leave some comments if you have some kind of system architecture related questions that you are not sure of and then you want to kind of like you know we can help you discuss and maybe write some blogs yeah feel free to leave some comments in under the YouTube video or under the blog either way is fine so today we're going to talk about a kind of a like old but interesting problem it's a little bit of hard as well it's not that easy took me quite some time to think this through so here's a problem it's called wild cat a met wild card magic card sounds like a British accent anyway so you can see the number is 44 that means it's a very question so essentially what this question means is you know given like a string s and also a pattern P and then there's a two unique characters right so why it's a question mark which can match one and only one single character and then a start and match any sequence of characters including empty sequences like him they see the star can map to empty string so now given this so give it as a given P so you're gonna basically return whether this with is a true or false like whether they match or not match so here's my thought process right so whenever you look at this question so let's just say look at this like he's sample 5 you have s and then you have P so as long as if you don't see any stars right so you have two pointers and then you keep comparing but now if you see a star you be like Oh okay because it can means zero to as many of the characters so what naturally we can do is two ways right so let's say in this case it's like okay if you mean zero star zeroes so basically out what I would do is I'll start matching this say d b c d c b with the rest of your string so that's one recursion or if that returns true we're good or what we do is this can map any strings were so naive and improve very beautiful solutions i will just start matching from you know c PCB to this sorry not yes and they're also d CB to this so essentially every single substring so let me quickly show you what i mean by that so what i so you know boiler spoiler alert that is basically that would be te time limit exceeded so what I wrote is okay first do some kind of not in dentistry check so now I will call his match helper but this match helper previously I did not added this so it essentially okay so if you already reached the end they have to be exact the same before you say it's a true but then this is an interesting part this is the beautiful part for this brute falls part what I did was you know if you are a star so what we can do is well just to recurse so if you are a star what we do is first will J plus 1 so that pretty much means in this case is that say if we're here so that's like using the existing substring to match the ones without the star so it's like TEF maps DF and if that's the case of this Kim's later as the optimization part is if you are already then last the string or your match to the last part so that means you're already cool so you were written to true but that's not the point is now I have to do a for loop for the rest of the part which is I'm mapping from here like the star can represent literally from like 1 to any characters in this case so I'm do like from EF I match your whole stream and then from F I matched your whole screen if you have sub strains that continue doing so the essentially is a four loop nested with a recursion call the elf part is easy so if there's a character map that I extracted into a separator function which means you know the either the character equal to is to each other or is actually equals to a question mark which match matches to any strain so as long as in the match which is basically I plus 1 and the J plus 1 just like a happy case and then just continue calling this recursion function so what you will quickly realize this is actually it was a time complexity I map here is actually exponential 1 so assuming s is M lenses MP length is n so this is basically because you're looking through m and then for each of the character they have two chances whether they are in or they're not in the string right so that's basically two to the power of n that's exponential so I was basically trying to make it a little bit of simpler one things I can think office and you're not really pruning the recursion but a more like a heuristic so if you like if you have like that because I submitted it will tell me it's erm I can manage why and then the one case is what you can do is if you have like multiple stars like this you have three stars what I wrote a quick function like we moved to play stars so essentially this will trim it like if you have two star or multiple consecutive stars it what is reduced one well still no luck that will still give you exponential time that's just a simple heuristic so that's for that part this won't work and then a natural part is essentially like a dynamic programming so what we can do you know it's kind of like this falls perfectly into dynamic programming because dynamically normally solves two types of problems one is basically only asking oh yes or no true or false without returning the detail step so if you're asking okay can you return the match there what about the match what are the passes then you can basically not answer in this because dynamic Ram is more like a Luke Harper I so like you keep like an either one-dimensional or two-dimensional one-dimensional or two-dimensional one-dimensional or two-dimensional arrays it's just telling you the result and the dynamic programming DP is also very good for extreme values for example what is the max of this minimum of this best value like best route maximal sum those kind of things so I have posted actually several videos if you go back to a puzzle training the YouTube channel you can see you know there is actually a perfect template for dynamic programming so there are a few steps right so while you initialize your array you initialize your values and then you have some kind of formula to populate all these values and then the last step is you code it up so here's the code so it's actually very clean and very simple to understand but you know what I'm gonna do is actually I'll give you one example how this dynamic programming came up right so let's say your screen is as ACB and your P your pattern is a star B you we know by just quickly look at it this should return to because you know this star can basically be met matched to a C and then this should return true how does it work so as you know so if this is the length M so the basic two three and then this n also equal to three so what we normally do is we give an extra room right so it's like because we need to populate the initial values it's like these are the initial values I mean I meant now this dark mmm this and also those are the initial values what I meant right so what you need to do is you want to give yourself like a buffer room to get the initial values and then those the yellow ones are actually the real truth table but because of the formula it always needs to look up a previous value so that's why you want to give this initial values now the second step is how do we populate so if you look at the code so what I did here is some check and then you have your row and column which in this case the M and n and there were what I said literally just meant what I just said before it just meant you know you had a key to a two-dimensional array you had a key to a two-dimensional array you had a key to a two-dimensional array with like row plus 1 and column plus 1 so that your lookup table is very easy so we can always copy some values like they zero-zero it was to chew so oh by zero-zero it was to chew so oh by zero-zero it was to chew so oh by looking at this if you think about it like this is the eye part and that this is the J part so essentially this is the S this is the J this is the P like P is more like column as is more like a ropes okay so this has to equal to true because it now if you map a empty string to map string empty string they match so perfectly true and now what I did is I need to populate the values right so here what I populated is more like the columns because only in J which is like in column J or P patterns we have there's it can be some kind of weird characters like a question mark or Star Trek so what I populated is more like you know like this dimensional so the rule is so if you see a star and then the previous value is also a star like a true that means you can actually map it to true so let's say here you have to map into false because this is because it's not a star so this is a star but prove at previous value is false so you have to be false however if this is a star so this can be a to right because you know a star can usually map to add to anything so this is a true and then this will also becomes true but that's not our example so let's change it back okay so we probably this and then by default in Java is educated or really everything the facility fault value for bullying is false so all of this is false 20 not explicitly initialize that and now let's look up the formula so this is basically the pattern so we it's not very easy to look okay this is much better so if we look at this right so the idea is so now we started populating this so do they match yes so we can actually have two cases one is whether it's a start because that's a hard case the other case is another start so if it is not a star so the formula is more like if you think about it okay if they are not a star so I have to be like because it is just a normal character right so whether it is to normal well now look at character including the press remark because that can match it to anything so this too has to match and that also means like a previously you know if I minus 1 u minus 1 you're basically like I'm on it I minus 1 J minus 1 that value often used to be tree so this has to be true and you and me have to match so basically in this case is a and a so that equals to 2 so the formula is okay if the previous value is a tube-like the diagonal value on the a tube-like the diagonal value on the a tube-like the diagonal value on the top left is 2 and also this 2 character equal to each other or I mean see these are practice a bracket or the equals 2 customer essentially this also means they're equal to each other we will populate at this value to be true and then we will continue so if you are a star that's a complicated part so what we do is essentially any of your neighbor node other than the diagonal part is true your true so if you hear I'm true so here what is the value of here right so because you know this is a false so there's no way you can think about this is like this will map it is because sorry let me see so this should be true because this means a maps a and then this can mean nothing so this can be carried over to chew and then if we map this value is like this a well anyways as long as one is true this will be true from this direction so this they can be matched so it's true so because the other way doesn't make any sense and then this is B so as I said this has to be true and then so that they can be met so this will be false and then we look at this one right so this one so it's like a and C so they are not the same so they just based off material false and then this is as well as your neighbor has a tool you will be true this is false then that's just bad this is the truth so let's see why this can be matched because this is a start this is the AC start can be a see that this is the true so this is a false because B not equal to C similarly this a not equal to B false star okay let's see so this is a false okay bad this is the true so that means it is basically what we carry / - achoo but what is the truth a star / - achoo but what is the truth a star / - achoo but what is the truth a star can mean a Seabee start and me can be C and B in its case so this would be true so this okay that's the B&B so you have so this okay that's the B&B so you have so this okay that's the B&B so you have to be true and then they have to equal to each other so that's a true so basically this is the value that's finally what we want to return which is two so that just means if we code it up it just looks like this and then this will be the value and then the time complexity is a very straightforward is old time and times and so is the space complexity because you allocated somewhere race so what I want to call this actually I need to do cab I mean the values and then this is this guy like I believe lots of you should already know like to char-broil so he already know like to char-broil so he already know like to char-broil so he explained the teepee solution pretty well but he did not start with let you know because this question will interviews unless you saw this you deep he I mean normally what people do what do the recursion put Falls like what I did and then trying to optimize and then later maybe interview would be like if you working or you realized oh you know exponential is bad so how can i optimize so but he just directly jump into that but it's definitely very good and then work watching and this guy went yeah he explained it like this day in Chinese that looks like they're you know playing games juju qualified GBA Yahoo so the King Ahaz oh yeah just worth wait I think it's pretty fun and this guy who's coding garden so he coded up for this solution like this if you haven't noticed this isn't very short even with the recursion part right so he's who idea is you know if you match to a star all you need to do is like you only match the lastest are so is essentially he bypasses all the previous stars only measure the last one that the reason is not that intuitive to be honest but this guy answered a pretty good so but why so far why this one can pass the OJ right because this why like he said is so if you think about recursion his solution is only recursion in the last branch like last a level because you see only with like whenever he see stars the wind wakers onto it this is the last one and then the reason of that is you know only the if the last branch does not match that just means the previous one won't met either so you basically saves a lot of computational time but it's not very intuitive to go on in there he didn't really explain it that well but it's not solved there's another way to solve this cool um that's it just leave me any comments if you have any like thoughts or remember the design questions if you want me to explain some design approaches I'm happy to look at the comments cool until then see you guys next time
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
371 |
welcome to this video now we're going to cover a coding interview question sum of two integers here's the problem statement calculate the sum of two integers a and b but you are not allowed to use the operator plus and minus addition and subtraction how you can solve this problem to solve this type of problems we have to use the concept called bit manipulation okay let's see how we can solve this problem if you're given equals to 2 and b equals to 3 then a plus b equals to 5 so in this case you have to return 5 if you were given equals to minus 2 be equals to 3 then we have to return 1 because minus 1 plus 3 equals to 1 if you are given equals to minus 2 be close to minus 3 then we have to return minus 5 because minus 2 plus minus 3 equals to minus 5. now how you can solve this problem first let's talk about when you have two positive integers suppose that we have equals to 2 if we convert 2 into binary then the number will be like this we have 32-bit for integers we have 32-bit for integers we have 32-bit for integers for better understanding let's assume we're dealing with an environment where we have eight bits for integers and we have vehicles to 3 and if we convert this 3 into binary then this will be like this now if we add these two binary numbers then we will get this binary number let's see how one plus zero is one plus one is zero we have carry one zero plus zero is zero plus carry and that is one and for the left we have all zero so it's evaluated zero all right and this number is equivalent to five we have to return this number and this is the sum of this two integer how we can add these two binary numbers such that we get this binary number without using plus or minus operator to solve this problem we're going to use bitwise xor operator b2 is and operator and b28 left shift operator okay first we'll calculate the xor between a and b then we'll have carry and then we're going to left-shift the carry and then we're left-shift the carry and then we're left-shift the carry and then we're going to do again xor and carry now let's see how you can solve this problem step by step okay now we're going to talk about for two positive integers don't worry we'll also talk about when we have two negative integers one negative integers and one positive integers also we have talked about in this video when you have negative integers and positive integers let's suppose equals to 2 then this number will be represented in binary like this and if we have b equals to 3 then this number will be represented in binary like this here we are assuming that we have an environment where we're dealing with eight bits for integers for better understanding and the process exactly the same as 32-bit integers exactly the same as 32-bit integers exactly the same as 32-bit integers okay we have equals to 2 and b equals to 3 and the binary representations right here for a and for b now what we're going to do is that we're going to calculate the xor between a and b if we calculate xor in between a and b then we will get these binary numbers x operations for zero and one for one and one zero and here only have zero so zero and zero here we clearly see that if we add these two number one and one the result is zero but we have carry one and the carry we have to add to this digit to the left okay for that we're going to calculate the carry for calculating carry we're going to use bitwise and operator then we're going to left shift that to the left to add the carry to the correct position so carry goes to a and b if we calculate b two is and operation for a and b then we'll get this binary number b two is end in between these two binary number zero and one is zero one and one is one and on the left we have zero so it will be evaluated zero now what we have xor and carry right we are going to left shift this carry now if we lift shift this carry then this one goes here and this is the representation now what we see here is that we have one at the correct plate if we add this one to our xor then we'll get our answer for that we're going to do xor operation between xor and carry now let's see what's gonna happen if we calculate xor between x4 and carry then we'll get this binary number now we see that we added one to the correct pledge let's calculate carry now we have to calculate carry for xor and this carry okay if we calculate carry let's see carry goes to xor and carry so in between these two then we get this binary number all right when we see carry calls to zero that means we're done with the operations when we found carticles to zero we'll return whatever we have at xor and that is our answer and we clearly see that this is our answer if we add this to binary number then we will get this binary representation and that's how we can add to positive integers this concept is similar for negative integers too now let's see how computers evaluated negative integers and how computers done between operations for negative integers okay and all that we'll see in this video if we have one positive and one negative integer let's see what's happening we have equals to 22 and b equals to minus 13. if we convert this 22 into binary then we get this binary representation if we convert 13 into binary then we get this binary representation computer doesn't know negative integer for negative integers it stored the two's complement so the two's complement for 13 is this binary representation and this is sign bit right that you know this is a sign bit zero mean positive integer one mean negative integer and we can get the valued heart in from this two's complement by doing two's complement of this two's complement now if we add these two binary numbers then we'll get this binary representation here we see that we have nine bits for understanding we already mentioned you that we're dealing with an environment where we have eight bits for integer in this case this is an overflow and this is our actual value right now the decimal equivalent to this binary is nine okay and the sum of a plus b is nine and this is how computers add negative and positive integers now if we have the sum of positive and negative integers is a negative integer let's see what's happened if we have equals to minus 22 then this represented in computer memory like this okay and this is equivalent to 22 but this is a negative integers computer doesn't know negative integer so we have to calculate the two's complement of this 22 of this binary number if we calculate two's complement then we get this number here we see this is sine bit this means this is a negative integer and the value we can get by doing two's complement of this 2's complement because 2 we have 13 if we convert this number into binary then we get this number now if we do addition in between two's complement and b then we get this number and here we see that we have one means this is a negative integer to get the value for this binary number we have to calculate two's complement so if we calculate the two's complement for this binary number then we get this binary number and this is equivalent to 9. so a plus v equals to -9 a plus v equals to -9 a plus v equals to -9 and this is how computers evaluated sum of a positive and a negative integer what if we have two negative integers let's see what's happening we have equals to minus 22 so this binary number is equivalent to 22. if we calculate the 2's complement of this 22 then we'll get this number and b equals to minus 13 if we calculate 2's complement of this number then we get this binary number okay now if we add this to two's complement then we get this binary number and here we see that we have an overflow because we are dealing with an environment where we have eight bits for an integer so this is an overflow and we have in our number one and this is sign bit right so this number is a negative number and the value we can get from this number by calculating two's complement of this number okay if we calculate two's complement of this number then we get this number and that's equivalent to 35 okay so the sum of a and b is minus 35 we use here 8 bits for better understanding you can go through the step i shown you in this video using 32-bit integers you will see using 32-bit integers you will see using 32-bit integers you will see the concept exactly the same now let's see how we can implement this solution using pseudocode first i'm going to declare a function add the text to integer a and b then we're going to calculate xor between a and b then we're going to calculate the carry by doing and operation in between a and b then we're going to check if we have car equals to 0 then we'll return xor that's what we have seen right here if carrie is not equals to zero then we're going to recursively call this function with xor and by doing a left shift and for better understanding if we have equals to 2 and b equals to 3 and let's suppose that we're dealing with an environment where we have 8 bits for integer now here if we do this xor operations we get this binary number then if we do this operation and operation between a and b we get this binary number we see that carry is not equals to zero so we're going to call this function recursively xor and carry curry by doing left shift so let's calculate the left chipped if we do left shift by 1 then we get this binary number and we have x or equals to this number so now in this case we have to calculate xor in between xor and carry if we calculate then we get this binary number okay then if we calculate carry in between this two number xor and carry then we get this number and in this case we see that carry equals to zero so we'll return xor and this is our xor and that's equivalent to five for better understanding you could draw logic get so you can understood this problem more clearly for worst case scenario we have to call this function at most 32 times because we're dealing with the environment where we have 32 bits for integer so the solution will takes big of 32 time complexity 32 is a constant so this will takes constant time complexity and for space complexity we have function called stack we might have 32 function called stack at most and they were just using two variables xor and carry so the solution also takes big of one space complexity okay and this is my solution to this problem hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
1,980 |
hi so today we are going to solve lead code problem 1980 find unique binary string so problem statement is like they are giving a array of string and each string having length n so the length of each string exactly the number equ equal to the number of string that we are having in the array like here we are having two strings so length of each string is two only and each character of string is either zero or one that mean we have to make only binary string so the problem is we have to find our string binary string of length n that is not present in the array let's understand by the example so suppose they are given uh Nal to 4 so the option uh string will be one option will be 1 0 1 second one may be 0 1 third one may be 1 0 fourth may be uh all zero so they are giving four array of four uh string of binary four binary string and length of each string is exactly equ equal to the number of character that we are having a number of string so here we are having four string and length of each string is equal to one and we have to return a different string of length n that is not present in this set so uh we can solve this one by many of many methods first approach that I will uh teach here is using diagonal theorem so diagonal theorem says that if you are having n sets of number and each set having exactly n number and that containing zero and one only so if you select the all the element of all diagonal element if you concate all the diagonal element and flip their bit then that resulting array is definitely not present in the sets for example here diagonal element will be diagonal this is the uh so here diagonal element is 1 0 and zero and if the if you will flip their wids so the after flipping it will be 0 1 and one so after flipping we are getting 0 011 it is not definitely not will be in not will be present in the all sets because if it is position if uh this string is at position zero then it will be equal to first position of the first point will be equal but it is not if it is present on the second position then second position will be equal but it is also not equal if it is in third position then the third bit will be equal but it is not equal so on so it will give you guarantee that if you'll select the all the diagonal elements and if you will flip their bit then the resulting sets that you are getting it is not present in the original string original set of strings that is the key idea behind the behind this problem so uh their code will be very simple let's code it so uh let's we will store our resulting uh resulting string in answer type of variable in initially it will be empty after that we will iterate through that after that we will iterate through all the strings so for auto s in nums and we will select the all the diagonal bit and we will flip their bit and we will merge them so uh and NS answer plus equal to nums I uh so if nums I equal to zero then we will conate one and if it is equal to 1 then we'll conate else we will add nsal to zero and we will simply return the answer so there are more than two lines so we will put it these things in bracket I hope it will be run let's submit it so it is submitting the another approach that we want to uh explain here is it is clearly mention in the question is the length of the string is not exceeding 16 and all the element of all the Str either zero or one so we can represent all the string as a number we can convert this binary string as a number and we'll put all these number in the string on the set and we will find if there is a number that is not present in that set if that is not present into that set then we'll simply convert that number into binary string and we will return that one so I have quote that solution also so let's go in the my solution uh my submission section I have submitted that one also I will explain the code of the same so simply copy that one and past it here and submit our it's already submitting so no meaning of submitting it again but I'll explain the code so first make a set and convert all the number all the string in a binary number and insert into the set after converting the set we are checking 0 to 16 number because if0 to we are having a set of 16 number so 0 to 16 will be 17 number so there will be definitely one number that is not present into that set so we'll find the first number that from 0 to 17 that is not present into that set we'll convert that number into string and we'll return that string so that could be the another approach thanks
|
Find Unique Binary String
|
faulty-sensor
|
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_.
**Example 1:**
**Input:** nums = \[ "01 ", "10 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "00 " would also be correct.
**Example 2:**
**Input:** nums = \[ "00 ", "01 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "10 " would also be correct.
**Example 3:**
**Input:** nums = \[ "111 ", "011 ", "001 "\]
**Output:** "101 "
**Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 16`
* `nums[i].length == n`
* `nums[i]` is either `'0'` or `'1'`.
* All the strings of `nums` are **unique**.
|
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
|
Array,Two Pointers
|
Easy
| null |
171 |
foreign title and you have to written the corresponding column number so if this is the first column B is the second currency is the all combinations are there so starts from a then till set again after this a gone till is that will go from zda to Z and this list continues for the it just it doesn't stop here thanks so if you see or a it's one next two next 26 comes here 27. 28 and so on so how do you get this number 26 27 28 all the respective numbers so for a if we take reference as a we know a minus a will be 0. so if you add 1 to that I'll continue what again for b instead of a if equal B minus a as the reference that will give you one plus one that will give it to so this will give you one similarly C minus a will be 2 plus 1 will give you three if this was 0 1 2 then just a minus a b minuses B minus S1 till z minus a Z minus a will give 25 plus 1 will give you 26 if this was 0 1 2 3 then this will say plus one is not a but the orthopedical ordering starts from one so a minus a as a reference we have taken is a reference letter is okay after that so let's take aid in this let's start with here it's a string right so we'll start with first graph so for a we know a minus a plus Community open so for a it's one then for B how do you do B minus a plus 1 is 2. we know for a is one B is total so if you do 1 into 26 plus 2 that is similarly if you do a z then you know a is one for Z it's 26. so same thing for your 1 into 26 plus 26 equal to 28 some number so basically what we are doing here the particular character at I that character minus a plus one I will give you a count value so this value what you do we have a result that is initial into zero next what to do result equal to result star 26 each time you push that to get 26 plus value result starts with X so at first you do this will give you one lesser value so resulting 0 star 26 will give you 0 plus 1 so now result equal to 1 this is the result again perform the value for this alphabet so Z will give you 26 SM value now this term result is called so 1 star 26 Plus 26. that is the answer as a result so this is how we calculate the coin so if there is a also same thing works so a will have one zero star 26 plus 1 so that will give one so next one star 26 again what because for this CL else it's for here also it's one so this will drop in six plus one unit number 27 next for this save 27 1 star 27 one sec uh 27 star 26 Plus 1. that will be some months this is how the logic works so you will have variable called it result equal to zero lesser than column title dot length and I plus so each letter V Travis so character will Define a variable for character c equal to column title dot character at ice equal to how C minus e plus one so now having compute the result so result equal to result star 26 plus value so at the end return result so result 0 then each local trial is find the value then enter 26 plus information runs okay if you understood the problem please like the video subscribe thank you
|
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
|
1,870 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge minimum speed to arrive on time so here we have a floating Point number hour that we get in the input um and this represents the amount of time you have to reach the office so you are going from one point to the office so for example here it takes at hour six you arrive at the office um and to do that you must take n trains in sequential order so what that this means here is that you take train one you take train from zero to this place here takes you one hour and then you go here it takes you three hours and then here takes you two hours uh sorry not two hours but three kilometers and then two kilometers so to get here it takes you one kilometer yeah it takes you one kilometer and then here it takes you three here it takes you two okay so this is the distance in kilometers of the of each trim right um and then each train can depart only at any teacher hour so what this means is that if you arrive let's say at 1.5 hour to if you arrive let's say at 1.5 hour to if you arrive let's say at 1.5 hour to the first shrine then you can depart from the second train only at hour two okay because you have to depart at an integer value so that's one other constraint we have here and the goal is to return the minimum positive integer speed which is basically how many kilometers per hour each train can um can take so that all the trains um so that you can travel all the distances here and arrive at the office on time and by own time means before or equal to this hour okay so that's basically it so let's summarize it again so you are going from one point to the office and you have the distances of the trains you need to travel through in kilometers of course and you need to find the minimum speed you need to have to be able to arrive at the office and if it's not possible we want to return minus one so let's take this first example here so the first example we can actually just take speed one because then we'll arrive at the first for the first train one kilometer that would be with one kilometer per hour it will take you one hour to take the second train for the second train three hours so at what speed of one kilometer per hour that's three so now you have four and then plus two now you have um six okay so you'll arrive exactly at six hour mark and so that means this is um can just return speed one because it works now for the second example is more interesting stuff but the second example the best we can do to arrive the minimum speed is actually three because you take the for the first train one kilometer with speed of three it will arrive at 0.3 hours but since you have arrive at 0.3 hours but since you have arrive at 0.3 hours but since you have to take a positive of an integer value for to the path for the second train you have to depart at hour one okay so if you depart on hour one that means here this is one um for the second Trend three kilometers with three kilometer per hour that's one hour so now two hours and then for the last one two divided by three is this and so now it's 2.66 all the way seven hour mark it's 2.66 all the way seven hour mark it's 2.66 all the way seven hour mark which is smaller than 2.7 so we are good which is smaller than 2.7 so we are good which is smaller than 2.7 so we are good okay now notice here for the last train distance we didn't take the full hour this is because for the last train we don't need to depart again so we don't need to get to the full hour we can just we arrive it at this moment and that's enough okay so that's one key Insight here um yeah so if you look at the constraint here the number of trays is 10 to the power five the hour itself is 10 to the power of 9. so this tells you that we definitely can't do any oven squat solution or any thing that goes through n and then goes through hour or goes through distance and so how can we do better the way this question is framed actually is really um gives hints to binary search because we have a large space of speeds that we need to choose the minimum from um and then we have a constraint and this should you should immediately think of binary search with things like this so let's see how we can tackle it um okay so with binary search like usual the what we need to find is a monotonic function that is either first the values are false and then once they become true they stay true or this other variant where once they become false they stay false okay so let's and this would be the function that we will evaluate for our binary search so let's see if we have a function like this and so since what we are looking for is basically the minimum positive speed integer speed which is basically kilometer per hour that we can use to arrive at to arrive basically before or equal to hour this is what we're looking for and so usually this x value should be whatever um whatever value you are looking for so here we are looking for the speed so let's say then f of x let's just have it as the um the minimum okay so basically it's whether we are able to arrive at the speed okay so this basically tell us um is it possible so it's a Boolean value to arrive at office before or equal to hour with X speed okay so X here is X kilometer per hour okay and if we take a look at this then one observation we can make is that if you can arrive at three kilometer per hour speed then if you increase your speed let's say to four kilometer per hour you will are still alive so let's say I'm able to arrive with three kilometer per hour I'm able to arrive at the office at hour before or equal to hour seven then if I increase the speed then it's logical that I will be able to arrive before seven even before the time I arrive it with three kilometers per hour if I take five I should be able to kilometer per hour I should be able to arrive and so once we are able to arrive at a certain speed if we increase the speed we'll be able to arrive either at the same time or even faster okay so that means this is the monotonic function we have because we are not able to arrive let's say at two kilometer per hour and one kilometer per hour so first the values were false and then once they reach 3 and they are true as we increase the speed the value stay true okay so this is the one we are going to use no we can apply by any search with this the only remaining thing to think about is how do we compute this function f of x and what are the bounds for our low and high and then we can use our template binary search now for f of x um well we just want to know if we are able to arrive so we can just go through the distances okay the range of so n let's have n be the length of the distance so one thing to note here like we saw in the second example is for the last train distance so we had let's say one three two for this one if we take let's say speed three kilometers per hour 2 divided by 3 gives you um uh gives you 0.667 we don't need to round this to one 0.667 we don't need to round this to one 0.667 we don't need to round this to one because we don't have another train to go to but let's say for this one at Value 1 divided by 3 is 0.33 at Value 1 divided by 3 is 0.33 at Value 1 divided by 3 is 0.33 something then we have to round this to one because we have to depart from this strain at a full integer okay and so that means for the last distance we don't need to take the ceiling because to around here to up to round up we need to take the ceiling of the into of the value here and so for the last chain we don't need to do it but for the ones before we need to do math dot seal so that means here we can just take everything before the last one and have arrive which tell us when do we arrive at the office and then here we just add the distance divided by the speed which is X to them when do we arrive that's what we did here and then at the end we need to add the time it will take to arrive at for the last trade and here of as I said here we need to take the math cell um in Python but for the last one we don't need to so just of I divided by X and here we can just take this of the last value divided by X without the 7. and then how do we know if we are able to arrive at the office well we just check that the arrive time is smaller or equal to hour if it is then this means we are able to arrive at the office with X speed so this is the function rules for by R binary search now the last thing to think about is what is our low and high value well with this method of binary research for monotonic function like this we just need to find boundaries that maintain okay that maintain that um that are either outside of the bounds or maintained that these um this constraints are valid so the problem here is that we can have a case where it's all false or a case where it's all true okay and so we take low and high outside of the bounds right so that we prevent for a case like this we prevent not finding a solution or for a case like this we prevent not finding a solution because the high needs to be outside of the bounds so what are the values outside of the bounds well we know for a speed of Zero Hour you won't arrive anywhere right so that's outside of the bound so let's just take it so low I'll set it to zero for high let's just take the maximum possible which is 10 to the power of 9 you can also do 10 to the power of nine plus one because the problems constraint tell us that um the highest value for hour is 10 to the power of 9. okay and so if we take this uh low and high we should be able to solve it um okay so that's pretty much it we have this structure we know our f of x is we just write template binary search now in terms of time complexity this is going to be all flag n and N being the search space and the search space is the speed um and so um the speed can be at most hour and so um yeah all the number of trains so um it should each this should be good because both hour is 10 to the power of 9 and N is 10 to the power of 5. okay um yeah and then our f of x function actually is oven and so for our binary search um so let's say this is of H and this is M so it's going to be of n log h uh yeah so that's pretty much it here now let's solve uh this and cut it up um okay so let's code up the solution we just saw in the overview so we need our function f of x and then we need to do the structure for binary search we said that we will take um n and then while um let's actually just take here and plus one well High minus low is bigger than one because we want at the end we want to have so when we have something like this we want at the end we want to exit when low is here and high is here okay so when high is right here and now it's here so the difference is one between the two and so we take mid for binary search and then to avoid overflow let's just divide it with binary um and using binary method and then we check if F of mid is true remember the invariant is that high needs to always be true so we set High to Mid then and then if it's false we want the invariant is full it low needs to always be false and so we set low to mid and our solution should be high but sometimes it's not possible so if it's not possible then a high will not be true so if all of these values were false then high would be false but it won't it can be true all right and so we want to check here if F of high is true then that means that we have a solution so otherwise we don't have a solution so we return minus one and now we can just write our f of x so we said we the arrive time is arrive and then we return if this is before or equal to hour that we need to arrive at the office and then now here we just go through the range so we need to say distance and here we do n minus 1 because for the last distance we need to add it without math CL and so follow the last distance n minus one divide by X we just add it without rounding up but for the once before we want to round up so we do arrive plus distance of I divided by X but we round up with math.zil but we round up with math.zil but we round up with math.zil okay and this should work so if we just run this looks good let's submit and this passes okay um yeah so that's pretty much it for this problem a very um a very straightforward implementation of binary search but you need to really be able to write binary research on functions instead of just on arrays um yeah so that's pretty much it for this problem thanks for watching and see you on the next one bye
|
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 |
528 |
hey what's up guys this is shown here again and so this time I want to talk about this later called problem number five hundred and twenty eight random pick with weight right so basically we're given like an array with in with positive integers each element of the array represents the weight after currently index for example if you were given like arrayed two and eight means that index zero has weight to an index one has weight eight so once you do a pig in index the one which the eight should have like four times higher chance God picked by the index zero with weight - picked by the index zero with weight - picked by the index zero with weight - all right I know you were you need to implement this pick index right so you know you read the normal like the normal random method in Python is we just pick up everyone has like an equal chance right after noon that and so how are we going to implement this is random pick with weight all right I think so the solution here is we're gonna use a pre some let's say we have a one four and eight right for example we have this is a Ravus these three arrays here three numbers here so what we're gonna do is we're gonna do a pre son right one five and thirteen right because the idea here is that the total peak range it's going to be the total sum of all those numbers here and so basically within the range from 1 to 13 which is the total sum of all the numbers we randomly pick like a ninja number right I'd say for example if we pick like us 6 if we pick 6 then we know ok if the if it is 6 it falls in the range of 5 to 2 13 right then we know ok 6 means it's 8 we need to still within a range of from 2nd and a number to the third number that's why we need to return this 8 here our 7 also 8 right and basically if we pick a number if the random number in the is in the range of 6 to 13 right so we see within this range I thought we will always return this index 3 same for this one so raising the range 2 to 5 right see index 1 so yeah in index 1 yes sir this is a likely next to here zero base and then it's the only one left is 1 so which one is index 0 right so as you can see here so that's how we do the range the random pick with the weight we used like the range of the numbers between those two to do the pick so is that being said let's try to implement this thing so first I'm gonna save this wait to stab you and then we're going to have like precepts right prisms integer and the first value is going to be the zero right then we need to initialize this prisms list here so simply to a in range tableau from one three sums high sums and right we append I minus one right class self W I right so that's how we initialize this a prism placed here and then when we start picking here random towards so kind of we're gonna use a random in Python and for the random int right the starting point is 1 and the ending point is the sum of the total sum of the this whateleys which is the last element in our pre psalms prisms list right so now we have a random number here so how can we get the index so we're gonna do a binary search here right since this thing is sorted let's say 1 6 1 5 and 13 26 and 32 right for example this is the prism free sound index so the prism list here and when we have a target values we want to find out the index right so how do we use the binary search we do so we need to find that the index that can be inserted right in this case so we're going to use the by bisect in the Python library and okay so index going to be the bisect so here we're gonna use a bisect left sorry bisect dr bisect left and the first one is ourself three sums and the second one is here it's a random so why we use a by vice select the left right because we want to get index so this left means if we find the same numbers should we return the left index or the right index right let's say for example if we if the random number is 13 itself right so the studying itself so which index are do we need here we still need 0 1 & 2 right because 13 is still need 0 1 & 2 right because 13 is still need 0 1 & 2 right because 13 is still within the range of the second weight right that's why we need to elect so the left will be basically if as if it's the same values it's going to return the index on the left side which is it which is 2 in this case if we do advise bisect select right so in this case it's gonna give us instead of 2 it will give us like a 3 okay so I think that's it so we just return the index in the end right here I mean we can use a linear search here but since it's a erased or date so every time we see a sorted array and you want to find something and I story the array always try to use binary search right so think that's true just do it just work let's see cool yeah works yeah pretty easy you know pretty straightforward the only I the only thing we need to keep in mind is that how can we get the help Co can we get the random number with wait right here we use a prism and then we use the range in that sum right with the binary search find our index so basically this range between these two numbers it's going to be the weight and we're gonna use the random number to represent that Prop a probability here cool I think that's it for this problem thanks so much for watching the videos and I hope you see you guys soon thank you bye
|
Random Pick with Weight
|
swapping-nodes-in-a-linked-list
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Linked List,Two Pointers
|
Medium
|
19,24,25
|
1,926 |
Welcome back, I have given you a channel from there, you enter from there and what do you have to do, exit and exit point, which is the exit point, which are the points and where do you enter from, you are entering from an entrance point, but what do you have to do? What we have to do is to reach the exit point as quickly as possible, okay, and in this number of steps in the world, you have gone straight from here to here and can move for direction, okay, how will you think, look at this question, we have given you this matrix, now what should we do? So what do we do now? Now we can either visualize it like this is our starting point and we are saying, this is going our way, okay and the path is going from you to four and from you to five. The way is going and you are going to six and from 6 to 8 and to 5 then this way is going to the exit so let's do the starting point, this means what you do is you are standing here and you guys first I will go from here. I will become like this, then I will go to 3 by van, then I will go from 3 to 7, what will I do in 1234, it will come here, okay, I will go for free, then I will go to 37, okay, then in this, you are looking at me, what are I doing in this, when I Could have done this travels, now I had visited Seven, I had visited this too, okay I had visited, but when I came back from the van on 4, I took it back to Explorer because what would I do then, I would go back to Source okay What can I do to optimize it that I don't think what I do I think why am I putting BFS in it because what happens is okay so what we do in BF is first we push this app Do n't do it like this, before this we went to this thing, then this is how we are together right now, meaning it can also be understood like this, what have we done, we have stood here, we have There were many people on us, we told everyone that you go on this path, then we told all the people here that if you were on this path, then in this way, the person will reach the exact first and tell them. That I have reached, okay, so now we have sent everyone that now we are going to three and four, so what will the van do in its man, okay and what will you do, you will say, go to four, go to the side and go to six. Okay, so whatever it is, this will also be done in two steps, meaning there is no one, okay, if here this commission was being sent to him on the phone, then we would have pushed it, but this photo is also being sent through this type only, we will call. It is okay and there is that much station Pushkar because how many steps will there be till here, you will have steps, it is okay for everyone, whoever pushes from here to this layer will reach all of them in three steps, so why would four ask for seven, that too If you don't do anything in Radian, then how will we do this thing, how will we send this message that if you push something in Three, then forgive him at the same time, okay, if we reach Two, then what will Five say that I will just exit? But if we reach here then what will we return, free will reach the next step, we will reach first, then what will we do, first we will check There are so many ways from this, if he is not visited, then what to do with those who are not visited and me. Okay, now how many elements are there in me, we have pushed the element free offer, it will work twice because what was the size, only then it will work for you too, so whatever you are, you will not be able to do anything to four because it is widgetized. The route from you which goes to 4, will not do anything to it now, 5 and 6 are being counted by other routes, we are reducing the steps here, what type has this become, as many as will come here, I will ask whatever the next ones are and like. What will we get, the root will be equal to ours, meaning we have reached the end, what will we return, we will fix this, so now let's look at its code, okay, so we will push the first one, plus it, okay, now its first element, we Why will we pop, okay and we will check that here, like we checked, is it not our end, so what to do, okay, so if your entrance point is this, then you have this, then this cannot be the exit point, you can have any other exit point. You will have to find some border, like this, if you are already on the border, then all the border points are there, then you will have to find some other exit point, from there, I cannot make I equal to intensity, I will check whether it is a valid point or not. What is our out of D boundary I plus van means where can we go, we can move in the I + 1 where can we go, we can move in the I + 1 where can we go, we can move in the I + 1 direction, all those children's are gone, we have them, we can take them from our friend, okay and we can take the steps. Okay, because after removing all these elements, we will have to plus the steps. Okay, so how will we check on the border? Okay Already widgetized, then this will push this. This will push this also, this will push this also, so what will happen to us in such a case that there is a cell which comes at most once. There will be a visit and the number of science is how much is the city, how much will the payment be, please subscribe to the channel also.
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
993 |
Hello Welcome To Day Gift Rather Subscribe Appointed Nodal subscribe to subscribe our suggestion fog subscribe Video subscribe to whatever question it's also given the internet to keep track of the series bane stuart finn ur amazing fluoride subscribe Video subscribe The Channel subscribe Now Already SUBSCRIBE TO TU UN-38 TO TRAVERSE JUST FORCE TO SAME UN-38 TO TRAVERSE JUST FORCE TO SAME UN-38 TO TRAVERSE JUST FORCE TO SAME GLUMINNESS SUBSCRIBE AND SUBSCRIBE THE HAI TO DUB WILL START DIRECTION WILL START THURSDAY APPOINTED SUBSCRIBE TO HA NA ONE GETS WEALTH FROM STUPID TO REMOVE VASTU DEFECTS LEFT SIDE IS Left Side of Nominal Idi Subscribe Ki Adi Sagan One Else Can Listen to Mention of the Country Will Repeat the Same Thing Will to You How to Left Relational Prince's Pet to Right Side Effect for Android UC the Best for Is equal to what do subscribe if you liked The Video then subscribe to the Video then and under-22 is domestic tours and what do subscribe Video subscribe button more that today's process of completing Kabir and subscribe my channel subscribe in the International Subscribe New Delhi Transfer In This Field Visit To Check Weather Dependence Of Equal Voting subscribe and subscribe the Channel Please subscribe and subscribe this Video Subscribe Now Subscribe That Behavior 10 Minutes Yatra Constipation Stomach Subscribe That Other For Back But keeping track of 1615 President on track subscribe to and then the side reaction the water parameters which are part of being a function at this talk about this forum redsubscribe to this forum subscribe Video subscribe entertain subscribe to the hear picture and subscribe comment and subscribe the Video then subscribe to the 200 ko band sidharke verses pe subscribe zurare subscribe to a sweet baby mode clear record infection so let's move where cold a part of income tax return the code of basic beer what do you do Do Subscribe My Channel Subscribe To Me Sirf Mez Hai Don't Left For Help In To-Do Subscribe Dot Loot Ki Is My Head Not Left Way Raw Agent David 220 Recommendations Of Creative And Similar Thing Hair Oil Ko And Anoop Sridhar Of Left Or Right Withdrawal subscribe Video updated yesterday morning Experience and wife in tears subscribe and subscribe the Channel Please subscribe this Video subscribe Quality means an unknown quality in customs A bunch of butt welding experience Video subscribe ki main ek sparing is equal hai and midwifery research Motivational is and Dadar test is also my experiment and this bell is internal but amused and avoid channel subscribe And subscribe The Amazing is this is not administrative watching bracket the colleges spread in office why a look at least 10 minutes that west direction passed in this To avoid the key and talk about different method now this is in celebs Tweet - One who is in celebs Tweet - One who is in celebs Tweet - One who is difficult-2 - 2nd difficult-2 - 2nd difficult-2 - 2nd id in Adhir and subscribe must subscribe and subscribe the Vyas pass in race on Thursday this is a text war bollywood actor Has Been Passed Na Dheer Veer Subscribe A Slice Of MP3 That Aapke Sorry That This Foreigner Was A Person Is Better According To Thursday Dr To Subscribe And Subscribe Button
|
Cousins in Binary Tree
|
tallest-billboard
|
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree.
| null |
Array,Dynamic Programming
|
Hard
|
2162
|
449 |
hey guys welcome back to another video and today we're going to be solving the lee code question serialize and deserialize a binary search tree all right so let's just start off with what exactly serialization means so serialization is converting a data structure or an object into a sequence of bits so that it can be stored in a file or memory buffer or it could be used for transmitting data or whatever it is and deserializing is taking that serialized data and converting that exact same data back into whatever data structure or object it was all right so what we're going to do in this question is we want to design an algorithm to serialize and deserialize a binary search tree and there is no restriction on how your serialization or deserialization algorithm should work you need to ensure that a binary search tree can be serialized to a string and the string can be serialized to the original binary uh tree structure sorry okay so one thing we want to note here is we want to go back to the original tree structure so before we move any further i just want to go through what exactly binary search tree uh tree is and i'll go through that real quickly all right so it's a tree based data structure like this one over here and what happens in a binary search tree is let's say we go to a certain node so let's go to this node over here with the value four and everything to the left of that node has to be less than the current node we're on and that makes sense so we're at four and we have one two three which are all less than four and then seven is to the right so everything to the right is greater than whatever the node we're on is so in this case seven is greater than four uh one more example so let's go to two over here so if you go to the left we have one and if you go to the right we have three and one is less than two three is greater than two so that's exactly what a binary search tree is now the thing is how exactly can we deserialize it we want to get back so once we serialize something and then deserialize it we just don't want a binary uh binary search tree but instead we need the exact same binary search tree that we had before so that kind of changes up or complicates the problem a little bit so now let's just go through a different ways of traversing through a tree so we have something called an in order traversal so in this we go to the leftmost node which is one and we get that so in this case we get one then we're gonna go to two then three four and then seven so you go to the left most then right or then the root and then you go to right so over here we go to the left most which is one then we go to its root which is two and then we go to its right value which is three and we go back to the root since we finished this values all of its left nodes so then we go four and then we go seven now the thing that makes the binary search tree special is that when you do an in-order traversal what when you do an in-order traversal what when you do an in-order traversal what is going to happen is that you're going to get the group you're going to get all of the values in ascending order and the reason for that is pretty simple the leftmost node is going to be the smallest value and the rightmost node is going to be the greatest value and everything else just falls in ascending order so that's pretty simple for us and this over here actually makes it really simple to form a binary search tree so what i'm going to do over here is i'm going to create a binary search tree but i'll try to make it balanced so in order to do that it's a very simple concept what we're going to do is we're going to go to our middle node which in this case is 3 and we're going to make that our root so in this case 3 becomes our root and what that's telling us is everything to the left of 3 is going to be to the left node since everything to the left has to be less than the value three and that includes the numbers one and two so one and two are both going to be on the left of it and four and seven are going to be in the right of it and that's how our binary search tree is going to look like but now the problem with this approach is that even though we do make a valid bst it is not going to always be the same as whatever the original is so in order to also get the original we're going to be using a pre-order in a we're going to be using a pre-order in a we're going to be using a pre-order in a traversal so how the pre-order traversal so how the pre-order traversal so how the pre-order traversal works is we go to the root then we go to its left and then we go to the right so in this case we're going to start off at four so we have four first then we're going to go to two and then one and so there's nothing on the left of one so in that case we go back to two and go to its right node which is three so four two one three and over here we covered everything on the left of the number four so now we go to the right of four and do the same steps but there's only one value over here which is seven and we're going to add seven so four two one three seven but how exactly is this actually going to be useful for us so this is pretty useful for us because it gives us important information of what the root exactly is and combined with the inorder traversal that can actually be pretty helpful and you could also use post order to do the same thing and that being said you could use each one of these in their own different ways in order to solve the same question i'm just going to be giving one of the solutions so i'll just kind of cross out post order and we'll just focus on these two over here okay so pre-order its first value is the okay so pre-order its first value is the okay so pre-order its first value is the number four and its first value is always going to be the root note so let's say now we take the value four and we know for a fact that this over here is going to be our root note so that's exactly what we're going to do we're going to have this as our root node over here now what we're going to do is we're going to go to the same number in our in order list so in this case where's the number four so the number four is right over here and using this information we can deduce for a fact that everything to the left of the number four is going to be on its left child so on the left child we're going to have the values one two and three and on the right child we're going to have everything to the right of four which in this case is well only seven and now the question is how do you further place them accordingly and in order to do that pre-order actually makes it a do that pre-order actually makes it a do that pre-order actually makes it a lot easier for us so now let's say we go to the left and the options we have are going to be only one two and three we're going to ignore seven because that's not going to be on the left-hand that's not going to be on the left-hand that's not going to be on the left-hand side we're only going to look at one two and three so now what's going to happen is we're going to check this value here and this add has a value of 2. so that is going to be the root that we have over here so we're going to have 2 as our root and now we do the exact same steps so we're going to go to 2 inside of our inorder traversal so 2 is right over here and actually to be more precise let's go to 2 over here because this is the list that we're actually following okay so now everything to the left of two is going to be on the left so in this case what's to the left then uh the number one is on the left so over here we could have possibly have one and everything to the right of two is going to be on the right so in this case it's three we only have one option for each and just to make it really simple i'm just going to write it down but if you do go more methodically you'd be going through each of these so you would have one over here and three over here okay but that's pretty much it and similarly now you're going to perform the same steps for the right side of it and as you can see there's only one option so it doesn't really matter and that would just be the number seven all right so hopefully that did make sense and again there are several different ways you could solve this question this is just one that i came up with um and yeah so let's see how we can do this in code and hopefully that makes a lot more sense all right so we'll start off with the serialization part of the code so over here in order to serialize it what we're going to do is we're going to store everything inside of a list and then we're going to take the items inside of the list and we're going to put them inside of our string so that way we're going to be outputting a string which is exactly what we're supposed to do and it tells us clearly encode a tree to a string okay so let's start off by actually defining our list which is just going to be called results and it's going to be an empty list so now that we have this we're going to be performing a pre-order traversal performing a pre-order traversal performing a pre-order traversal so let's just make a function for that so let's just call this pre-order so let's just call this pre-order so let's just call this pre-order and the value it's going to be taking or the parameter is going to be the route that we're currently on or the route that we're currently visiting okay so over here we're going to be doing two things so the first thing is we want to add the route so let's just directly do that so res dot append and we're going to be adding root dot val all right so we have this over here and then after that we're going to go to the left and then we're going to go to the right so let's go to the left so we're going to be calling this function recursively so pre-order and when you go to the left so pre-order and when you go to the left so pre-order and when you go to the left you're going to do root dot left alright perfect so let's just copy this and now we want to go over to the right so when you want to go to the right it's the exact same thing but instead you give it root to top right now this is going to keep going until we reach all of our nodes but there's actually a small problem over here so let's say we go to node one and to the left of one we have a value of none so what exactly do we do over there so in order to kind of stop this program at one point what we're going to do is we're going to check if our route has a value so if root only then are we going to do these steps so if the root is equal to none then in that case we're not going to go inside of the if statement and that should be it for our pre-order function our pre-order function our pre-order function all right so let's just get out over here and for the pre-order function here and for the pre-order function here and for the pre-order function we need to call it over here so let's just call it pre-order and in the just call it pre-order and in the just call it pre-order and in the beginning we're just going to be giving our root which we get from over here all right so at the ending of this we get a list of integers now the problem is what we want to return is going to be a string and what we want to do to make it a lot easier for us instead of inputting or giving our result over here an integer value let's give the same thing as a string so let's just give it a string over here so now our list holds strings so the last step is going to be to add that into a single string and to do that in python it's pretty simple so we can just use the join function so let's just directly return it so we're going to be joining it into one string and between each of the values we're going to have a space so that uh so we're going to have one value and a space another value and so on and so forth and let's use the dot join function and we want to join inside everything instead of rest and one more thing is the this step over here is really important because it has to everything inside of our list has to be a string in order to perform the dot join function so that's it for our serialization part pretty simple but now we want to go on to the deserializing part which might be a little bit more complicated all right so now let's move on to the deserializing part of this so real quickly what we're going to get for the input of d serializing is the same as what we output in serialize and in other words all we're doing is we're taking the string and we're going to convert it back to our tree binary search tree data structure so to start off what we're going to do is we're going to take everything inside of our string and we're going to convert that into a list and that just makes it a lot easier to manipulate and that way what's going to happen is that it's going to be easy to go to specific indices or index okay so i'll just be using list comprehension to do this you could also be using the map function to do that so what i'm going to do is let's do x for x n and we want to kind of split each of our values and if you recall each of the values are spaced out by a single space so there's a space between each of our values and we can actually get that pretty simply using data dot split so let's just do that so x for x in data dot split and uh data is coming from right over here okay so now that we have this we get each of our value values now the problem with this is that the x value over here is going to be an a string but we actually want to convert it to an integer so we can actually make comparisons and do a ton of other operations on it so let's just convert that into an integer and now we're going to have our data as a list of integers of each node's value so now what we want to do is we want to build up our binary search tree and to do that well let's make a quick function over here and we'll just call it build and over here we're going to be giving it two parameters and again i'll be going back to the same idea that we did here and we had two different lists so we had one list for inorder and we had one list for pre-order pre-order pre-order and one question that you might be having is how did i get my in order list because we didn't actually make a function in order to get an unordered list but it's pretty simple an in-order list for a binary search an in-order list for a binary search an in-order list for a binary search tree is always going to be a sorted array and using that property all we can do is since we already have our pre-order since we already have our pre-order since we already have our pre-order data over here all we're going to do is we're going to take this and sort it and that's exactly what we're going to be using for our inorder list over here all right so one more thing that you want to notice over here is that each time we call this function the pre-order and pre-order and pre-order and inorder list that we're referring to is going to be different so for example in this case over here for the four which is our root note we're going to be using this in order list and this pre-ordered list and this pre-ordered list and this pre-ordered list and let's just say we go to the left of four and the in order list that we end up using is just going to consist of one two and three so similarly we're going to always be giving it different values for in order and postor of pre-order for in order and postor of pre-order for in order and postor of pre-order sorry and keeping that in mind that's exactly what we're gonna give our helper function so build over here is gonna take two things so i'll just call pre for pre-order and i'll just say in pre for pre-order and i'll just say in pre for pre-order and i'll just say in for in order or in order never mind okay so we have both of those ready all right so inside of this the first thing that we're going to do is let's actually take out a node from here so the node that we're going to have is going to be whatever is at the pre-order and at the whatever is at the pre-order and at the whatever is at the pre-order and at the zeroth index so i don't think i actually showed this over here but each time we're shortening out whatever pre-order we're shortening out whatever pre-order we're shortening out whatever pre-order we're using and whatever is at the zeroth element is what we're going to use as our root so a quick example is when we were at the beginning we chose the zero element since that's the root which is four so that's exactly what we're going to do and over here we're going to create this as an object for the tree node class so let's just call the class the tree node and how do we exactly have this class it's predefined uh for us over here so we don't need to worry about that so this over here we created our node so now what we want to do is we want to create our inorder function or instead we actually kind of want to know and where is that inside of our inorder function now in this case 4 is right over here we could just look at that and find it out but we want to find its exact index and that's what we're going to be using a temporary variable for so i'll just call this variable called temp and we want to find what index this current value of the node is at so in order to do that all we're going to do is we're going to refer to our inorder list and we want to find the current index that where the node's value is on so index node.val the node's value is on so index node.val the node's value is on so index node.val and that is going to tell us at what index we're on so now that we have this we're going to actually make the recursive calls so let's currently say that we created the node of the main route which is the number four now the first thing that we're going to do is we're going to go to everything to the left so over here let's just do node.left and so over here let's just do node.left and so over here let's just do node.left and what exactly is this going to be equal to so over here we're going to be calling the build function again and we want to give it the pre-order traversal that give it the pre-order traversal that give it the pre-order traversal that we're using now the pre-order traversal that we're now the pre-order traversal that we're now the pre-order traversal that we're going to be using is going to be exactly the same so we're going to use pre-order we're going to go to that list pre-order we're going to go to that list pre-order we're going to go to that list and we're going to start off at the first index so why are we starting off at the first index and the reason for that is because the zeroth index value is already created as a node so that is the root node so we're going to start off at the first index and we're going to go up to and including the temporary value that we have so that is going to be temp plus 1 because we want to include it as well so i'm just going to go back over here so 4 over here is at the zero one two third index right so four is at the third index and what that's telling us is our pre-order or the list of values that our pre-order or the list of values that our pre-order or the list of values that we're gonna use over here starts at two since we're gonna start off at the first index and we're going to go up to the third plus one value so zero one two three and we're gonna go up to here so we're gonna get two one and three and that perfectly makes sense since that's the those are the values that are on the left of four all right so we have that over here and that's for our pre-order list that's for our pre-order list that's for our pre-order list and now let's do the same for our inorder list so that's a lot easier and all it's going to be is we're going to start off at zero and we're going to go all the way up to that temporary value that we have so that's pretty simple uh over here everything to the left is obviously going to be everything up to four so one two and three is on the left right so we went over that and using this that we created over here let me just copy this and let's paste it over here we're going to do the same thing but instead we're going to be doing it for our right node so over here let's just do node.right node.right node.right and we're going to be calling the build function but our pre-order is not going function but our pre-order is not going function but our pre-order is not going to be the same so in this case now we're going to start the first value is going to start at 10 plus 1 and we're going to go all the way up to the ending so that's going to be the pre-order list that going to be the pre-order list that going to be the pre-order list that we're using and the inorder list that we're going to be using is going to be different so we're going to start off with one to the right of our temporary value so we're going to temp plus one so we start off from there and we're going to go all the way up to the ending so that's exactly what we're doing and that should be it and at the very ending of this recursive call we're going to call return node and finally after this over here let's just go outside of this function and we want to return uh this value over here that we get so let's do return and we want to call the build function so we're going to call the build function and we're going to what is the pre-order list going to be in the pre-order list going to be in the pre-order list going to be in the beginning so in the beginning it's exactly what this is over here so it's going to be our data and uh which makes sense because over here we did a pre-order traversal so that's did a pre-order traversal so that's did a pre-order traversal so that's going to be the pre-order traversal going to be the pre-order traversal going to be the pre-order traversal list values for the beginning and what are the in-order traversal values going are the in-order traversal values going are the in-order traversal values going to be so the inordinate traversal values like i said earlier we're just going to sort our pre-order traversal so sorted data our pre-order traversal so sorted data our pre-order traversal so sorted data and this is the same as doing it in order traversal and that should be it so let's submit this and let's see what happens okay actually i forgot to mention one small condition over here so as you can see over here it says uh index error list index out of range okay and that makes sense because we actually did not consider for a fact when our pre-order value a fact when our pre-order value a fact when our pre-order value is actually empty so if not pre-order is actually empty so if not pre-order is actually empty so if not pre-order so then in that case we're just going to end up returning none okay and i forgot to do that earlier okay and a quick reason about what that means so when our pre-order value so when our pre-order value so when our pre-order value does not have anything that means we've reached a child or sorry a leave yeah so let's submit this and hopefully it works now all right so it does as you can see our submission is accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Serialize and Deserialize BST
|
serialize-and-deserialize-bst
|
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree.
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
|
Medium
|
297,652,765
|
90 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem subsets 2. we did solve the first one of this and that was actually a long time ago and people have been requesting i solved this one as well so let's do it today the first one is actually very similar to this one the only difference is that in this case the input array that we're given can contain some duplicate values now our job is still the same we want to return all possible subsets we can from this input array nums but since we do have duplicate values it's going to be tricky for us to not have any duplicate subsets in our result the good thing is we can return the solution in any order so that's good but let's take a look at an example we have one two now a subset of one two is basically uh some values from here where the order is preserved for the most part so you know we could just take the value one that's a subset we could take the second value two that's a subset as well we could take the third value by itself which is also two but here you can see we have a duplicate right these are both the same we can't include both of them so you know we don't include the second one and by the way even if we don't choose any of these for example if we just have an empty list that is still a valid subset as you can see in the output over here we could also take the first one and take the first two which would give us one two we could take the first one and then take the second two but that would be the exact same that would be one two as well so we're not going to keep both of them so you're starting to get the idea of you know subsets in general and what the problem here is going to be for us to not include any duplicates in our results when we don't include any duplicates we have six different subsets that we can create and before we actually get into the assertion you might be thinking okay maybe dynamic programming is something we can do and that would be possible but i know immediately by looking at this problem that we can't do dynamic programming and the reason is because we're not really counting subsets or anything like that we're actually creating the subsets so even if we found some kind of shortcut it wouldn't really make this any more efficient because we still have to create all of these subsets and how many possible subsets could we have well to generate a subset for each value we can either choose to include this value or not include that value so for each value we have two choices now how many values do we have in our input let's just call it n so let's say 2 to the power of n is how many subsets we're going to have now how long is each subset going to be well at most it could be of length n so we're going to take the number of subsets multiplied by the length of the subset so this is going to be the overall time complexity to actually generate all of these subsets notice how we can figure this out even though we haven't even solved the problem yet and this kind of hints to you how we are going to solve this problem this is basically a brute force solution right so we're going to be using backtracking okay so let's get into it so let's take a look at an example and let's just start with the first subset solution which is actually pretty trivial for a backtracking problem remember we want to create every single possible subset so for each one of these input values we have a choice are we going to include this one or are we not going to include this one so putting it more simply with a decision tree you know for the first decision we have we're at this one right and we know that because we're going to keep track of an index a pointer whatever you want to call it and it's initially going to start at zero once we make our decision here then we're going to shift it to the right and then make our decision over here and then keep doing that for every single value in the input but so let's start with our first decision which is the one so let's say we do include that one then we are going to have a array of one this is our subset so far if we don't include the one we're going to have an empty list which is still a valid subset but we're not done yet we still have to iterate through the rest of the array so next we're at the second decision which is two values so for here we could either add the two and if we add the two we'd have one two or we could not add the two so we're basically skipping the two which would leave us having a one same over here we could add a two which would be just 2 by itself in an array or we could skip the 2 which would leave this being an empty list still ok so we just finished this value now we're at the second two and we're going to continue this kind of naive approach but now you're gonna see what the problem is so for here suppose we add this to which would leave us having one two if we don't add the two we stay as a one two and over here you're gonna see where the problem is so here we could add a 2 which would give us a 1 2. you see that we have two subsets that are the exact same now even though we're not finished with the array yet uh both of these paths are clearly going to lead to the same subsets because they are the exact same and they the remainder of the array is going to be the same for both of these so we're going to end up with duplicate subsets but the important question is how did this happen and how can we prevent this from happening let's take a look so as we make this decision tree for example when we're over here and we're at the two value we know that all subsets that follow this one like as we go down the decision tree all subsets are going to include at least one value right and the decision we're making is okay we're including this two so if we do include the two then we're saying all subsets that we create using this one are going to include at least one two value so this path is supposed to be the path with all subsets that include at least one two and we don't want duplicates so when we make the decision on the right side where we skip this two value we don't include the two value on this right side so what this right side should represent is all possible subsets that don't include at least a single two basically all subsets that do not include any two values why because this left side over here already includes all subsets that have at least one two value so if we include any two values on the right side we're going to end up with duplicates so what we have to do is not include any two values on this right side how can we do that well basically when we were over here that's what two we were deciding at right when we choose to skip this two we should choose to skip all two so instead of taking our i pointer and just shifting it by one to be over here we should actually shift it by two to be over here because that's how we know we're not going to get any more two values but this input representation might make it look simple but we're actually not guaranteed that the input array is going to be sorted so we have to sort it ourselves which is going to be n log n time but that's not a big deal because we already know that the time complexity of this solution is going to be about n times 2 to the power of n so this is pretty insignificant so now let's re-draw this decision tree keeping what re-draw this decision tree keeping what re-draw this decision tree keeping what i just mentioned in mind and then we will eliminate all the duplicates okay so this can actually stay the same because this is the side where we do include a 2 but this is the side where we're skipping all the two values so our pointer when we're making a decision now is not actually going to be over here our pointer is actually going to be over here at this 3. so are we gonna include a three or not that's our choice so if we do include a three we get one three if we don't include a three we just get one okay and what about this two well we chose one two so now the next decision is going to be are we including the second two or are we not including the second two so we can draw that so if we do include the second two we get a two and if we don't include the second two we just stay as a single two and lastly on the right side over here are we actually going to be choosing from the second two well no because we already skipped the first two and that means we're gonna end up skipping the second two as well so the decision we're making over here is actually going to be are we including the three or are we not including the 3 so that's going to be 3 by itself or just an empty array and so now you can see that this is actually the last value that we were looking at so we're not going to go any further down in this case so just to kind of illustrate that i'm going to put a box around here this is the base case we're not going to go any further same over here this was also the base case because we were choosing from the three value here we included it here we did not include it okay at this point you probably get the idea so i'm going to fast forward so over here we either include the three or we don't include the three which will leave us with a one two three the other one would be just one two and the other decision is just one two over here if we include the 3 we get 1 2 3. if we don't include the 3 we just get a 1 2 and then let's finish these two as well so this would be 2 3 or just a 2 if we don't include the 3 and then this one is going to be 2 3 or just 2 by itself so these are all of our subsets that are going to be added to the result output you can see that it's actually not quite 2 to the power of n in this case would be 2 to the power of 4 which is 16. in this case i think we actually have about 12 of them and the reason is because we're eliminating duplicates right if we included the duplicates it would have been 16 but that's why uh the time complexity still is the same we can still say the time complexity is n times two to the power of n because remember this is the worst case we don't actually know if there are gonna be any duplicates in the input or not if there's not any duplicates this is gonna be the upper bound you know if there are some duplicates the actual time complexity might be a little bit smaller than this but i think that's enough for us with this explanation now let's actually get into writing the code luckily it's pretty straightforward okay so now let's code it up and we're going to declare our result it's initially just going to be an empty array this is what we're going to be adding all our subsets to and remember before we actually get into the backtracking portion we want to make sure that our input array is in sorted order okay so now let's write the backtracking portion we are given uh two main inputs that we're gonna keep track of one is the index that we're at in our nums array and the second is what's the current subset looking like so far uh we're gonna have a single base case and that's when we reach the end of the input array so basically if i is equal to the length of the input array nums that's basically how we know we have gone through the entire array that means we can take this subset that we have built and go ahead and append it to our result but we want to make a copy of this subset because this subset is just going to be an array and we're going to be using this as we do our backtracking so what we want to do is actually create a copy of this subset so that when we have a future backtracking call that we don't end up overwriting this subset because we're taking a reference to this subset and appending it to this array what we want to do is create a copy and we can do that in python like this or you can use like a built-in copy you can use like a built-in copy you can use like a built-in copy function in java or whatever language you want and after that we just want to return because we don't want to continue backtracking when we reach the end of the array okay that's the base case but what is the recursive case well remember we have exactly two decisions to make one is all subsets that include nums of i that include the number that we're at the other case is all subsets that do not include nums of i so we do not choose to include nums of i in our subset let's start with the first decision what we're going to do is we're going to include nums of i right so we're going to take our subset and append to it this number nums of i and then simply enough we're going to go ahead and do our backtracking call by passing in the next index so we're going to pass in i plus 1. and we're going to pass in the subset that we have so far and you know that's going to take care of all subsets that include this number so very easy but before we start generating all subsets that do not include that number we should probably remove from the subset the value that we just added to it we can do that just by saying subset pop that'll pop this value that we just added so now we're going to generate all subsets that don't include numbers of eye but this is the slightly tricky part because remember if there are duplicates the duplicates will be right next to each other because remember we sorted the input array so what we want to say is i plus 1 as long as i plus 1 is inbound so it's less than the length of the input array and you'll see why we're doing this and if nums of i is equal to nums of i plus one so what am i doing here and why am i doing it well remember if we have an input array like one two and we're at this value and we're choosing to skip this two then we should probably skip the second two as well because we don't want duplicates right we should skip the second two and then our index i is gonna be over here right and we're gonna compare this value to this value are they equal yes they are so then we're going to increment our pointer to be over here now then we're going to compare this value with the next value 3. it's not equal so that's when we're going to stop this loop right and what this loop is going to be doing is just going to be incrementing the i pointer like i kind of talked about right now but what if we didn't actually have this 3 value here in that case our i pointer would be incremented to be this position and we'd see that i plus 1 is out of bounds so then our loop would terminate as well okay and after the loop does terminate we still want to run our back tracking because even if we don't add any values even if we skipped the entire array you know this is this case over here is going to be the case that ends up adding the empty array to the result so we definitely don't want to skip calling backtrack onto this regardless of what the while loop ends up doing so let's call our backtracking uh pass in i plus 1 same as we did up above and let's pass in the current subset after we have popped the value from it remember that is actually the entire code as long as i don't have any bugs let's run it to make sure that i don't so first we want to actually call our backtracking function let's pass in 0 as the starting index and just pass in an empty array as the initial subset and then after that we can just return the result so now let's run it to make sure that it works and as you can see on the left yes it does work and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon if you'd like to further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Subsets II
|
subsets-ii
|
Given an integer array `nums` that may contain duplicates, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,2\]
**Output:** \[\[\],\[1\],\[1,2\],\[1,2,2\],\[2\],\[2,2\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
78,2109
|
6 |
hello friends welcome to good Hecker disco tutorial here we are going to solve zig zag conversion code in public the string paper is hiding is written in a zig-zag pattern on a given number of a zig-zag pattern on a given number of a zig-zag pattern on a given number of those like this you may want to display this pattern you know fixed found for better legibility so paper is high this is the exact pattern so see the naked wizard corrector in vertical direction first and then slope and there's a vertical direction our game so read nine by nine so this all to our new zigzag pattern string so new zigzag pattern string is still read mega Fun Zone by each character by each curvature so right is a code that will take a string and make this conversion given our number of results so we need to implement this function namely come work return the string datatype and takes a input of the string like I know the judge says paper is hiding below for any string also integer value of the number of results as an input so like a number of those means the maximum number of those for each vertical columns like this is a street here so if we call this common word paper is hiding Street function should return lism it's new zig-zag pattern string so from this zig-zag pattern string so from this zig-zag pattern string so from this coding problem we can kill this is a coding problem from PayPal so if we look at the early history of Internet we will find that a paper is also nagar and legendary company like a node bullied founders here like in a mosque you know say oh so those are like influential people in internet industry so we can't think of as AC interesting coding problem may be an early age of party people those guys come up with these coding problems and they want to test job candidates intelligence and the coding skill so we are here to take this challenge and try to solve the Coenen table so to solve this exact coding problem so we are going to first find the underlying pattern logic behind this zigzag format so here we have this paper is hiding the exact format string so here I'm going to first draw the index of the origin index of the paper is hiding at the left side of this each character so found 0 1 2 3 4 5 6 7 8 9 10 11 12 13 and then I'm going to draw the new index like a what's an index of each character in the new the exact format string so it's for read upon the job by each character 0 1 2 3 4 5 6 7 8 9 10 11 13 so to find the solution for this zigzag pattern so we need to find the relationship between the old index and the new index so at an F site of each character is a odd original string index of its of this character and at the top is a new index in the new zigzag former string so we need to find a relationship so here I'm going to introduce two concepts so one is called intervals interval and the latter one is called step so interval and step are two concepts will help us to understand the logic behind the zigzag formal string to understand like the what's the relationship between the two characters so what is an interval so see here we see here like there's a vertical columns in the exact format so there are four vertical columns for this example and the record is the distance between two worthy columns is an interval so the value for the interval it's just on the index of the next column - previous column so there is a 4-0 and - previous column so there is a 4-0 and - previous column so there is a 4-0 and 8 - 4 and the top - 8 so we see this for 8 - 4 and the top - 8 so we see this for 8 - 4 and the top - 8 so we see this for this example the interval between two vertical columns is just 4 so if we are doing the experiment and from 1 2 3 4 - doing the experiment and from 1 2 3 4 - doing the experiment and from 1 2 3 4 - and like jaws is the exam patterns - and like jaws is the exam patterns - and like jaws is the exam patterns - some - some experience for many times we some - some experience for many times we some - some experience for many times we were going to find that and we are going to find that from the observation that there's a relationship between this interval value and the lumber of those that's number observed for this example again is a 3 so the relationship is a 2 and minus 2 so for this example number of those 3 so 2 multiplied by 3 minus 2 that's a full it's you go through the interval value so if you increase that number of those we work at them they are corresponding interval value so next the step is a concept we are going to refer to the distance between the vertical column and some middle characters for some lows like here for this index 1 so that are the P s and I hear this is a middle correctors between two vertical columns so we call this a distance between vertical column and the middle character because this as a step so step the value is a also the index difference like 3 minus 1 that's 2 7 minus 5 as true that's a you know 1 minus 9 that's also true so step has some relationship with the interval so interval minus 2 I so I is an index of zone so interval minus 2 I will get a step like for this index ones Oh so we know this example that the interval is 4 minus 2 multiplied 1 that's 2 so if step will be true and the step is an ingrained between 0 and interval so if the step value is equal to 0 or interval the basic means that there's no middle characters between two vertical columns so we don't need to display that middle characters so here we know that this is a valid range so if within this range and the way are going to display this middle characters and the way also notice that if we are at the end of the world whatever comes last where the call comes if way we will not have the middle characters so that's also our age case so with this 2 concept interval and step we already understand them logic behind the zig-zag pattern we know the zig-zag pattern we know the zig-zag pattern we know the relationship again with a number of those so we can generalize our algorithm so for our algorithms because we are still to display this string by those by correctors so we are going to for each loan so we are going to try to with it each vertical column so we are going to for each column and if it is a vertical column between each vertical column if there's an item middle characters we are going to display this me middle characters otherwise just display that two way that are each column characters so that's a this logic so here we know this like idea how to solve this so we are going to go back to the coding so I'm going to demonstrate in Java to solve this code in public so first introduce our variable coordinance so this is just to store load nice value of the original string because we are going to use this original string dense value many times in this coding so I use a integer value to store this integer variable to store this value and first we are going to have our age HP's checks so what is the educates check for this coding public so if a number of those is greater than this names or if the number of lows is less or equal to one so what this means so even that means like oh if we have a number of sources is a three but we only have a let's input the string that's just two characters or even number of those just one so that basically means that we don't need to do any conversion so we can still return this original string so that's each case and then we are going to initialize a corrector over array of characters that's a zigzag sharp new job this is a chart Ari we still have a sameness of the original string so this chart we are going to store the new zig-zag pattern string characters new zig-zag pattern string characters new zig-zag pattern string characters and we are going to install this you know Chari first because it's dynamic so we can install that first and then we can then cover this to a string for this final output and the one we are going to have a count variable so count means how many characters were already being put into this the exact char array and then as we just mentioned we are going to introduce is a interval variables so the interval variable has a relationship with lumps of lows so that's a true multiplying number of those minus 2 and as though we are going to do our for loop so we are going to with it try to display each character news exact string I and for each load as plus and for each load we are going to calculate a step first because step has a relationship with as oh and also the interval and then we are trying to weight it each column each vertical column correctors so start from I and J is nests and the J step so this increment is by step so we are going to find it whether the each column to H con this is as interval but it's an interval so we are going to increase by interval try to wait it in each we call column characters so here like the first one so for if you look at here that the first character of a each though is just like an original sequence of an Iranian Street like the first row of the first character is a first character of the origin string and seconds of the first character is a second character of the origin string the third row first character is a certain character of the origin string so first here we can do zigzag chars that count is equal to this is star chart at J and we increase this cut and then we can have this if check if there's a mid corrector in this zone we are going to display this mini character so as we just imagine so the step should be in range to step to the greater than zero and less and interval and if there's a nicer last character we should also consider should not be out of range so if a J plus step shooter next and learn less and Zeke there count to the eCos to star chart add J plus step so that's all from each vertical column we are going to wait it a next middle character so in quiz that if we find a one middle character and that's it and we are going to return the call this industry cover this zigzag correct respect to output on final string so we first do the H case if a number of lows quitted an immense number of those is an S or equals to one we just return the original string and the weight build the array of our characters called zigzag charts to stall them each character of a new zigzag stream and we calculate an interval value based on the number of those and we are going to iterate each low each load for each though we are going to calculate the step is I use this formula and for the each low we are going to try to despite each vertical column characters so first one is always a star found on J so here increase that if we put one and if our step is in range and we are going to display on middle character in we are going to this way and store this a middle character into this the exact characters and then finally cover these are the exact charts back to the string okay next click Submit okay cool accept it so we get a right solution for this coding problem so as you see we going to find the underlying logic underlying patterns behind this the exact format and we build this solution so as also this interval and the step concept uses variable names because I find like a English music the interval you see here this is a interval and the GNA this is interval and the step is a little between this two keys so that the interval is a bigger concept of this step so sometimes that girl in real time realized industry the coding naming is very important and now we have a like a meaningful names for these concepts okay that's all about this coding problem so I hope you enjoying watching this is a good hacker so thank you for your watching and thank you for subscription to this YouTube channel so let's make keep making progress together so see you next time
|
Zigzag Conversion
|
zigzag-conversion
|
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000`
| null |
String
|
Medium
| null |
474 |
welcome to april's lego challenge today's problem is ones and zeros you are given an array of binary strings and two integers m and n return the size of the largest subset of strings such that there are most m zeros and n ones inside the subset a set x is a subset of a set y if all elements of x are also elements of y so i don't know why they worded it like that but we have a bunch of strings with ones and zeros we have a limit to how many ones and zeros we can have and we want to return the one with the largest number of subsets so here we can see that we can include all four of these maximizing our constraint with five zeros and three ones and we'll have a length of four so we want to return that four so um initially when i saw this problem i thought perhaps there's going to be a greedy approach to it if we sorted it by the length of these strings and then try to just go through it and maximize our number of ones and zeros but the reason that's not going to work is say that we had for example like one those are ones one and i said oh you can have three ones and three or i don't know four zeros or something like that actually you want six zeros well if we did something like this what would happen is since it's sorted by length it would first take this one then we'll take this zero one but then we can't take any more because we've already completed our three ones but that's not going to be the answer right because the maximum here is going to be all three of these not just these two so greedy approach isn't going to work and once i realized that you realize pretty quickly there's really only a recursive approach to go you have to do something recursive so we can do that we can brute force it and check every single combination of strings or subsets and see which one you know completes our constraint and is the longest but to do that would be very inefficient um if there's a recursive solution use usually there's a dynamic programming solution as well um so we do have constraints let's see we know that the m represents number of zeros and n equals the maximum number of ones right so uh what we can do then is have like a dp array here that's going to contain say that we had a maximum of two ones and i don't know one zero or something like that we can have this be represent representative of how many zeros we can have on the row level on how many ones we can have on the column level uh we need one extra row to account for zero these will always be baseline zero because if we have a constraint of zero ones that means we there's no nothing that we can use to put into that subset uh so what we can do is kind of dynamically go back say that we start with um two ones and one like say that we're given this number here we can check at the maximum uh move backwards and say all right well we know that one and one or uh we can do one and one zero here so if we had a constraint of two ones and one zero let's move back one here and see if we can add to whatever is uh before there so here we see that's one then we can move back here to say this is going to represent 1 and 1 0. again we move back to say all right well before if we had completely did that what could we do and get the max between this and this here plus one so here you can see that's one as well uh and for this example that would be it but um just think of it as like we are maximizing our constraint and then moving backwards all the way to the point that we can't fit this substring inside anymore and by moving backwards and adding to what we had before we could find kind of build up the number of strings using this dynamic programming array so let's start by creating a dp array and that's just going to be a nested for loop so 4 i in range of this is going to be number of ones right and this would be j and range number of zeros that we can use plus one remember and this would just be zero over here so now that we have our dp array what we'll do is do a nested for loop for every string inside of our strings and basically move through all the m times ends that we could use here so let's see four call this i in range of uh n minus n but we're going to move backwards right so it's going to be n that we calculate and the first thing i suppose we need to do is count up the number of ones and zeros inside of a string so ones is going to be s time count of ones all zeros is going to be s count of zeros so for i in range of n moving back uh to all the number of ones n equals ones so we've already calculated this kind of makes sure that we're not going to go out of bounds here uh and i'm actually going to actually minus 1 here for indexing j in range of m 0s s1 minus 1. so now let's update our dp array so this is going to be dp of ij is equal to the max of dpij or let's see it's going to be dp i minus ones j minus zeros plus one so this is going to build up this dp array and at the very end we just need to return our dp of c1s zeros ones so let's make sure let's see if this works that okay i think i flipped this all right so that does look like it works um here let me just print out the dpr8 to show you what it kind of looks like and you can see essentially the last cell here represents the maximum m and n that we can use and all these previous ones represent like smaller constraints so we've been building up the number of strings that we can add and by moving backwards we can make sure that we're not going to recount certain numbers when we update our dp you can certainly move upwards if you'd like but if you want to do that you would have to have like a temporary dp array in the middle here so moving backwards is a little more efficient let's see if this works and submit it and there we go accepted so time complexity wise it's going to be m times n times s i suppose we do use m times on space and yeah that's it this is probably the most optimal so one thing here i do want to i think some of you are under the misconception that i saw these blind and i come up with this like in this same progression definitely not like once i realized this was a recursive solution i essentially had to look for help and saw a solution that looked like this and thought this one was the best one i'm just you know trying to understand the solution and relaying that back to you guys uh that is totally different from solving this blind like i've attempted to solve some of these blind and make videos but i've found them unwatchable so if one day i get to that point i will release more blind solved videos and perhaps then i'll even monetize them trying to focus more on the quality of these videos so but until then i'm just going to brute force it grind my way through just like you guys are doing as well so thanks for watching my channel remember do not trust me i know nothing
|
Ones and Zeroes
|
ones-and-zeroes
|
You are given an array of binary strings `strs` and two integers `m` and `n`.
Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_.
A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`.
**Example 1:**
**Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3
**Output:** 4
**Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4.
Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}.
{ "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
**Example 2:**
**Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1
**Output:** 2
**Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2.
**Constraints:**
* `1 <= strs.length <= 600`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists only of digits `'0'` and `'1'`.
* `1 <= m, n <= 100`
| null |
Array,String,Dynamic Programming
|
Medium
|
510,600,2261
|
11 |
Hi Everyone Welcome Back To A New Video Today We Are Going To See A New Question From Top Interview 150 And The Question Is A Two Pointer Base Question Which Is Container With Most Water This Is A Medium Level Question Now Let's Move On To The Problem Description So let's see the problem description now in this problem we have been given array of height of length and this n word means this n number of heights that we have been given these are like the points okay and we can say these are the pillars and each Each and every index denotes a point on the n We have here so the at will be represented off of the one first axis so in this way each index is acting like a we can say point on the x axis and the height is denoted on the va axis okay so now we have two Return the maximum area between the two pillars OK now what the like maximum area of pillars here denotes is the amount area of pillars here denotes is the amount area of pillars here denotes is the amount of water that can be contained between two pillars now we need to return the maximum amount of water that can be contained OK also we need To like keep in like we need to keep in mind that this ca n't be a slat container okay so if you will think that this is the height of eight and this is sense so why can't we just take 8 * 7 and we can take 8 * 7 and we can take 8 * 7 and we can return 8 * 7 Which is 56 and it will become like the return 8 * 7 Which is 56 and it will become like the return 8 * 7 Which is 56 and it will become like the maximum area so that is not possible ok there for we need to keep in mind the container will always be a straight one ok the level should be maintained so that the water is not overflow ok now How to solve this question Right first let's see like how do we work in this now this is the height ok t we have a maximum height here we have seven here also we have an at here right so we might think that why don't we take this To the height is maximum here but since we are considering the area OK the distance between these two is 1 2 3 4 5 OK so if we do let's say 0 1 2 3 4 5 6 so we are getting five here and f - 1 will Give us 4 right so 4 * f - 1 will Give us 4 right so 4 * f - 1 will Give us 4 right so 4 * 8 will give us 32 The area that we are getting from these two pillars is 32 Now let's take the area from these right so the height here is max We will consider the minimum of both so minimum is seven and The distance between them is 8 - 1 That is seven right so 7 * Ba7 will give us is 8 - 1 That is seven right so 7 * Ba7 will give us is 8 - 1 That is seven right so 7 * Ba7 will give us 49 which is quite greater than the previous one right so we need to compare the maximum like compare the areas and we need to return the maximum value possible Now How Do We Solve This Right So While Thinking While Following Pattern We Will See That If We Are Moving From Both The Direction We Can Take The Area And We Can Store The Maximum One Right So We Will Do The Same Okay Now What We Will Do Here I've started the iteration from here Okay I've started the iteration from here Sorry from the zero index So I've started the iteration from here And for the like second pointer we will B Starting from back now what we will do is we will first need to get the minimum of both right so one is the minimum of one and seven so let's take the height as one in the minimum and the distance between both of them is seven so The area by both of them is seven now why like why do we need to take this right if we have a greater value than that so we will simply move this one forward okay now why are we doing this if let's say the a this value is Lesser Than This Right So May Be We Can See A Candidate More Eligible Than This One In The First Right One Is Like Kind Of The Least Value Possible We Can Get A Value Greater Than That So What We Will Do Let's Say If We Have I and J here the value which will be lesser in comparison like on the I and the in the J which ever is the lesser value that we will move forward okay so in this we will move forward now what will happen we have a height of At okay and the difference between them is a difference between them is seven and the height for this is seven right so we have to take the minimum of eight and seven is seven right so what we will do here is we will multiply them and Now we have 49 here right after that which one is the minimum of both this one right so what we will do we will move here OK now we will again take the area so what will happen out of this which is the minimum of this one is The Minimum Right So We Have Three Here Right So Three We'll Take And The Difference Between These Both Is Here It Was Seven Right So We'll Get Six Here Now We'll Get 18 Again Between These Two This Was The Minimum So What We Will Do We will move this forward again we will compare both what we are seeing both are equal so we can move any in this case okay and we can both actually we can move both of them the pointer forward so what we will do we have a here And 8 Multipla Ba 4 8 Multipla Ba 5 Okay or 8 Malla Ba 5 In the Previous One It Was Supposed to Be 30 40 Right I Mention 32 It Will Be 8 Malla Ba 5 So We'll Get 40 Here Now Here's What's Happening Both Are Equal So What We Will Do This Will Also Move Forward And This Will Move One Step Backwards Now We Will Compare Both In This Way We Will Take All The Areas Right And We Will Only Return The Maximum Value Possible So How Do We Do That Right Here we are performing some steps one What we are doing We are comparing the height at i and j so let's do that first if height at a is greater than the height at j What we are doing in true cases if j is lesser than we are Moving the j like backward when we are then what we are doing we are incrementing the aa value now we have this and before that what we are doing in order to get the area we are taking the minimum of both right so for that for area what We're doing we're taking first we're doing j - aa first we're doing j - aa first we're doing j - aa right we're taking the length and for height and we can say this if this is the length this is the bread right so for that what we're doing we're taking minimum of height Of i and j so let's do that now this part ok this conditions will be done after ok because if we will check this condition increment and decrement before only we will have problem in the answer so now a means after calculating the area only we need to Move the points right so this if conditions will be running after calculation of the area Now once we have calculated the area we need to store the maximum right so for that what we will do we will store the maximum of lets say our maximum is stored in Maxi so maxi of maxi and area okay so this is what we have to do in this question what we're doing once a means this is quite simple to understand what we're doing here is we're calculating the minimum of the two pillars and we're Taking the length of that and we are returning the area we are moving the points an according to the like minimum pillar if the height is minimum for that the pointer will move and the greater height will be staying at that point now why Are we doing that now let's say I have a height of at here and height of seven here right I'm not moving this height like I'm not moving this pointer because let's say there was a possibility at this index also that a point like a Height of at will be there right so if I had missed that then like let's say there was a there might be some possibility that between that we can get a higher a area possible so in order to avoid that when ever we have a Like greater height we'll be at that pointer only and for the lesser pointer we'll move forward okay so this is what we have to do here and as in the pseudo code we'll replicate this in the code editor so now let's move on to the Code editor let's see the code now okay we will be starting from the zero index and we will be like we will have two points one will be starting from the row index and the other one will be starting from n + 1 starting from n + 1 starting from n + 1 right so let's do that First now what we are doing is slow iterating from I and we need to complete the lesson only right we are moving from two sides and neither will come together and we need to stop there Need to do here first we will be calculating the area right so let's calculate the area wa was equal to j minus a and the minimum of height of i and j right so we will take the minimum of height of i and j after this What we will do is we will be calculating the maximum rat so let's take the maximum of maxi and area let's declare the max now what we were doing we were checking for condition also write if maxi sorry height of i is greater than height of j Then what we were doing we were decrementing each other wise let's take else only like we will not be moving both the points we will move any one pointer in case of equal also it is less than aa and equal to aa then we will simply increment Like a ps equal to ok now out of the look what we will do we will return the maximum area now let's try to run it ok it will be max sorry let's try to run it again the sample test cases pass let's try to submit it so This Code Has Been Accepted That's It For Today Guys Thank You For Watching If You Found This Video Helpful Please Let Me Know In The Comments And In Case You Have Any Doubt Let Me Know In The Comments To I Will Try To Clarify It And In Order To Continue With Me In This Coding Journey Please Subscribe To My Channel And Hit The Bell Notification So You Will Be Notified Every Time I Post A New Video Thank You For Watching
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
451 |
Jhaal Hello Hi How are you love you all doing good welcome to the learn co disney today will solve question tips and character frequency and social media level question and will solve discussion and even after you upload e used is on time urine se if chunri show Fear of approach how we will do soul slow agency the example date history and specific short with the first chief what is given in defiance of water stream near difference that possible britannia dum and episode on the basis of pregnancy a larger pregnancy the number should be Come First Shoaib Qureshi Ki Jodi Hate You Can See Suite Comp First And You Are Anti I Abhi's Work No Warranty Swelling CRS Modeler Day TV Show All Welcome First I Will Come After Some Years Were Going To Use That Audio Cancer And Dictionary Vibe X FOR MAINTAINING AUTHOR PQRS T U OK SOVEREIGN BOND ANCESTRY THIS BODDH AIR FORCE CHIEF ARN TV THAT FESTIVAL 'S AJAGAIN CTR THIS BEHAVIOR 'S AJAGAIN CTR THIS BEHAVIOR 'S AJAGAIN CTR THIS BEHAVIOR INCREASED AND DICTIONARY WHY BECAUSE THEY ARE GOING TO MAINTAIN K Heaven Airplane Mode of the Order of the Should Be Used to predict if you agree to t&c main suresh vision hai so let's purse mein ka safar dictionary hai hair ko * tower spring no water singh if i have difficulties in this speech in hair ko * tower spring no water singh if i have difficulties in this speech in hair ko * tower spring no water singh if i have difficulties in this speech in dictionary ke din it's ok tomorrow morning apni created adarwise hui to make NC One A Note Of The Too Is Too Short Illegal Dictionary Fennel Dad I Will Reduce I Will Dry Yes To Member That X Dio Effects On The Basis Of That Awadhi Ka Vacancy On The Basis Of Frequency Marriage Shopping So Now 202 Ok So No IF ALL THE CHARACTERS ARE IN THIS AUTHIS WILL BE THAT IN THIS WILL GIVE THE KEYS FOR LIPS LIST HALDI SHUDDH V COAT DISAWAAR KI KISS SAFER I LASH 34 A SOCIALLY AWARE MITNA SPRING IS A PLUS TO X PLUS ISER TRACTOR AND HC Multiply Vida Number Ka Abhyudaya Deaf And Frequency Should Avoid Doing Them Just Doing For Add Multiple With Two Shirdi Amazon Vikram Dushman 100MB The Same Thing Which A Scientist And Actor And They Are Depriving A Pregnancy Show Is Vikram The Same Time As It Is Present Any Citizen In This Way You can see a possibility listen to it vitamin double listen BK also have got and I values 5.1 se meeting on spring that and I values 5.1 se meeting on spring that and I values 5.1 se meeting on spring that and they got a great soul has written the effigy of indie is so ok sorted 21 custom lambda debit the x ok sir know its chief Ne decreasing order so IF you were raised in that VCRC 134 Vikram Member Vikram Divas OK 10000 Leo 186 Behave Just God Correct One So Let's Amazed You were saying no 10.25% on poster You were saying no 10.25% on poster You were saying no 10.25% on poster questions ₹ 1 This person got a ring in his mouth questions ₹ 1 This person got a ring in his mouth questions ₹ 1 This person got a ring in his mouth and Adjusting word dictionary on the basis of cancer in this getting all 21 and it for being an ifico piece to make the number of a person in the spring set show admin adhikari filmi video mein
|
Sort Characters By Frequency
|
sort-characters-by-frequency
|
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.
Return _the sorted string_. If there are multiple answers, return _any of them_.
**Example 1:**
**Input:** s = "tree "
**Output:** "eert "
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer.
**Example 2:**
**Input:** s = "cccaaa "
**Output:** "aaaccc "
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers.
Note that "cacaca " is incorrect, as the same characters must be together.
**Example 3:**
**Input:** s = "Aabb "
**Output:** "bbAa "
**Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect.
Note that 'A' and 'a' are treated as two different characters.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s` consists of uppercase and lowercase English letters and digits.
| null |
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,387,1741
|
910 |
Hello Everyone Welcome to Twenty Possibly DSP SS Master and Second in this Question Don't Give and You Can Perform Special Operation Inch Element Director Vikram Arya's Tweet A Number's Tweet and Aircraft Number's Promise Land Acquisition Subscribe to the Subscribe button and Subscribe color soya sauce MB setting which is question and Thursday maximum - minimum subscribe and Thursday maximum - minimum subscribe and Thursday maximum - minimum subscribe The Channel subscribe to subscribe Video subscribe Shubhendu maximum and this is Amolak Singh inch also something like this thank you do something minimum loot-loot subscribe to Aaj ke iss 3 hua tha aap laut demo number line morning 35 volume maximum do subscribe button aadheen hai on one hand without plot number on the number line financial the food and will always be part of - 08 - - The Observer to the volume - 08 - - The Observer to the volume - 08 - - The Observer to the volume maximum Will Always Been Doing It Will Find Us on Facebook Follow Me Subscribe Prev - 250 Elements and Answers 54150 Then Prev - 250 Elements and Answers 54150 Then Prev - 250 Elements and Answers 54150 Then Video The Channel and subscribe the Channel Please subscribe Free Now School Mobile Number Three Do Subscribe My Channel Subscribe to Brahmapur Blockade Minimum Qualification Malinga Test Andhera Answer and Effect Use 60 and Three Labs Subscribe What Do You Love Me Is Volume Minimum Boss Gillard's Tweet Volume Maximum Reduce From Its Maximum - - - Ki Ke Main Annu Yours Soil To This Information Available During Computer 100 Next 9 Is - Is - Is - Ki K 8 - Meaning Of Is - K And What 8 - Meaning Of Is - K And What 8 - Meaning Of Is - K And What Iodine Next And This Is Your Intentions But I Want To You Will Guide You All The Limits Of Possibility Subscribe To The Amazing Channel Now Subscribe to The Element A Probable Candidates for Your Answer Blurry subscribe this Video not support to the Video then subscribe to the Page if you liked The Video then subscribe to 123 Foreign 000 Ireland Line I Plus End What Do You Find The Minimum Tweet Volume Admin That What Is The Free Candidate Volume Minimum Rajeev Its Lutz Plus K Adarsh Cult Ko Mara PF Oil Plus One For Beginners Element In The Traffic From The Possibility Of That Highest - K That Highest - K That Highest - K And Others Five Plus Records of Women to Reduce to Minimum at All Times and Reducing - From Various Elements subscribe The Video then subscribe to the A Night - Minute Congress and Western A Night - Minute Congress and Western A Night - Minute Congress and Western Dress is Well Submitted and Passed to All Left Over Time Complexity and Esq Time Complexity Difficult Water Of And Can Also Log In Quantum Theory Of Relativity Quarter Of In Log In This Will Take The Complexity Of Water Of And Speech Complexity Videos Thanks For Watching This Video A
|
Smallest Range II
|
nth-magical-number
|
You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104`
| null |
Math,Binary Search
|
Hard
| null |
437 |
hey there F coders welcome back to another episode on COD Master Quest in today's episode we are going to tackle another question related to the binary trees so let's get started and find the problem statement on Le code the problem is path given the root of a bin tree and integer like Target sum return the number of passes where the sum of the value along the pass equal to Target sum and the pass doesn't need to start or end and the root or left but it must go downwards so if you look at the example number one we should return three because we have a pass here including five and three another one include uh 5 two and one and the last one which is minus oneus 3 and 11 so now let's come back to the visual studio code and try to solve this problem before solving the question let's talk about our observation to solve this problem I want to use a pre-order traversal and at each step I pre-order traversal and at each step I pre-order traversal and at each step I want to keep track of the Run exam so if we started from node um you know the root note and then move to the five and then move to the three the running sum is going to be 10 then 15 and then 18 right and we want to keep track of the number of u values for the running sum in the in a dictionary right so now let's copy the function signature and three node definition and paste it inside the visual studio code let me change to the visual studio code and paste the Cod there we go extract the true note definition since we want to work with this true note definition and then Define a helper function which is the pre-order Trav right so let's say pre-order Trav right so let's say pre-order Trav right so let's say pre-order input is going to be three pre-order input is going to be three pre-order input is going to be three node optional and current s which is an integer and we are not going to return anything from this function so it's Y and to get rid of this optional threee node uh let me guard it here let's say guard let root equal to root lse return and then um we need to extract the value from this root and say uh and before that since we want to change the value of the current sum let's store it inside the variable let's say car sum equal to car sum or current sum right and then uh let me say current sum is going to be equal plus equal to root. ra right and if the value for the current sum after this change is going to be equal to the expected sum we should increase um the number of um Times by one right but before that we need to um sort this target some somewhere right so let's say we have a variable here sum equal to zero at the beginning and then self. sum is going to be Target sum right since we want to um call the T the pre-order function um call the T the pre-order function um call the T the pre-order function after um setting the value for the Su root and the current sum at the beginning is zero right and maybe we can Define um count here as well which is zero by default and after adding the value of the root uh to the current sum we can check whether if current sum is equal to sum then let's increase the count by one right and after that we need to have the reference to the uh number of times that we see each value for the run examp so we need to have a dictionary here dictionary between integer and it's empty by default and we should increase the count by deex uh current sum minus sum and default value is going to be zero uh yeah there we go and then we should increase the number of times that we see this current sum in the dictionary so let's say dict for the current sum and default is zero increase by one and let's call the pre-order one and let's call the pre-order one and let's call the pre-order function uh for the left sub tree and right sub tree so let's say um root left and current sum pre-order root right and current and pre-order root right and current and pre-order root right and current and after performing the pre-order for the after performing the pre-order for the after performing the pre-order for the current U for the left sub three and right sub three we should decrease the number of time that we see current sum by um one so let's say dict current sum default zero in inrease it by one so if you look at here um we calculated the number of times that we see a pass downward with um summation equal to Target ZM and at the end we should return count right so if you look at here one more time first of all we try to uh get rid of the optional three node then since we are going to change the uh current sum during the uh to in this scope of this function let's make a variable in sense of this current sum then um increase the value of the current sum by the value of this root the value that we stored inside this root and then if the current sum is equal to uh expected sum that we set it here uh let's increase the count by one and since we are storing the uh you know each value for the running time inside the dictionary let's say whether we can find uh another pass uh by this difference inside the dictionary and if it's possible Let's uh increase the count and then add the uh the current value of the sum to the dictionary perform the uh same operation for the left sub tree and right sub tree and after performing um this operation we should decrease the number of times that we see um current s by one now to make sure there is no syntax error let me try to run my file there is some syntax error um current sum label is not provided so maybe we can add a one underscore here clear and run it one more time and it seems there is no syntax arrrow anymore so let's copy the solution come to the browser paste it just right here and hit the submit button there we go here's the solution for this question thank you everyone
|
Path Sum III
|
path-sum-iii
|
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8
**Output:** 3
**Explanation:** The paths that sum to 8 are shown.
**Example 2:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[0, 1000]`.
* `-109 <= Node.val <= 109`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,113,666,687
|
88 |
we're looking at lead code number 88 it's called merge sorted array and so here we're giving two sorted integer arrays num1 and num2 and we're going to merge nums 2 into num1 as one sorted array and the number of elements initialized num1 and num2 are m and n respectively and we can assume that num1 has in size equal to m plus n such there's enough space for the additional elements from num2 so you can see here on line 6 the return is void we're not returning anything we're just modifying num1s in place instead so there's a couple different ways we can go about this in a brute force way where we could create a third array uh get all the numbers merge them together and then just go back and repopulate nums one with the correct sorted order but there is a much more efficient way of approaching this and that's using two pointers okay so let's go ahead and jump into the conceptual and kind of go over how we would approach that so here we have our two arrays we have nums one which is one two three zero and nums two which is two five six and we have m and n at both at three and so what we can do here is we can go ahead and set our first pointer here to m minus one so three minus one so the index will be zero one and two let's just go ahead and write these indices in here just so it's a little bit more clear 0 1 2 3 4 and 5 and here we have 0 1 and 2. okay so we have our first over here at the second index it's just going to be m minus n right here we have this m as our input we're going to minus 1 and set our first there okay our second we're going to do the same thing we're just going to set it to n minus 1 so at the end of the array and we're going to go ahead and put this second pointer right there and then our ith pointer we want to set it at the end of our first array okay so we can do m plus n minus one or we could just do the length of nums one whichever one is easier we just wanna set this ith variable right over here at the end now we just do a simple merge we just wanna check is the first value greater than or equal to the second value okay it's not and so what we're going to do is we're going to go and uh update our i-th value here and uh update our i-th value here and uh update our i-th value here okay so i'll just go ahead and take an eraser here remove this and this is now going to be updated to uh to six i'll write it in green here okay it's going to be updated to the larger value and then what are we going to do we're going to go ahead and decrement our second index or s index and we're going to decrement our iath index and now we're going to ask the same thing which one's greater between f and s okay s is greater so we're going to do the same thing we're just going to go ahead and update our ith index with whatever was an s in this case it's 5. okay and then we're going to go ahead and decrement our i and decrement our s okay now we're going to ask the same thing which one's larger it's f so we're gonna we're just gonna update it in the same way we're gonna go ahead and update this to three which we get right here and then we're gonna decrement f and we're going to decrement our i and now we check again which one is greater they're the same so we're going to take it from the right side because we want to empty out that array first okay so what we're gonna do here is we are going to remove this s here or i'm sorry remove the value there at i and go ahead and put in what was in at s which is two and then we're going to decrement i we're going to decrement s now when s is out of range we know that there's no more values in this s array or in the second array and we can assume then that the array is merged because now there's nothing to compare to so whatever's left over in the first array is going to be in the correct order okay so this is how we approach this now let's think about time and space complexity how many times worst case are we going to have to go through this array okay so our time complexity here is going to be o of m plus n okay worst case so we can reduce that down to o of n for time complexity and what about space complexity well if we did the brute force way we would have to create auxiliary space and store all those sorted variables or sorted values in an auxiliary array and then repopulate the nums1 array so that would have been linear space but here because we're not creating any new space relative to the size of the input we're using these three pointers our space complexity is going to be o of one all right which is pretty good so let's go ahead and jump in the code and code this out okay so what do we want to do first we want to go ahead and create our first which is going to be equal to m minus 1 okay we want to create our second which is going to be equal to n minus 1 and then we want to create our i variable which is just going to be m plus n minus 1 or we can do nums one dot length we'll just do m plus n minus 1. okay and now we want to create our while loop we want to say while second is greater than or equal to zero so while we have elements in second what do we want to figure out which one is the bigger value between first and second so we can just put these in variables we can say let i vow or let first vowel just call it fval equal nums one at first and let s val equals nums2 at second okay and now we want to check if f val is greater than s val what do we want to set nums one at i to f val and then we want to decrement i and decrement first okay else what do we want to do let me just go ahead and create some extra space here so we can see we want to do nums one at i which is going to equal second vowel going to decrement i and we're going to decrement second okay and that's it that's all we have to do for this let's go ahead and run this make sure everything works okay we'll submit it and we're good okay and so this is a very efficient way of solving this you can see um we're getting 91 on space and then 60 percent on speed we'll go ahead and submit it again this is always off it just really depends on how the computer on the back end is running all of this here we have 85 91 so this is a very efficient way of solving this you could do it another way the brute force way it's a little more intuitive to create an auxiliary array put all the sorted variables in there merge them together sort them and then go ahead and repopulate nums one but then we're creating a lot more space doing it that way so this is much more efficient okay so that is lead code number 88 merge sorted array um i hope you guys all enjoyed it i just want to check did we go over space and time complexity we did okay and then just one more thing is that you can see that this is very frequently asked at a lot of these companies so it's definitely a good one to know and uh yeah so anyway hope you enjoyed it and i will see you all on the next one
|
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
|
764 |
in a 2d grid thumb - silly - when every in a 2d grid thumb - silly - when every in a 2d grid thumb - silly - when every cell contains of one except for those who come into this mines which are zero what is the largest access a line plus sign of once contained in a cleared we turned the order on to plus sign + n9 we turned the order on to plus sign + n9 we turned the order on to plus sign + n9 return 0 mmm an access of you understand time to point out soon hope it can nd down this hole okay that one don't you have to generate so n could be almost 500 and it could be almost 5000 mine so it's already passed away right now I'm just wondering if I should watch you can you know create this and you're late what is the dynamic here Oh like what is it I mean and this is tricky even knowing that it's time for Grammy okay tiny make two and so that just tells you that OPM okay I mean certainly you could do it man you are naively and oh and cube times yeah so then you probably want something better than that we just do two folders and then started each one in and do it off and operation to see was to pick us on that one I'm going to be to the columns and the work separately maybe that's another idea that possibly maybe doesn't mean world in persuaded okay like maybe the mines tell you something you know just like some real process of elimination you think because I mean knowing that there is a puss of order one does that tell me oh great okay but knowing that there's a person forward it - it doesn't really person forward it - it doesn't really person forward it - it doesn't really tell me anything about a possible one it three is it and can we do better than n Square where n is five I guess we don't need to do better than n square but it R but and cube should be fast enough where do you find a way to do but maybe that's time out I mean one thing I can think of it's just happening like a lookup table to kind of keep track of the strings of one so someone like that on both DuBose and calm so you don't have to keep you know to them and I would maybe point you to N squared you have pre-process in there squared you have pre-process in there squared you have pre-process in there good boy maybe I'm going to try that No okay you then you get to stuff and squared like a maybe should be okay thank you a messaging media yeah well hey also hey thanks for joining it again poster way yeah I was talking about it earlier I was just kind of figure just try to think it through a little bit before I was starting to code for this one where yeah good you could definitely pre-process two columns and stuff and pre-process two columns and stuff and pre-process two columns and stuff and most independently and then you stemis to generate like a list of candidates to kind of do it man this is a medium maybe I'm missing something very obvious yeah but uh yeah I was thinking about doing someone like that but I'm also just trying to think a little bit of like because I am we are giving one hint which is that is a dynamic programming problem and I'm trying to think like that's not wait like what is the recurrence for or like I know it's like half key like that mine I might not have thought of this as a dynamic program form to begin with but I'm trying to think well if it is then like you know what is the like what is the recurrence right well I guess you mean something else for 1d yeah I mean I think too good about other problems as well it's just I'm specifically practicing dynamic programming so and like certainly you can yeah it certainly you could practice other type of problems it's just that for me it is definitely something I'm weaker at if I could do them at the same time though like welcome and it I think one can tell I'm Malou or haven't been doing with these type of promises that are not good at thinking about it backwards I keep on thinking about like okay this is the first step how do I create a recurrence of that where I mean one thing that I've noticed while I was kind of going through what I've been doing is that I haven't been doing the pattern where like okay this is the last step how can I take advantage of dissipating the last step and what does it mean you know like backwards talking forward kind of thing but uh so maybe there's something like that there okay like well I think there is its appointment which like you can like it takes 2 min or for like maybe there's four things where yeah maybe that's it maybe I could have four time back like one DP for four and each of those contains the one if you will like the number of consecutive ones that are coming before and then you just kind of in one and then it your store cost it's just a min of those four things okay maybe I got it I don't know if I'm is describing a welder but maybe in the coda makes sense a little bit okay I don't want to write it if I'm being too uh too much copy and pasting and I just named the tomboy of the matrices I'm not doing to see actually yes things that are easy in my mind in terms of my preferences about square matrixes oh yeah I mean just by creeping in a way of shoe elements yeah okay and that's one for you to the direction okay this is very similar to there was a promise which biggest rectangle no greater or something like that or square and agree kind of I think the hardest part for me about these things is that like a lot of this I retain from just knowing the answer from a long time ago as i'ma like that so if I don't remember the answer or similar problems I don't know what was what's like a great approach to figure this out in a while but okay this should be infinite if I wasn't it's not paying attention - okay - okay - okay mindful minds okay so that's of the way and both in all the directions now we have to do is just make sure that we mmm maybe you could do this in a clever way coding but for now I'm just pin to it this way it'll be nice to make better I wonder typing yeah you go to there's a mine on it and we add it to the one to the left which is I minus one say to the matters on wheat oil directions so then that will keep track of the longest consecutive ones now before this position on the left side and then we do the same one for right okay actually it's not so this is a little more copy and pasting maybe I could clean this up at some point no because yeah I mean okay I can't just I mean it these two things like we've had to maybe I should just throw at this table way then you know Eddie's is better than nothing so this should be look quietly they're smart but I need this that is just left this up good we track the time how's this easier about the commedia even maybe there's an easier way so keep time to comment I think also it's just that uh dynamic program pause I just way you see the code up we're totally like you know I'm not spending like three hours writing a project so maybe that's why people tend to like those problems but nothing I agree with it yeah touch me that's why I need two ways I mean I could still combine them with or in tax time in a queen away the ice would be this movie is slightly easy to understand okay now the answer is just a blend of all those four directions in every way okay but cool me so let's see go to men of all those four things that did this one folder No yes and it's quieter because it could be anyone so bigger than okay hmm to do everything huh you dab it off by one because if you do them in the right order then this would be just one plus the previous one yeah it's definitely possible I drink TP by itself also just like lent itself to really clean code in yeah which I mean which is good well lived you might but yeah I don't know I think definitely it is a overemphasized in general because I think it's someone's identity we could because there's not that much coding you could squeeze in an end to be easier but whether I agree with it or not is another story okay me finish this one real quick so in those good oh no oh okay no I did it I did the inverse problem actually I think that's why I confused a mine streaks and what and the safe streaks nothing made a dish and I have to walk index one two three always be oh man type of well there's still one big huh but that was a definitely a type of in other guys they get one if this is another type of okay but type was a fine yeah well that's why we have testing right that's also why copy and case coding is bad when you have one type of instead your five type of justice because the fun even if not an amount there's some it okay cool hey I don't use that much memory which is good and I feel I just want anymore for into yourself a guy's deaf a struggle do but with this one twenty five minutes definitely hmm I don't know it's just kind of a mess like do I like I look at my code i yeah i mean there's maybe like a queen up some things but that's why i don't really like these things as an interviewer when I'm judging them it's an interviewer because I look at it's going like well that's kind of cool but you know it's just for loops and understanding is more important sometimes but I don't know I mean this is a video but I think this is also like no trickier than I would have imagined and that's or not call it mentos but it's a problem sulfate so I don't know cool okay we have the idea that I have here is that you know you for each cell I keep track of the maximum number of streaks of ones that are coming here then and then you do it from left up right down and the member of all those four things will give you the length after the pass at that spot and this is n square way I mean you could yeah these are all fold up so you could see the N square point very quickly so yeah you got try half of this one yeah okay yeah pretty okay class
|
Largest Plus Sign
|
n-ary-tree-level-order-traversal
|
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`.
Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`.
An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s.
**Example 1:**
**Input:** n = 5, mines = \[\[4,2\]\]
**Output:** 2
**Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown.
**Example 2:**
**Input:** n = 1, mines = \[\[0,0\]\]
**Output:** 0
**Explanation:** There is no plus sign, so return 0.
**Constraints:**
* `1 <= n <= 500`
* `1 <= mines.length <= 5000`
* `0 <= xi, yi < n`
* All the pairs `(xi, yi)` are **unique**.
| null |
Tree,Breadth-First Search
|
Medium
|
102,775,776,2151
|
63 |
Hello friends welcome to code Sutra and have a wonderful day in this video we'll be discussing about lead code problem number 63 unique paths 2. in this problem we are given a m cross n Matrix and we are also given obstacle at some point and this will be the starting point and this will be our ending part the starting is always at zero comma 0 and the ending will always be this point which is M minus 1 comma n minus 1 okay now there are few obstacles in the path which means you cannot travel through these obstacles and these obstacles are indicated by the number one and zero indicates that there is no obstacle okay now we have to find all the unique path starting from this point and ending at this point if you look at this example this is the only path and these two are the only two paths that will actually lead from the starting point to the ending point all the other path since this is at the center will have a obstacle and those paths will end so the answer in this case is 2. similarly if we look at this example this is the only path that we can travel and it is given in the problem that you can either travel right that is you can go in this direction or you can travel down these are the only two direction that we will be able to travel we cannot travel in any other direction sorry for the interruption but I have a very quick announcement that we are conducting a binary search workshop on August 13 and in this Workshop we'll be discussing from the fundamentals of binary research to very advanced level in binary research not only will be discussing problems but more importantly we'll be discussing about problem patterns that get asked infrequently in interviews so if you are someone who is interested in this Workshop I have mentioned the link in the description do consider joining the workshop now let's look at the quick observation and the approach that we can draw let us take an empty Matrix where there is no obstacle and see what observations we can draw now say you are here what are the two options that we have got either we can go down or we can go to the right and landed this place but I say as soon as you landed this place what does this problem get reduced to a matrix of 2 cross 3 that is once you have landed here you have no option of going back we have no option of going back similarly once we have landed down we have no option of going down so where is this leading us to this is leading us to a recursive approach or we can call it as a dynamic programming approach so that is where it is leading us but since there is an obstacle what we can do is if any path leads to that obstacles we have to stop there we should not proceed from that point so those are the quick two observations that we can draw now let's look at how we can actually build the solution let's take an empty array and try to build the solution let's take this example only first we will build for an empty array empty Matrix so this path we are at this path now how many options are there that you can come to this point from anywhere there is only one option right that is you can come from this Square other than this Square there is no other option now let's pick up a random Square in a matrix let's say this now how many options does this have either it can come from this or it can come from this so what we will be doing at every point we will look at the left and we will look at the top and how many ever paths are there we'll be adding those path for example this will also be one and one right now for this it will look at the top and it will look at the left and it will write to what does this mean this means that there are two paths to this particular point that is one from the left and one from the right similarly if you look here there will be three parts it will look at top from the top there is only one direction that it can come but from here since we can come to this point only in two different ways to this point it will be two plus one so it will be 3. so in total 3 similarly here also it will be 3 and finally here it will be 6. now this is the unique Parts if the given Matrix doesn't have any obstacles now let us write that with the help of an obstacle okay so let's take a three cross three Matrix once again and it will go the same that is since there are no obstacle here one and one now since there is an obstacle here do we have to do anything no right why because you cannot travel to this no matter what so it will remain as a zero now what will this be this will again be 1 because 0 plus one similarly here also 1 plus 0 it will be one finally we will have 2 and that was the expected hence so the first step is we'll fill the top layer the Second Step will we will fill the First Column then even if there are obstacles on the first path will stop there that is anything from there will have zeros for example in the top layer itself if there is an obstacle here can you go to any of this so all of them will be zeros and zero similarly on the First Column as well if there is any zero all of them will become 0 and the formula Remains the Same that is in this table what will be low while filling up the table we will fill it from top to right and we'll go from this direction we will go in this way of filling the Matrix so that will be our approach let me share the sudo code we first initiate the DP Matrix of the same length and what we'll be doing first we'll be filling the top layer that is the top row and the First Column right now we use this simple formula that is we are looking up to the left and we are also looking at the top and we are filling these values right so finally but one additional case if and only if there is no obstacle only then we will be adding this if there is an obstacle will not be adding this and it will remain as a zero and finally we will return our answer and there are a few similar questions that I would like to share and this is one of my favorite problems and this is a hard level problem but it uses a similar approach if you are interested please do solve this problem and we have a dedicated telegram group where we'll be solving similar products so do consider joining the telegram group thank you for watching the video please do like share and subscribe
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
76 |
Hello everyone, today we will give question number 5 of our sliding window mechanism, it is a hard level question of the delete code, so you will not find it hard, okay and we will make it easy, the name of the question is and it is a very good question, okay So this shows how popular and good the question will be. Okay, so let's see the question in the input and understand what the question is. So in the input you will be given two strings, one S and one T. Okay, you have to find the smallest window in S. You have to find the smallest window in No, there is one more window which is the smallest, this one, our answer is also correct, so the lunch of the first window is 1234567, so this is also our output, okay, so now let's see how we can solve it and it is very clear, see. After reading the question, I am getting to know that this sliding window will be the best solution. Okay, sliding window can be the solution for this. Okay, so let's see how to solve this. Okay, so look here, see what I will tell you the story, it will make this question very easy. Okay, so understand step by step how to approach it. Okay, first of all, look at the thing that has been given to you or what you have to find. So when you are iterating over S then you need to know that if it is A then is it present in A or not, otherwise to find out you will have to store all the characters of T somewhere so that If I can get quick access from it, then it is best that the map is fine and you have to keep the frequency as well. You should also know the frequency of which character has appeared how many times. So I am also the best. It is fine for this and given in the input. That is, lower case alphabet and upper case alphabet can also be alphabet. I am okay, so first what we do is store all the letters in T in the map, then which is the first letter in the team, this is how many times it has appeared. The first time has come, I have reduced it. Okay, now see that now I have given that brother, the number of characters that should be there. There is an account of characters, right? You should have that many in your window. Ok, the count required is 123. Well, it is clear till here. Now look, let's come here, I am here. Let's start from here and I am here right now. First of all, see that If this is my character on which I am standing right now, okay on which I am standing, if its value is present in the map and greater than zero, okay, it is present and greater than zero, what does it mean that it will be in our team, only then the map It is present in it means we need a character, so come on, if we need a character, then we have taken one more, okay, then it will go to our house, okay, and in the map, give a greater, it is zero, if we remove the zero, then we have got what we need, I will also ask you to check the account. So far I have understood it, okay, and in the Han map also, you will have to update the character you are in. You have to update it, okay, so now you update the account in the Han map, so see, I have an account. Removing this, I am doing mines here, so it has become zero, okay, now let's see, let's move ahead, yes, the counter is not available yet, account is required, so it has become zero, otherwise it will be seen when it becomes zero, okay. First, let's move forward, okay, now I move forward, so I move forward, now this is mine here, okay, do we have it on the map, okay, so we will decrease the counter , okay, this must not have been there in the beginning because There was no but now when he is traveling so di we got but di we need it otherwise it doesn't matter so we wrote di and changed it to mines so by default it is zero so if we add mines to it then it will become -1 di Okay, add mines to it then it will become -1 di Okay, add mines to it then it will become -1 di Okay, mines van means that we do n't need it, we don't need it, we do n't have a team, okay, because the character I am in, I have to mine it, its frequency is okay, I Here it is okay, so first of all, check whether it is in our map or not, if it is okay, then we will not change our required account, right? It is not in our map and its frequency. It is not even greater than zero, okay, then we will not do anything to our required account, okay, listen to my every word carefully, then okay, it means that we do not need such impacts, there is nothing, so neither have I told O. Dal given here is okay, similarly, it is okay here and Dal given mines van, let's go okay now let's move that brother in the map we have B, if it is there then is its frequency greater than zero, yes it is greater than zero means we need So what did I do, I did the mines, so everything is clear till now, is our counter done? No, we still need one, so still we are not doing anything, now we will move ahead, okay, let's move ahead. If you are saying then OK, I have gone, now here it is okay and then if the frequency is greater than zero, otherwise it will not affect the counter requirement, but we do not have to minify the frequency of I, now let's move ahead. I will have to, right? Now we will take A and C, so what did I do? Okay, the contact has become zero, it is clear and in the character in which I have reduced its vacancy to zero, okay, now what should I do to check what happened? We have got all the characters and that's right too, if you pay attention then you have really got all the characters in this window. Okay, you have got it. Okay, now look carefully, now I have got this window. Which has all the characters, okay, so this window, can we shrink this window? Okay, that's okay, but I want to do one more thing, the window that I have now, I want to make it smaller. What can I do, then where will I make it smaller, from the left side, I will make it from the I side, okay, Asar Pad Gya means that he has missed something in the window, if any character has been missed, then the count character should remain the required hero, okay, it should remain counter. But we can shrink it, let's check, okay, if we shrink it, then who is helping us in shrinking? Our I variable came here, okay, so first of all, what I said is that if we shrink, then observe window. It means if I shift I here then this part will go out of the window right because now it is in the window otherwise the frequency will have to be updated in the map plus WAN. Okay so first of all. Now where is the character number A? Is it on A? I am going to remove the character number from this window, there is only one character, only one frequency, zero, here, so we have done this, increased the van, okay, this is okay, now after this I will also check that is it good, is the frequency of ours greater than zero? You have made plus counter plus, I have become one, which was in our team, only then it will be greater than zero. Okay, so come on. I had to increase, so I increased, okay, here I increased, here, okay, here, but you see that counter, okay, now G will move ahead in its journey, okay, so now pay attention between I and J. What are the characters, we have B and C and the frequency of both of them is also zero. Here in the map, it is okay, only one frequency has become vane because we removed it from the window, it came and K is in the window, A is not there now. Now, to search for the same, we will move ahead, okay, so I have moved K forward, now K A has gone here, okay, now K A has gone here, so first of all, look at where it is in our map. Isn't his frequency greater than zero? Is n't it retirement? Its counter will be -2, you go to the house even more, that's why I am not doing anything right now, I am moving forward, the counter will be zero. Then that means we would have got a window. Okay, so I ask that brother, is the frequency of D in the map greater than zero? It is not > 0, which means I do not want it to be not > 0, which means I do not want it to be not > 0, which means I do not want it to be retired. Okay, so reduce the frequency of D further. If it was -1, then make it reduce the frequency of D further. If it was -1, then make it reduce the frequency of D further. If it was -1, then make it -2. Okay, let's go. DB will move forward. -2. Okay, let's go. DB will move forward. -2. Okay, let's go. DB will move forward. Now my counter is quid van is not zero, that means we don't want it. Okay, so reduce I also further and make it -2. Okay. Ca n't do anything, we will have to move ahead, now B is ok, so is the frequency of B greater than zero, it is not in the map, otherwise there is a counter requirement, we have made mine van, ok, now we will move ahead, there is still a counter, that means I need it, right? So account required means one will decrease because I need one, so I took A, here it becomes zero, okay, now look, we will increase it further, but before that, see this, the counter is zero, which means we have got such a window. In which all the required characters have been found and that window is mine, look carefully, in this we also have this, B is also C, OK, so now if the account required is zero, then let's remove it. What do you see the size of the window? Mines i plus van how much will it be 10 - 1 + 1 10 - 1 + 1 10 - 1 + 1 earlier it was ours and now 10 has come so only six was good so it means I don't want this window size ok so now we can check this let's see how much We can make it smaller, who used to help in making it smaller, I used to do it, okay, let's start the incident, let's fix it, so Ai is here, okay, so first of all, okay, so what is the frequency of Di, what did I say? Now we are going to exit from our window, so we will have to increase the frequency of the di, okay, the frequency of the di, here we have -2, this is good, okay -1, -1, -1, now let's see what the frequency of the di, which is the character I am on, should be reduced. So Diya but what is the frequency of Diya is greater than zero? Greater than zero means that we need it is big otherwise we also need a counter because we did not need Diya, now my Ai will move ahead, Ai in front of me is right here above. Okay, so first of all, it 's mine's van. Not only that, he is not there in our team, he won't be there, now I move on to B. Okay, now I've gone to A. Let's make I plus van, so look at the frequency of P. Now mines is WAN, if we add plus WAN to it then what will happen if the frequency of B is > 0, ok the return is not zero, that is why I will not do anything to the account required right now, A has just come here, ok, I will not leave our required, let's go. Okay, okay, when C is C, then the frequency of C will have to be increased. If it is on C, because we are trying to horn it by removing it from the window, then we have made C vane. Okay, now I will check the same again whether C is The frequency of is greater than zero, brother, give it greater than zero, it means that we need it, we cannot remove it from the window, then I will plus van the counter required that brother, I have shrunk the window, but while doing it, I Removed C which is what I wanted, so here's the one which means here we came here, then here A went. Okay, this window Ayurvedic has now made Sense Counter Required ours, so now we have to send K. You go ahead. And find the remaining character and bring it, now K will appear in the resume. Okay, so K brother, if you go, then G A is here. Okay, and Han, every time you are moving I, keep checking every time. Which was the smallest window found? Remember in the previous one, I go back, again I was here in the previous one. Sorry and I was here, right in the previous one, we did not check the window size. That time. Let's check it now, 10 - 5 + 1, time. Let's check it now, 10 - 5 + 1, time. Let's check it now, 10 - 5 + 1, okay, this six came, so our window size is also 6, so there is no improvement, okay, that means there is no benefit, this much was here, wasn't it here in the next time. And we told K that brother, you go ahead and find the rest, so yes brother, it is okay on the nine, no, it is okay, N is in our map, otherwise there will be no impact on the counter requested. If he will go ahead in his journey then he has been here in the last place, he has lived here in the last place, isn't there 12 but there is no place here on the index for 12 years, that is why I have written it on the side. Okay, so now he has come here but look, now this is the important part. If the question is ok, then A went to C, so first let's see, yes, it is greater than zero, meaning we need the van, so we made it zero, ok, it is ours, is there ABC in it, very good, meaning we got the window, ok, that's good. But what did I say, let's try to make the window smaller, can we make it smaller? Now Aayi Bhaiya will come to the rescue, okay? Now Aayi will come to the rescue, can we do it for us ? Okay, now look, Aayi is here now. If the above is fine then it is fine then okay if the frequency becomes miniscule or not if it is increased then okay if the frequency becomes zero then I will question whether that frequency is greater than zero, it is not greater than zero, that means we never wanted this. There will be no effect on the counter required. Okay, so I have moved ahead. When I moved ahead, you can see that our window is getting smaller, isn't it? 1 2 3 4 5 6 There is still a window of 6 size, so there is no update. Ok, let's increase the frequency by -1, so if we increase it becomes zero. Is the -1, so if we increase it becomes zero. Is the -1, so if we increase it becomes zero. Is the frequency of di greater than zero, otherwise this will not be required for the counter requirement, we should not even read it because we did not need di. Look, where is di in T? Come on. Okay, let's see, now I will move ahead, okay, I have moved ahead, now you are seeing the window size, how much has it become, the Windows size has been punched, I have taken i+1, so let's update the Windows size, the I have taken i+1, so let's update the Windows size, the I have taken i+1, so let's update the Windows size, the window size should be mine. The punch is okay, the punch is done, but you should also tell when the punch took place, where the eye was, the index 8, then note down that too, right, the start eye, because you have to send a string, no, in the response. If we want to send some, then we will find out from where my minimum window starts, we will also store it so that in the end we can send the string from eye to window size, then okay, I added 8 in the start time so that brother comes. The index from which I got the window size was the smallest, okay, 12345 is a very good Windows and it has become smaller, okay, and the frequency of I will have to be increased, okay no, it is not greater than zero, okay. We are looking at the counter, so okay, now it will move ahead, now I came ahead, okay, so first of all brother, I was happy that the window side has reduced further, look it has become four, so I am the first to change the window size. And I reduce it to four, okay, it has reduced, it is a good thing, so I have to change the start i also, from where did I get the lowest one, what is the index, I have written nine here and stored it, the start time is nine. A is very good now, so let's increase the frequency of B. The frequency of B has become that van. What has happened? Yes, it has become greater than zero, so here the counter is fine, so if you are removing it from the window, then your retirement too. The van should be increased. Now the counter quad has also increased and has become a van. Okay, now I have come here. Okay, why did I come here now? No, I am not okay. So, I have moved ahead. It means that you will have to move forward in your journey now. It will move ahead and whatever is left will be used to find the character but now if it moves ahead then it is out of bounds, that means our journey is over and the final answer that came to us was that brother, the smallest window size was four. Where else did it start? The index number started from nine. It is fine every time. It is easy from the ninth index to 4 lengths. This question is very good friend. It is exactly the same as the story I just told you, that is the same code too. I will do it line by line, okay, I will explain it to you very well, I am Pretty Sir, you will not find it difficult, it is also easy, okay, I will not say it, I have made this question medium, we Pretty Sir, we will do the lines exactly like this. And in the same way, if we will tell you the story so that you can understand it better, okay then let's start coding, then let's start recording it. First of all, let's find out the length. Okay, and one more thing, you should know this. It is necessary that you have to find T, cat in S, then it is not possible, that is, if the length is big, what you have to find, then I cannot find it, then send me a return, okay, what did I say after that? Was that we will keep a map ok now I would have stored till now it is clear ok now after this required account is equal tu kitna tha we have i = 0 j = 0 ok we have i = 0 j = 0 ok we have i = 0 j = 0 ok after that we will store window size start icon not store If you do this then it will work, where you are getting the minimum window, you can take out the substance only there, but if you repeatedly take out the substance in between, then it will become slow, isn't the good start only once, if you get it will be taken out in the last, okay? So it has just started, we have not found anything yet, okay, so now let's start the story, exactly as I told you, the story starts, okay, it will come out in our journey, okay, it will find all our characters, okay, so the first character. What is my S of G? Okay, so first of all let's see whether the frequency of this S in our map is greater. Give zero, which means we need it, which means it is required by us, so it means we will call the required account now as mines. We can do this because we have required it, so we have taken one if from the map and its frequency in the map has to decrease every time, so you have to do this, okay? Now after doing all this, what did I say that if the required count is Got zero, ok, start syncing D window, right? Keep syncing till zero, ok now we have to update the current window size with the window size, now we have got a better one, meaning if it is so, then it is ok by not changing the windows size. And Han, where did we get this from? Okay, fine, after that, what I said is that first of all, the character in which I have come is neither shifting nor sharing, so first of all let's increase its frequency, if its frequency is SFI. The frequency of which has become greater than zero means we must want that but if we throw it out of the window then our retirement will also increase and our required count will also have to be increased as if the story was ours, it is fine whoever comes, there should be no doubt. You must have been here exactly as told, it is ok and now let's ring Windows, ok, great, it must be getting cleared till here, all this will be over, if that internet remains only max then we would not have got it then. Then we will return it, then we will return it, okay, let's submit it and see, this question is very interesting, friend, I liked it very much when I made it, okay what's wrong, it should not have been returned, okay if I have a window, right? So he is sending all the examples, do great, have passed all the best cases, take the exam, solve successfully, this is the best question of the question, according to me, it clears a lot of things. Okay, if you have any doubt, you can comment in the comment section. do it
|
Minimum Window Substring
|
minimum-window-substring
|
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
|
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer.
|
Hash Table,String,Sliding Window
|
Hard
|
30,209,239,567,632,727
|
68 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 68 text justification before we read the question prompt i just want to say that 78.6 of you that are watching this 78.6 of you that are watching this 78.6 of you that are watching this channel are not subscribed and you're watching my videos freeloading getting this information getting these jobs and fang and you're not subscribing so if you're watching this video right now please subscribe before you go any further because if you don't it's bad karma you're not going to pass your interview and then i'm going to be laughing when i'm working and paying which i already am and you're not because you didn't subscribe to this channel so make sure you subscribe because i don't want to be solving these hard google problems pulling my hair out trying to figure out solutions for you guys and you don't even subscribe to the channel where the videos will stop alright cool let's read the question prompt given an array of strings words and a max with format the text such that each line has exactly max with 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 max with characters extra spaces between words should be distributed as evenly as possible in the number 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 ok that was a bit of a mouthful now let's look at one of the examples and see how it's supposed to be done and then we'll think about how to solve this question we're back in the code editor and let's look at one of the examples so we're given this list of words here this is an example of text justification and we're told that the max width is 16 and this is how we're supposed to return it now let's think about how they got it remember that we want to pack as many words as we can onto a line so that means basically we're gonna do this in a greedy manner so let's work through this so we're gonna first put this in there and that's gonna get rid of four characters right so we still have room because our max width is 12. so that means that on this line we still have 12 to work with right then we're gonna try to put is and we can put is because that would only take another two characters which means that we have 10 to work with and obviously we need to put a space between them because you know we can't just have them next to each other so really we have nine characters can we put an you know do we have more than two characters yes and remember that we need a space between them so ann is gonna take another two and because we have to account for the space we now have six so we get to example which is one two three four five six seven characters long and we would need a space which means that we need eight characters to actually fit example onto this line and we only have six spaces left which means that we can't actually put it on this line so it has to go on to the next one but remember that there's still six spaces left on this first line so we need to distribute them evenly to these spaces we have here so luckily there's only two spaces so that divides perfectly so that means that we can add three to both of the spaces so it would really be this and then we have four spaces so one two three four we have is and then we have again four spaces one two three four and then we have an and that way we'll have used all 16 characters so now this line is used up so we've gone through these words and this is no longer valid so now we're at example and now on this line we start fresh at 16 characters so let me just kind of separate these two and again so we have 16 and remember example is seven so we can easily do we can write it because that's we have space for it so we're gonna say example so that's gonna take you know seven characters right so this is gonna take us down to nine but remember we need a space um but we will you know account for that later so we've used example now of right to use of we would need a space and then we need space for two characters so we need a total of three so do we have that yeah we have nine so that means we can take a space and we can take of and we'd be left with six so we'll have you know uh one space and then we'll have of right and then okay then that means we have six spaces left and we get to text which is length four so to place this we would need a space plus text so total of five so that means that we would be able to place it because we have six so we can do space um of text right so the next word is justification which is obviously longer than our length of one so that means that we can't place it on this line now remember we still have one character left that means that we have to allocate it with spaces but there's two places where it could go how do we decide where to put it because obviously in that one last one we could evenly split the spaces between the two and it was fine but this is an odd number so we're gonna have to choose which one gets it so what does it say for us to do right if the number of spaces does not divide evenly between the two words the empty slots on the left hand side must be assigned more than the right so that means that this left space is going to get sorry this left space here is going to get the extra space so when we write this it should in reality be so we'll have example and then two spaces here so we're going to use that extra space here oops okay of and then we only have one space after the of so we'll have of text cool so now it means this line is taken care of and now we're just left with justification so this is one two three four 6 7 8 9 10 11 12 13 characters long and it's actually the last character in our or the last word in our words so we can just have it there so just if i hate writing with my mouse justification okay so we have justification which is 12 characters which means that we're going to have four left over so we just need to basically um oh actually it's 13 because there's that period there so it's period so that's actually gonna be um what is it 13 characters long so we have three left so we just need to put three spaces at the end and that's how they got their solution right you can see the three spaces here you can see the two spaces here the one here the four here and the four here so that's how you do it and looking at the example it's really intuitive and it makes sense how we're gonna do it but the actual solution is a pain in the ass i'm not gonna lie to you keeping track of all these things that we need to do is not so simple this is a hard level question so we're gonna go to the code editor and i'm gonna walk you through the solution i'm not really gonna hand hold you that much because if you're looking at hard level questions you should be able to follow this logic and understand how greedy algorithms are going to work and you know the topics that we're going to need to solve this question i think that if you don't understand them it might be a good idea to go back to mediums and solve a bit more before you get there because once you get to the hard level you should really just be able to pick these up quite quickly so i'm not going to do too much hand holding i'm going to explain my logic line by line but you know i'm not going to draw everything out and make it super dumbed down as if this was like an easy or medium question because if you're doing the hards again you should really uh be pretty dialed in at this point and you know be able to follow logic so i'll do my best to break it down as best as i can keep it simple but i'm not going to hand hold you too much so let's go to the code editor and write this out and it's not going to be fun so i'll see you there okay welcome back to the code editor even though the solution we went over previously it was quite intuitive and easy to follow from you know a hypothetical standpoint actually writing the code for this is more complex because there's some edge cases we need to consider and you know the actual mechanical implementation of it is a little bit trickier it's still not that bad it's just easy to miss some things so the approach that we want to go with here is going to be three-fold with here is going to be three-fold with here is going to be three-fold remember that we can have the case where the word that we're processing can fit on the current line um we could have the case where it can't fit on the current line in which case we need to justify it with the proper amount of spacing this is where you know the problem does get a little bit tricky and then at the end what we need to do is remember for the last line of text it needs to be left justified and no extra space is inserted between the words which means that we just add spaces to the end so that's going to be another edge case that we have to handle in pretty much all the cases is to deal with that last um last line so enough blabbing let's actually write the code for this the first thing that we're going to want to do pretty straightforward we're going to define a variable to store our result so we're going to say res is going to be equal to an empty list and we're going to need a pointer to keep track of which word we're at so we're gonna say i equals zero and we're gonna say width equals zero and this width variable is going to store the current width of our line remember that we need to know whether or not um our width is too large because if it is then that means that the current word that we're processing if we added it to the width it would you know it would go over our max width that's provided to us so we need to keep track of how wide we are currently and if it's too wide then we need to go to the next line and then also handle the actual spacing of our current line we're also going to need a variable to keep track of our current line variable which is going to be all the words that we have for a current line so what we want to do is we want to go from left to right through our words and then check whether or not we can add a word to our current line if we can we're just going to add it to the current line adjust our width accordingly and move our eye pointer up if we can't because that means that the current word would push our current width over the max width then we need to handle the spacing to justify the words that we currently have and then reset our current line to be the next character or sorry just to reset it back to an empty list and then we're going to reset width down to zero because now we're starting a new line and we need to kick the process off again so let's write that code so we're going to say while i is less than the length of words so this is going to be our loop to go from left to right we're going to say that the current word is going to equal to words of i pretty straightforward so far and now what we need to do is we need to check whether we're allowed to take this current word so we're going to say if with plus the length of the current word is actually less than or equal to max with then that means that we're allowed to take this word and it won't you know cause us to wrap around and remember we're not allowed to wrap around here so if this is true then we're allowed to basically take this current word so all we need to do is say all right we're going to take this word so we're going to say the current line we're going to append the current word and we're going to say the width we're going to add to the width the length of the current word whoops word and it's actually going to be length plus one and the reason that we do plus one here is remember that we need to account for the space in between words right it's not just all the words squished together there needs to be at least one space there may be extras based on the justification but for now we're going to assume that there's only one space and we'll deal with adding the extra spaces later so that's why we do plus one to account for the word and then the space that we need to add after it and then also what we're going to do is just we're going to increment the pointer and we can continue through our loop until we get to a kind of second case here which is when we're not allowed to take the current word which means that we need to basically reset our progress for the next line but we need to handle the spacing of our current line so what we're going to do now is handle this case so we're going to say the amount of spaces is going to equal to the max width minus the current width um plus the length of the cur line so essentially what this is going to tell us is how many spaces that we have to allocate right so we have max width here which is the max width we're allowed to use the width is the width that we um you know i've currently taken so far and then this length is basically the length of the current line so doing max width minus width plus the current line length will tell us the total amount of space is left that we have to allocate to basically justify our text and make it equal to the max width so this is what that spaces is doing and now what we need to do is actually add those spaces so we're going to have a variable to keep track of the number of spaces we've added and we're going to set that equal to be added and then we're going to need a pointer j to basically go through our current line which remember is a list of the words and we're going to add to those words um empty space to the end of them like equal to you know the amount of space that we have so what we're going to do now is we're going to say while added is less than spaces so while we still have something to add what we're going to do is we want to make sure that we're not adding um extra space basically to the end of a uh the last word right it doesn't make sense to add it well we can't add it to the end of the string it has to be you know between two strings so like we wouldn't be able to add white space to this and here it has to be you know at the end of this or is so that's one edge case that we need to consider is that we can't actually do it for the last word in our line so what we're going to do is we're going to say if j is actually greater than or equal to the length of our current line -1 so the length of our current line -1 so the length of our current line -1 so basically if we're at that last word in line we don't want to add any white space to it so this is an edge case we need to do so we would need to reset our um j pointer back down to zero uh and what we're gonna do is we're gonna say um you know we're gonna add to the current line of whatever our j pointer is we're going to add a white space there and what we're going to do is we're going to say added plus equals to 1 and we're going to say j plus equals to 1. so basically go through the words and add one space each time and essentially just keep going until we've added all the spaces now that i see this there actually might be a more clever way to basically just derive the spaces that you need up front and then essentially just add those number of spaces each time instead of having to go through it um but i guess this is just how i've managed to write the code i guess you can optimize it further later on but this should work either way so once we've added all the spaces what we want to do is you know that means that we have processed our line here and since we need to wrap to the next line because we're in the case where we're not able to take a word because it would cause a line to be too long that means that our current line is actually ready to be added to the result so we're going to say res.pend to say res.pend to say res.pend um we're simply going to join together these strings that we have in curling and we're going to add that to our result here and now remember that we need to reset our curl line because we're now starting a new line and we need to reset the width back down to zero and we're actually not going to increment the i here because we still have to process this current word now so it's going to go back here i won't change in this case and we're going to still be working with this word and now we can take it as part of our you know next iteration through the while loop so that's going to be the while loop and this is going to run for every single line but remember that we need to handle the last line which is a bit of an edge case because we don't want to justify anything we just want to add spaces to the end and the way that the problem is actually given to us will guarantee that you know this else statement here will never fire for the last line uh we won't have to justify the last line like this um so you know we don't have to worry about it being somehow incorrectly justified by the time we get to the end of the loop by the time we get there it should be ready for us to actually process so what we want to do here is we want to essentially process this last line so once we get out of this loop current line will have some values for it and we need to process it to take care of the last line um so what we're going to do is we're going to say for each word in range len curl line minus 1 and again -1 because curl line minus 1 and again -1 because curl line minus 1 and again -1 because we don't want to be adding white space to the last um last line here um what we want to do is we want to say current line of the word we're just going to add um a white space in between them right so essentially what we want to do is like uh if it's not clear so if we have the words like you know this is and whatever and this was our last line um you know we don't want to be adding any white space um extra white space right it just needs to be one space between them so it should be like this is am so essentially that's what we're doing we're just adding that white space there um and what we're going to do now is what we need to do is just add the extra white space at the end if there needs to be any white space it could be the case that it's actually already pushed as far as you can um but we will need to check that we have done that so we're going to say the current line minus one so this is going to be the last um you know letter whatever in our last line here so for in this case it would be b we need to add the appropriate amount of white space so we're going to add to it white space equal to what so we're gonna say that whatever the max width is uh minus the current width plus one and this value will basically just tell us uh how much white space we have remaining here um and that's what we need to add to our current line so hopefully that makes sense and then at this point what we want to do is we just want to say res.pen again we need to add want to say res.pen again we need to add want to say res.pen again we need to add this thing to our actual result here so similar to what we did up here uh where is it uh we basically just need to add the last line here to our result now that we have properly uh justified it with the kind of rules here that it should be left justified and no extra space is added so at this stage all we need to do is actually just return result and if we submit this hopefully we'll see we haven't made any bugs and okay cool we have solved the problem and our solution seems to work so just to recap what we want to do because this problem is a little bit more complicated uh we want to traverse from left to right through words and we're going to take you know the current word where we're at which is words of i and we're going to check if we're allowed to add this word to our current line because we keep track of whatever the current line is and whatever the current width is and what we want to do is we can take this word if the current width plus the length of our word is less than max width in which case we can just add it to our current line append to our width the length of the current word plus one because we're accounting for the white um so yeah for the white space that we're adding after it and we just want to increment our um i by one and then continue in the case where we can't take it uh we need to add the appropriate amount of um you know white space between each word and we're just going to do this in like an iterative manner i went over it earlier so you can rewind the video to that point if you want to go over this particular piece of code and then at the end remember that we needed to handle the um the left uh sorry the last line which has a special requirement of being left justified and no extra space inserted between the words so the approach that we did here uh would not be correct we need to do a little bit extra to handle that case so this is what this portion is doing so that being said what is the time and space complexity for this algorithm well the time complexity here is actually going to be big o of n and the reason for this is because we only have one loop to go through our words here and essentially what we're gonna do is um we're going to you know just go from left to right through the words and process them uh piece by piece so that's going to be the time complexity because we go from left to right here and the space complexity of this algorithm is also going to be big o of n because in the worst case um you know our current line is going to end up storing all the words and the reason for this is if max width is actually equal to you know the sum of all the lengths of words plus one or it's like plus one on each word individually then the current line is actually just going to store everything um so that means that current line would basically just store whatever words is in the worst case so that's why it's going to be big o of n there so that's how you solve this problem again this question intuitively it makes sense how to solve it putting it into code is a little bit trickier this would definitely not be one that i want to see in an interview because there's so many edge cases and areas where you can make a mistake it really is one of those problems where you have to think through the edge cases ahead of time and you know just be ready for them um you know this is a hard question i guess it's pretty you know spot on that google likes to ask this one um because they typically ask this sort of crap um but yeah anyway so hopefully you enjoyed this video hopefully it made sense um i think if it didn't you know maybe go back through the explanation see if you can't derive what the solution would be um or i guess work through the solution one more time anyway i'll stop blabbering now if you enjoyed the video please leave a like um comment subscribe and you know happy coding bye
|
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
|
910 |
hey everybody this is larry this is me going over day 21 of the league code daily uh challenge on lead code uh hit the like button in the subscriber and join me on discord uh as usual i actually solve these live and i do the um explanation live so however for this problem i actually had a lot of issues of it uh it took about 40 minutes for me to do it live so this little preview is me going over the solution um and hopefully in a distilled way uh and then you can watch me solve it actually more live afterwards um after i explain the solution a little bit uh yeah so feel free to you know hit the like button hit the subscribe button and enjoy my discord and all that other stuff but yeah so the idea behind this problem is it's just greedy um and just trying to think about doing it in an intelligent way i did not and i took it took me a long time to figure it out and it's just about case analysis at a certain point i actually um had so the core idea that i would say for this problem is that okay so let's say you have an array um right and let's say we start with negatives uh meaning that we subtract k from it from every element right well okay so then this is one snapshot that gives us a possible answer right don't worry about the rest of the stuff yet uh we'll go over it uh as we get closer let me also zoom in a little bit for better visualization okay it's a little bit too close but yeah but okay so given that you know we can always you know subtract k from all the elements therefore we can take our initial um our initial min as just taking the first element and then the last element and subtracting them to get the uh the delta right the difference um and then now we want to i want i was using the uh term greedy a lot but i would say actually another way to think about it is that okay so now let's do a brute force type thing oh yeah and also first of all we have to sort them so that it goes in increasing order um that is a key part of this problem so definitely do that and that's one part of the code i left in actually but yeah uh because then it makes it gives us uh properties that we can use later on because we then assume that um given to adjacent elements the early element is going to be smaller than the later element right so then now um because of that properly we can make some adjustments right um well let's say we just pick end points at random like you know make this bigger well does that have really help maybe we can figure it out but and if you do it that way for random number of them this can be uh for input size of n it's gonna take two of n's possible combination to switch this up to positive right so the first thing i would notice is that um let's say we started with subtracting k from every element let's we can switch oh we look at the first element right well the thing is given the first element let's make let's switch this to adding k right well what happens well there are only a couple of cases which is that okay this is now either um still the smallest element and if this is still the smallest element then well then this is gonna um then we cannot make this element smaller this we cannot make this element smaller and all the way through right um so that means that the answer is set in stone once this is true right so then we can return immediately let's say this is an element now this price um we don't actually do the actual sorting but let's say we sort it and we have we moved this to the uh bottom because now is the biggest right at the latest well in this case now you just do the math because this is a new example of okay well uh now the next number you know that's gonna be the smallest and then so you just compare it to the biggest element right which is as you know um we do a comparison if this is if this number that you just added is bigger than the biggest uh number then we have to do some maths right and there are a couple of things to notice here is that when we add this number this only makes the number worse or that's not true actually but if you add this number it doesn't you know it may change it but we're not testing that yet um and also if you look at every other number like if you add this change this to a plus well this is going to give you a worse answer then if we just leave it to this right so and the reason why that is because um if this is the biggest number then you know the balance between these two numbers the beginning and the end uh if we add this if we change this number to the nat then by principle this will either be well this will either not change the answer or this number is bigger than this bigger this number which would make the number worse or the answer worse right so then this is our new element right and then the other case that we can go over and this is just case study in a way is that okay let's say this is in the middle right well then what happens well what happens is that okay that's well let's do two things right one is we check whether this number is the delta between the first number and the last number check to see if that's the smallest if it is the smallest then that's a possible answer right um if it's not then you just move on it's fine right and then now you go to the next number uh which is this new number now we're on this number okay right so then now here now we try okay this is a similar way but it's not the same but now we try again okay that's what happens if we add this to a plus well there are two things right one is now this is uh now this is the biggest number right um and if this is the biggest number let's just call it the second i'm just gonna add two for a second this is for first number um if this is the biggest number then okay we changed our range let's check just check again we do a check from here and here so basically this is your second index and then your dirt index check to see whether you know you have a better answer or this is in the middle right and this is something that when i solved it live i missed a little bit was that um this is this next number could be in the middle but you know that because we both add both numbers by k this has to be here right so this number has to be smaller than this number so it's either here and that this number so then if this is the case again we check you know this number the new third element and then the last biggest number right we just update the best value of course or the other cases that actually you know if we go back a little bit um actually the first if we put the first number here right and then now we change it to a plus we put this in the in here um right because of what we said that this number has to be strictly less than this or greater than this number and because this number is bigger than this number um then the newest smallest number is actually the first number the added version of the first number right so then in that case you add you track the difference between this new min number and then the new or the old max number so that's basically all the test cases and in that way you keep on going from left to right uh checking what happens if we change this to a plus one at a time and once you're able to do that in a consistent way then go through it um then that's how you get the code and answer um so do i basically did this live uh and i ran into a couple of um observations that was a little bit wrong and that's why it took so long but yeah so i'm gonna go for my code real quick to kind of go through what we went through but again after my explanation you could watch me solve this live um which was a long video and you could feel free to fast forward for it but hope hopefully you'll you know see where i did well and how i attack uh a greedy problem even though it's a very tricky one for me but yeah so we again we start with subtracting every element we take the initial best answer as the first and the last uh because the first is the smallest and this is the max number and we update the max and then here for each iteration well we go through this thing we change the current number to um to add k and we add it twice because we have to first compensate for the fact that we subtract k the first time and then a couple of cases right which is that okay if the new or if the new number that we just added if it's um if it's the smallest tender if it's the smallest number which we said is smaller than the next number because if this number we add k is smaller than the next number minus k then a sub index will always gonna be the smallest number and you cannot do better so then we return best here um uh and we double check that the smallest number is this new number or it could be the first number right because of that visualization that we did where the first number is always going to be uh you know and this first number also we already added but that added number is always going to be the smallest number going forward after a certain point right so yeah so that's our one of our case and then another case is okay if this new number that we just changed to addition um is between uh the next number and the max meaning it is in that scenario where we um when we're in between then well then the new best is either um the next element or actually and actually this is not necessary so this is a little bit confusing uh but yeah so this is either the next element so either the next element which is the negative version or negative k uh sub uh we took k from or the previous um min which is the smallest number with the addition right so one of those minus the or subtract that from the max and that's our next best answer and we continue otherwise well otherwise then a sub index with the addition is the new max and it's always going to be a new max until the next number that you updated so then mag reset max is equal to this number and then again we subtract it from either the next number which is the negative version and it's just the new min or the old man which is the added version of the first element right um and then at the end we just return the best results from all these possible uh segments and that's how we get the answer um it is kind of tricky even though this code looks really short and mostly straightforward uh but i hope that uh you know yeah and this is technically just a sub index plus minus one but uh but this is really tricky so i would definitely recommend uh um going for it a little bit so what is the complexity of this right well we're dominated by the sorting so it's gonna be n log n because human and because this is just of n from the rest of these loops so it's going to be unlock and time in terms of space it's going to be linear space because well it didn't tell you when to find it if we are able to modify the input array which doesn't really make sense because uh if you put this as an input and someone changed your input uh as your response then that's not an acceptable answer so i'm gonna assume that you know in code i actually don't use extra space um i'm gonna assume that you make a copy of this and you should so you should just do something like um let's just say this is b which is we just make a copy of b right um so this is going to be linear space because we make a copy of it and then we use it later and that's fine because you really shouldn't change people's input uh but if you want to you know be say it's okay for employees then um then technically it is over one extra space um but yeah and of course i would also say that you can actually um do this for you know you could do this part by just having all one extra variables by keeping track of the min and the max in the clean way however because you're still sorting that still modifies the input so that's still going to be o and uh space if you don't want to modify the input even though here i modified it to the next degree again this is a tricky problem for me so let me know what you think uh and you can watch me solve it live afterwards uh it's a long video feel free to watch in 2x or whatever your favorite speed is and even my explanation is like 14 minutes so it's way long for me it's tricky and i will talk to y'all later bye-bye hey everybody this is larry bye-bye hey everybody this is larry bye-bye hey everybody this is larry this is day 21 of the december lego daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about jay's prime smallest range too so i do solve and explain these problems live so if they go a little slow feel free to fast forward and jump ahead uh okay so given an array of a you can either choose minus k or x is zero k okay um and you're trying to get the smallest possible difference between the maximum i okay so the first thing i'm doing now is just looking at the constraint to see whether we could play around it a little bit more um so each number is going to be up to 10 000 and k is less than 20 000. so we can probably do some sort of greedy uh either on i mean a couple ways to do greedy to be honest is you can sort a and then you know move to move certain numbers to uh increase and move numbers on the bigger side to you know small so there's certain degrees of that uh we might have to be careful to play around with uh the numbers in between and yeah and i think that's roughly how i would think about it um yeah uh it's just going to be some sort of greedy and some sort of like jiggering if you want to call it that to make sure they're right um but it's going to be some sort of greedy and with the edge case being like we have something like this you can you know the three is going to be outside the bank either you add it or subtract it and that's going to be part of the trickiness as well so yeah um i'm still trying to think about the actual implementation um like i feel like the idea is going to be right but there may be also be edge cases because greedies are kind of tricky to kind of get right and you know in the easy case these are easy but this is probably the tricky case where it will inform me how to get it and you have to go you have to add or subtract k right so there's no choice but okay let's first but and noticing that it's going to be 10 000 we can actually just check the bounds a little bit um but let's see i think so what i'm thinking right now just as a fact as a dot is whether i can binary search right and the tricky thing to note is that even though i said greedy is a thing if you greedy add a number to the left um you can actually subtract a number from the right the biggest number and it may be the new min right and that new min may pose a problem in terms of thinking about it in like you know like then varying of you're going from left to right on might not be may not hold true because you assume that the first element is going to be men but that might not be well that just might not be true right um and then you have to redo the math and that may be a little bit tricky but then my question is my thought is would you ever well i would also say that you always want to increase the first number no matter what i think that's a basic base case um and the reason why that could be is like you let's say you have one two three and k is say just ten thousand something very great uh if we make it negative uh 99999 it's always no matter what it's going to be um the same as or like you know this is the same responses um like we if we subtract k from all these numbers that's gonna be the same response as adding k to all these numbers right so in that sense um we don't get any new information so then for me then okay the only way that the answer can change from that base case is if we add to it right and then what happens when we add to it is something that we have to kind of think about um and from that i also think about whether we can binary search from that all right uh and um and there are other ways to bind there's definitely a binary search one but one that takes it um takes advantage of the fact that this is ten thousand i think so one binary search would be just okay let's say the smallest number can be um negative 20 or negative ten thousand because that's the smallest number that you can go from zero to negative twenty thousand um then you can binary search the max number um or not um can you is that too slow that may be too slow actually but uh but that kind of idea may have some merit i don't know but yeah as i said i think i am going to sort and then i'm going to take the first number and increase it by k right and then there are a couple of scenarios okay so let's set our base case which is the best which is you go to uh oops the last element plus or sorry minus the first element right um and this is even though we don't do any modifications to with k we can assume that we just subtract every element by k as we said so that's what this means essentially and we could just do this um now that we change by the first element by k what changes right well we start to process whether to add or subtract from the next elements and that is curious because in this case huh i feel like so d i would also say that these are the type of problems that i'm actually a little bit weaker at because i feel like it's going to be some sort of greedy but then it's about like implemented in a way that i know to be correct which is always uh and proved to be you know at least in my mind correct but i'm always in my mind i'm just thinking about different um inputs and as i go for different inputs in my mind i'm like okay well actually that's an edge case and that wouldn't work so i'm just trying to think about okay what to do about so if it's sorted we can maybe look at them one by one which is for x in the suffix right okay i think i have an idea right so the two choices that it can do right okay i think now i'm coming over an invariant which is i think maybe to be honest a little bit dependent on a sort of a dynamic programming but not really but um but now i think what i want to do is just keep track of the min and the max and going through them one by one in some way i think i had that idea but now i have to articulate it in a good way um but basically for each number right do we want it by to be the new men so basically if hmm okay i think now i know that this is a long video but i think i have a another way to articulate this which is actually which is that okay this concept of min and max right so basically now i look at each element and this is sorted so it's going to be in an increasing order um let's say we you know subtract k and then in this case uh the smallest element it's going to be in the first element right and then now just for you know try to figure out how to do a possible you know all possible things well let's say we convert this to a plus right well what the hell happens either this is still the min which is fine that means that um this is our new answer i think actually because if this is still the min then no matter what we do we cannot do better than uh what is already given right because if this is the min if we add k and it's still the min then we can you know the second number cannot be bigger but you can make it worse by adding and so forth for the all the way to the last number where you know if you subtract it then it is going to be closer to you know the number that you added and that's greedy right uh but obviously if you convert this to a plus then it's just going to make the answer worse also by you know obviousness hopefully um okay so then so those are the two cases right so then now let's say we add this to plus and this is no longer the min um so now here we say okay we look at the sub element sub ray sub array but we look at this element if this is minus and this is a plus then um well the two scenarios right as we talked about one is that this is the new min if this is the new mean meaning that you know this plus the first element is bigger than the second element minus k then this is the new min um so then we can you know treat this as a new array because now we could just ignore this because this is going to be inclusive except for an edge case where this plus may be the biggest number in the way which um yeah i don't know right like for example in this case if you add instead then you may get um or yeah uh negative 9998 negative 9997 right oops but again in this case we can do the math um and yeah but then this would be the next main element right so i'm just trying to think about in variance and what doesn't change as we do the loop but in that case we can you know set this to the max or whatever and then go on right so okay so the two cases let me type them out so that i feel like i may be repeating because i'm still trying to go through this problem in my mind so yeah if second element is now the smallest then um first element with plus is either in between meaning if this element is in between here then it's not interesting at all and then we could just remove and ignore or it could be the biggest element between or is the biggest element right um and then the other case is what we talked about already which is if the second element is not the smallest then we can we then we are done because the first element with a plus is always going to be the smallest and any changes will only make it worse okay so i think this part we talked about and i think that makes sense easy to code but this part there is an additional concern i have which is that okay what if it is in between again then we're done with the first element to be clear uh and then you can kind of um you know think about this as a sub problem and then just solve it for the separate way ignoring the first element right or if it is the biggest element then what happens well if this is the biggest element then if this is the biggest element let's call it and how do i want to phrase it so now the plus we moved it to the back as a and this is done right so just to be clear like we don't have to edit this anymore um i don't know if the exclamation makes point but that's gonna if it's the biggest element then there are two things to do right which is okay well if this is a subtraction then we already have the sub problem to solve which is that we assume that the first element is the biggest element then you know we check to see if this is the new best answer right otherwise we also want to check the plus and then now it becomes a little bit i wouldn't say recursive but iterative now going forward we go okay let's have a price and then now we look at the next number and then here we ask the same question right is this the newest number is this between the thing or is it you know the nearest big number right if it is the newest then we update it and put it in the back again um of course we don't process this more than you know twice but yeah so i think now oh that was tiring um and i hope that you're following along i know that this uh video has been going on for about 15 minutes it is longer than usual because i haven't you know i don't know how to solve this in a any faster than you saw me so i it this may be the first problem i uh the first time i've seen this problem and i don't think my usual um pat like it's not a problem in which you're like oh it's just this algorithm right so i had to work it through so i hope that the thought process um you know even when i was trying out in my head without code uh different examples or different uh processes with respect to like binary search and then it didn't work and stuff like that right um hopefully this is a good template for it and now that i have this we can just code it right so okay so we sorted it we set the best as you go this now let's um i think there are ways that you can keep track of stuff but i think for the first iteration um i'm gonna just write the code as dumb as possible and then we could clean up afterwards right so uh so yeah so let's write this so for so okay so let's start with n is equal to length of a uh and then now we can do for index in range sub n so yeah okay so if index i mean we only handle the original case so let me that's for the sake of uh maths uh to be consistent with what we showed i know that actually you can make some implicit uh implementation things so that you don't have to actually implement it but let's actually just do this with a sub index let's subtract k and then we'll start again with another pass you can actually be a little bit clever about it but i think it just makes it a little bit confusing and have potential for mistakes so for index and range in the second pass now we want to see if we can add this index right add k and of course i'm going to add it twice to compensate for the fact that we subtracted once right and then now we check okay and we're going kind of do the thing right so next element is equal to a of index plus one we'll go over the edge case with respect to this last element later maybe um well no i think we could actually just subtract from one we don't need to care about the last element now that i think about it because for the last element you never want to add it for the same reasons that you know because if you add the number to the last element it can only make the answer worse than optimal um at least it'll be worse than this case right where every number is already negative so i think we can safely do this though leave a comment if you're unqueer about that um okay so then now we check um okay or so just use no okay that should be fine um okay right so okay so if the next element is bigger than a of index or even equal to because if it's equal to like i said you can only make the number worse by increasing it and because of that logic um you could propagate it for the other ones so then here i think we can return immediately because of the same thing that we said which is that um yeah if um let's say there's a plus in front uh because we already added the number and if this if the next element is smaller than or if this element is bigger than this element just making this a plus can only change the answer and if it stays a negative then you don't change the answer right and don't change the end of in a positive way okay so we can return early so then now if the second element is now the smallest which means if the opposite of this so this is an else i'm not running the else because we return early here so then okay so then if a sub index is either in between so if this is bigger than the last element so this is the notation for the last element in python in case you're not in wifi but um if this is let's do the other one if this is in between then we're done then we can just continue but we have to do a check we should have to do a check for the best which is that okay if this is the case uh and of course this um let me actually rewrite this because i know that i will next element to be clear but i think this is actually clear at this point right so if this is oops this is if a of index is greater than a of index plus one right so in this case that means that if you want to be explicit about it um and i think this can be equal too as well actually because same thing right so this is if i have indexes in between this right this is what i'm saying more expressively i know that we didn't have to write that but i actually i figured i might as well write it for readability reasons um so if this is in between then we can continue to the next um index because we know that uh we can just throw it away essentially right in a way because we know that um if this is in between then we're done because we're not going to make the answer any worse right and then now if this is if a of index is the max so else if a is of index is greater than a sub 1 and i know that this is an else and from this can this is always true but i just want to be explicit um with respect to here so yeah um so a of indexes to max what happens right well then we update the max element okay yeah we update some x max element so max is equal to a sub index right and first let's start having this is equal to the last element is the max and here then actually we have to update this because now we're comparing it to not the last element anymore but the max element it's a little bit confusing the way i explained it for sure but this is my thought process as i'm coding it live so hopefully that's okay so that's basically the update loop but we don't have an answer obviously and yeah and you know we could figure it out right so how do we want to figure this out uh just to be correct right because okay so if this is bigger than this is already the best so we don't have to update here if this is in between we also well in this case then the smallest is going to be index plus one and um and then max is the highest rate so we can do i don't know if this is necessary strictly but that's that i'm going to write this so that um oops uh just to explicit so it's max minus index plus one because this is now just the new smallest of the entire length right okay and then here um the max of course now well actually we could do it afterwards it doesn't matter because this is always true right so uh so we just change how you write it and then now the new max is now the new thing and also um you know the smallest is the next element as we said because otherwise we always returned so it's going to be just this number again and at the very end we can return best um okay cool this is a very long video i hope uh this is understandable let's run it real quick to see if any typos awareness or just wrong answers uh yeah let's do this oops oof wrong answer that is a little bit sad hmm well i changed oh did i put max i think i remember putting max baxter because i'm i don't know i think i've been just been talking about mac so much but we all obviously actually want this to be min because that is what they ask you for the smallest possible value uh huh still wrong so this should be two and this should be eight right so why is this wrong for this default case hmm that is weird why did i get 10 i mean 10 is in the beginning right so okay so let's check real quick um i think let's also just put impossible so that i can kind of make sure that i don't know that just print a just helping me visualize uh this is for the last one so that means that this doesn't even get here right if this is bigger than that then a sub index is already the smallest element i think i just don't update it on the first loop though this is still wrong for the last loop but let's move this down here is for quality so yeah i think i just have to keep track of a little bit more things so okay oh n is two so this is this should go for this once right yeah two and eight um but we never update the best is that normal i guess not max minus a of index because a of index is the smallest maybe i just assumed that it would get updated previously but maybe not for the first element so we can run that real quick and that should be good for this case but now we have an issue here why is that i think it's because i don't maybe i update this too aggressively here because i remember seeing uh and it's good that our impossible never kicked by the way but uh we could print a real quick a lot of debugging today debugging central so hmm let's put this in the back okay oh no max is four but this is six huh let's print out more things uh just for just to be sure about why i'm getting one yeah max is six so why is does it give me one hmm yeah that's i admit i have a typo somewhere because six minus three obviously would be three is this one now i mean because this is what we update when we're here right so we only check four zero and six three do i update best somewhere by accident i mean this is only the other place where we update best so that's a little bit awkward i probably have like a really silly typo somewhere um because i don't know that's just been my ammo lately unfortunately but hmm like four minus i mean all these invariants are right except for bests let me just take one out pass it around oh because this mx oh wow i have to be a little bit careful that's just me being careless then because what happens is that this gets updated with the old max before this condition and for some reason i thought that i could generalize by putting them in the same price but i actually needed this first so okay that it i mean it's good that my ideas are right but my implementation it's a little bit bad that my implementation is not let's give it a submit because i'm a little bit tired and it's about half an hour in hopefully it's good but it is not oh no uh okay let's see let's put it back in uh why is that wrong so we have one because we how did i get seven in the middle how did i get five oh that do i sort this yeah i sort this right yeah so i have one three ten um so that's four seven six that's right oh that's what i guess where we want it to be except for that there's something wrong when something is weird because this should not execute like this for sure so what do we want okay let's say what did you say was 1 310 so basically what is our ideal her code uh 1 3 10 in theory we want this to be it's four right um so we want this to be five seven six and what does that mean that means that when we have a five we actually won one three ten so this is actually negative one this is six um so when five gets up five is in between this so we do a min of the max and this so this is seven this gets updated to seven this should be good and then the next iteration we have negative one oh i missed a case i think where we okay well now we try no i think i thought about this case if i handled it incorrectly for sure where we add the number to seven um and now we have to care about the previous number because by definition the last number is going to be bigger than this or smaller than this number so that this is no longer the min even if you add it i made a wrong thing here um we're done with the first element so this is not true i was wrong on this we're done with the first element if we keep minus or we that's why initially i had a concept about keeping the min element but i think i got a little bit confused afterwards but okay whoo this is hard this is a tricky one to get right um at least for me this might i don't know um if we keep minus or the previous element is the smallest okay so how do we so this is in the middle so we have to change this case right um so this is the min if so basically it is just a sub 0 then right it's either oops now this is either a sub 1 this um okay so i think my thing is and i'll explain a little bit if index is zero what happens right if it's big then we just take a sub one so best is equal to min plus mx minus a sub 1 um else if it is not the zero then what happens you add a number but then that means that your smallest large and assuming that you tried adding it to all the previous prefixes um the smallest number is always going to be either the next number which we have or the first number which we added on so it's going to be min best mx minus the min of either a sub index plus one or a sub zero which a sub zero now has to added stuff right something like that i want to say oh still wrong answer though so definitely missing some other elements as well because basically here we want so okay so for the second element well we have to update here as well because so i only looked at the first index and assumed that i would go recursively but or iteratively but that was wrong uh this is a tricky one but like i said greedy problems are hard for me anyway so if a sub index is the new max then what is the min right the min will be again this similar thing right okay yeah either this next element or the a sub zero okay because again in this case we have to take the smaller of these two and a sub 0 already has the addition one and a sub index plus one has min or has minus there's a lot of case analysis for this one but uh i'm gonna do a quick summary at the end and also go red deep oh wow i am i should test more but i just i'm a little lazy today uh or like we're 40 minutes and so yeah so okay 3 2 10 why is that wrong so we have 2 3 10 we have the answer we get is 3 and expect the answer is four expect an answer is four and that should be obvious because this is just four or five uh oh sorry oh wait what is number two yeah four five eight right it's a four and ten or eight or four and eight or four so how do i get three hmm dun let's also print a sub-zero long day so we want this one four one eight okay this one is seven and what i did once again two three ten so you add two so it's only four one and eight uh so four is going to be in the middle that's fine we have one and an eight okay so in between that's good but then now we have to look at um the next number right so then now we look at the next number it is this thing and i think this is probably i just didn't take re-evaluate i just didn't look at this re-evaluate i just didn't look at this re-evaluate i just didn't look at this case again because i think previously well that case has been wrong every time so that's probably what it is returning um so okay so basically what happened is that okay you have a you have the three uh where's the three other one and then now you add four back it's gonna be five it's already bigger than this number so then we return the mean of this which is not true right this is actually the min of this number and a sub zero okay so this is actually uh it's a good problem i think i made a lot of silly mistakes okay accept it so yeah um it is a 40 minute it is very unfortunate um but at least we finally got it and hopefully you saw how i stumbled on everything but um but i think that's the thing with greedy is that sometimes you see a pattern and you think you're right but you have to prove it and you have to be careful and i did not do eight of those things um so that's why it makes these things hard and hopefully you watching me solve this in over 40 minutes uh it's a good you know example of someone who struggled with this one um even if they're supposed to be good uh but we did work for it we did uh solve this problem even if it was a struggle so hopefully you learn from it um okay so what's the complexity it should be this is a yeezy complexity first of all note that we sort so it's going to be n log n uh at least um and then after that each element we just look at over one operation so again it's gonna be dominated by the n log n um the rest then the space we actually don't use any extra space however we do edit the input um so i'm going to call this of n because we should not edit the input and be careful you should make a copy and don't edit the input so yeah so it's gonna be of n and yeah that's all i have for this problem um i think well okay let me let uh yeah i mean it has to be our event and you can actually do this without editing the input but you still it will still like you could keep like min and max uh kind of what i was trying to go for if you keep the min and the max in variables then this would only have all one extra variables however because you still sort that means that you're still modifying the input so it's still going to be linear time if you are committed to not a linear space sorry if you're committed to not modifying the input um cool uh that's all i have for this problem hope this was interesting and hope you learned from my mistakes and my thought process as i go through them um let me know what you think and i will see you hopefully tomorrow bye
|
Smallest Range II
|
nth-magical-number
|
You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104`
| null |
Math,Binary Search
|
Hard
| null |
1,658 |
hey everyone today we are going to solve the ration minimum operations to reduce X to Zero so you are given integer array nums and integer X in one operation you can either remove the leftmost or the rightmost element from the array NS and subtract its value from X note that this modifies the arrays for future operations return the minimum number of operations to reduce X to exactly zero if it is possible otherwise return minus one so let's see the example so you are given 1 one 4 2 3 and X is five so if we take these two numbers from right side so X will be zero right so that's why in this case output is two and let's see the example two so 5 6 7 8 9 and the x is four so in this case um so all numbers um in input array is greater than x so it's impossible right so that's Yus one and then let's see the example 3 2 21 1 3 and X is 10 so if we take three two from left side and uh one three from right side so total is 10 right so that's why in this case output is five okay so let me explain with this example 3 2 21 13 and x = 10 with this example 3 2 21 13 and x = 10 with this example 3 2 21 13 and x = 10 so to solve this question um so we have two choice to take the number from like a left side or right side right but problem is so we don't know what numbers are coming next or next so it's tough to manage left and right numbers at the same time right so that's why we need to change our idea so here is my strategy so if uh so we have to like subtract some numbers from X and in other words so if we can calculate numbers which doesn't need for x and then subtract the unnecessary number from total number of input array so we can get X right so that formula is total number of input array so total equal in this case 30 right so total number minus unnecessary number is 10 so that means if we want to calculate the unnecessary number so the formula is total number minus X in this case 10 so in this case unnecessary number is 20 right so in the end so we take these two number from left side and these three numbers from right side and uh this 20 is unnecessary number um so we calculate a few minutes right so if we can find this unnecessary number um so all we have to do is just uh subtract total length of input array minus un length of unnecessary number so if we have five here so I think un length of unnecessary number should be two right but in this case total is like a 35 Z right so in this case 1 2 3 four five six so total length is six minus so length of unnecessary number is one right so one equal so five right so length of this five includes like a three two from left side and one three from right side so one two three four five looks good right so that is how we uh think about like a solution okay so let's iterate through one by one I think we can use a sliding window technique so initialize left pointer right pointer with index zero so now this T stands for um like a Target number not total so which means the unnecessary number so 20 right total number of input array 30 minus x 10 so unary number is 20 so be careful and the current Su is initialized with zero and then um max length of unnecessary numbers position so first of all minus infinity so in the end um so max length is still minus infinity so we should return minus one because we don't find like a um like a target number and then um n equal 6 that is a length of input array so let's begin so first of all um every time we move right pointer to next but now we initialized right poter we zero so add plus one to current SU and then every time we check these two condition so this is a loop I think we use y Loop and the current sum is greater than a Target unnecessary number um it's not right so let me explain later and uh if current sum equal unnecessary number Target it's false right so let me skip this and then move right pointer to next now we find a two so add two to current sum five and then check these two condition so current sum is greater than Target it's not so Skip and equal skip right so and then move next now we find a right uh not right uh 20 right so add 20 to current some not 25 and then check this two conditions so current sum is greater than Target yeah that is true right and Target sum is 20 so we go inside of the loop and the first of all um so now this 25 is between this range right and uh so now we so current sum is greater than Target so that's why left number in this case three will be like out of range right so that's why we subtract left number from current sum so in this case um 22 and then we add plus one to left pointer so now left pointer is here index one and then so this is a loop so um we continue until we meet this condition so now we check this range and 22 is greater than 20 right so we meet this condition so we did the same thing now left number is two so subtract two to from 22 so 20 and then out plus one to left pointer here and then we check again so 20 is greater than 20 so we don't meet this condition so we skip uh this y Loop and then we check um if current sum equal Target so 20 equal 20 right so in that case um we take a max length of these two so first of all current max length so minus infinity or left minus uh not left right minus left plus one so now left uh right is index two so 2 minus left is also two + 1 so 0 + 1 is minus left is also two + 1 so 0 + 1 is minus left is also two + 1 so 0 + 1 is one right so that's why um max length is now one and then finish and then again uh move next so right point is now pointing one so add plus one to current sum 21 and then I check current sum is greater than Target that's right in that case we subtract left number in this case 20 so current sum will be one and then add plus one to left pointer here and then if current sum 1 equal 20 we don't meet this condition right so we skip if statement and then move next right pointer is now pointing another one again so add plus one to current Su two and check this condition two is greater than 20 false right we Skip and 2 equal 20 it's false right so we Skip and then move next so now we find three add three to current s five so five greater than 20 false right and equal 5 equal 20 it's false right so we Skip and then we finish iteration right and then all we have to do is take max length and uh so now we have one right so that's why uh we successfully found the length of like unnecessary part in the input array so that is one so in the end all we have to do is total length of input array is six so 6 - 1 which is five in this so 6 - 1 which is five in this so 6 - 1 which is five in this case so this is a return value so if we take 32 from left side and uh one uh 3 one from right side so um we can create like a 10 right five and 10 right so yeah uh this looks good and the length of 32 and 1 13 is 1 two 3 four five so that's why we should return five and uh if as I told you if we still have minus infinity in the end and we should return minus one because we don't find a like a unnecessary part and then one more thing so this minus infinity is not equal to zero so be careful so what I'm trying to say is that so what if we have only three two one three so we don't have this 20 so in this case unnecessary number should be zero right total 10 and xal 10 so in this case zero right and then uh we start from left pointer right pointer from index zero so in that case um when every time we add each number to current s we meet a this condition right so that's why so if we meet this condition so left pointer always move plus one and I subtract left number from CS so that's why uh C is so current sum always zero and the left pointer is actually ahead of right pointer always so that's why uh so every time we meet a this condition because the current time always zero and the unne number is zero so and then um compare max length current max length and uh Left Right minus left plus one so as I told you left pointer is always ahead of right pointer so for example like a left right pointer is zero left pointer should be one so zero minus one + one is zero so always we get minus one + one is zero so always we get minus one + one is zero so always we get a zero as a Max strings so in that case in the end we get a zero here and so this zero is not equal to minus infinity so in the end uh we should return uh so in this case length should be 0 one two three four 0 one two three Z not Z 1 2 3 four five so five minus Z is five right so that's why we need to five operation yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all um Target is sum of input numbers minus X so this is unnecessary numbers and if Target is less than zero in that case we should return minus one and then initialize LIF pointer equal Z and the current sum equal Z and Max okay let's say Max sub length um equal Ro and uh minus infinity and N equal length of nums easy right and then let's start iteration so for so initi right here in range and end time and first of all current number to current sum plus equal nums and WR and as I explain earlier while current sum is greater than Target unnecessary number in that case um subtract current left number from current sum so minus equal nums and left and uh move left to next so plus equal one and if current sum equal Target so if we meet this Condition it's time to uh calculate the max length so max sub lengths equal Max and the current Max versus right minus left plus one and then after that so minus one is if Max sub length equal um Flo um minus infinity if not the case um so total length of input array n minus Max sub length yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of n so N is a length of input nums array so this is because there is a single Loop that iterates through the element of the array ones so that's why and uh space complexity is actually a one so because the code this code use the constant amount of additional memory regardless the size of the input nums array so space used for variables like a Target left current sum and Max sub length and M does not depends on the size of input array and remains constant so that's why yeah 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
|
Minimum Operations to Reduce X to Zero
|
minimum-swaps-to-arrange-a-binary-grid
|
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations.
Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`.
**Example 1:**
**Input:** nums = \[1,1,4,2,3\], x = 5
**Output:** 2
**Explanation:** The optimal solution is to remove the last two elements to reduce x to zero.
**Example 2:**
**Input:** nums = \[5,6,7,8,9\], x = 4
**Output:** -1
**Example 3:**
**Input:** nums = \[3,2,20,1,1,3\], x = 10
**Output:** 5
**Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
* `1 <= x <= 109`
|
For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps.
|
Array,Greedy,Matrix
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.