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 |
---|---|---|---|---|---|---|---|---|
485 |
See, in this video we are going to question the lead code for 885 Maximum Consecutive One. In this question, there will be a binary are given, it is ok that means zero and one will be there only and what do we have to do, maximum consecutive words are coming out as if here is Consecutive. There are two vans here and how much is there are three, so what will be the max of both of them, if three comes, then what will be the answer, our 3 will be very good, there is no problem, now see if I look carefully, what is this? What is happening here is all hells are coming, okay what is this, all hell is this, that is, whatever answer comes, it will be all hell, even if it is only one van, even if the answer comes, it is ours. But if it happens, Sabri is fine, see what it means, whenever you pay attention, after this video, whenever any question comes, then you should see once, can those questions be asked through the sliding window, okay here. Now let me tell you which sliding window will solve this question easily, there is no problem, now see what happens in the sliding window, let me assume at this time, the sliding window keeps on sliding, it is on the side, see, let me now. The window which is there only has a van in it, then made 1 for the second time. Now see, the van that came in the first time is our answer obviously because it is still the answer man. Take the answer man, I do n't have anything. Answer, I am fine, I am seeing this for the first time. Okay, the loop has run, I saw this for the first time, so this is the van, which is the van, it has been A once, what does it mean, your answer is now the van, okay, then the sliding window has become so much, okay how many A are there now? There are two vans i.e. the how many A are there now? There are two vans i.e. the how many A are there now? There are two vans i.e. the previous one which was van and the one which is now, which one is the maximum among them, what is the meaning of this, now my answer is 28, okay, now the sliding window will be this, now see what is there here. The condition is not met, here it is zero, okay, as soon as the condition is not met, okay, then we come back from behind, that is, we will cut it from our window, we cut it from our window, now look again, what is my condition? The match is happening one by one continuously, does it mean that it is not happening? Cut this also out. Okay, now I have seen again. Now see if my condition is matching, it is not happening, that is, cut off this also from your answer, that is. Is it ok through the window, the answer is, you will still be mine, ok, now my window is finished, ok, now look, I have come here, I am ok, the window is no longer there, ok, what is the answer, its number is WAN, but What was the answer in the last time? If you came then what is the answer now? So this is very good. Let's go ahead. The window has moved ahead. Okay, very good. Now the window has moved forward. Now what answer will you get from this one? What is the answer from this previous one? You had come, it means you will still be there because we are leaving max obviously ok right, now increase the maximum number of consecutive vans, now increase the sliding window, now from here it will become three answers, earlier it was two, this means what answer is 3 A? Now look carefully suniyega, I told you the way to do any question from the sliding window. Any question, what to do, this will be the photo, okay take a screenshot of it, this will be the photo, there will be a pointer in every sliding window, there will be a pointer on the left. It will be right, okay, what do we have to do, we have to hold the right hand and keep hitting it in our answer. I have put a loop one at a time, neither will it hit in the first time, it will also hit in the second time, both will be done, okay, ok. So we will keep wandering through the windows one by one, but here I have put a condition here. If anything comes that does not match the condition, then we destroy the sliding window from behind, destroy it from behind, remove the same logic from left. Window and left plus, that is, whatever pointer will be there, we will keep increasing it, okay, and update the answer, whatever I was doing to Sam, he will do it here, okay, it has not come to my mind yet, there is no problem, there will be a voice, I said to everyone. First what has to be done is to increase the sliding window. Now look, in place of Sam, I will do the window itself, this is my window for you, what is the slamming in the window one by one, the right has to deviate, the number of right is equal, no, okay, good and then Finally what to do, the answer is mine, the answer is ok, I have just added the mines, the answer has to be updated, what will be the answer in this case, the max will be Math Dot Math Answer and I will write something here. Ok and will return finally, what answer is ok, now look carefully at what I am doing in the window, I am adding one by one, ok, but if I take it, this window is mine right now, then what will I do, it destroys it from behind, right? We will be destroying from behind i.e. right? We will be destroying from behind i.e. right? We will be destroying from behind i.e. what will I put here, I will put a loop till what I told, till our condition is unsatisfied, I am saying again, there will always be this photo in every sliding window, in the file condition. What will we take, as long as any of our conditions are unsatisfied, keep destroying, okay, unconditionally satisfied, we will write here, there is no problem, what should I write inside, what to do with the sliding window, we have to destroy the left side i.e. window destroy the left side i.e. window destroy the left side i.e. window minus equal tu. The vein of left is fine, it has been mined, look at the window, what is our window, basically the time can be anything, what is our current product can also be, anything can be good and keep doing left plus, point A is there because it is fine. Very good, now what is this condition, isn't this the condition, this is just a matter of mind, what is the condition here, okay, what is the condition for us is that brother, see what should always come, should always remain kanjivative, van, now how in that condition. Now let me write, see if this is a sliding window then what should I write, what is the sam, you will come ok and what is the length also, you are here, understand the condition, what is there here, the sam of the window is three and what is the length, it is also three, but if you look here Look at this here, if this is a window, somehow we also take it as if this window is a, well then see how much is the sam of the window, but what is the length here, it is three, what does it mean, we have got the condition which is Right - Left Plus Van What will which is Right - Left Plus Van What will which is Right - Left Plus Van What will happen with this will increase the length of the window, this is not equal, you do that is, as long as this is, what is this, what is the meaning of this, brother, the condition is not satisfied, ours is fine, there is no problem. No problem, as long as the condition is not satisfied, then destroy from the left. Keep coming. Okay, that's all. Okay, great. Now I am updating the answer, but what answer should I write here? I am updating it here. What should I write, look, Max will always come in answer, that's why I have written, give the answer, math answer and current answer, how will the answer of current window come, this is what is written, see, in this case this is the answer of current window. That is, the length of its window, if I take it as just the window, then right, left, plus van or Sam is the current, now look here, I could have also written Sam, brother Sam, take out the Sam of these three, take out the Sam of these two. Sam, take it out, it is written but my mind is very sharp, okay, intelligent, we can see because look, van is van, what does it mean, brother, this is equal to the length, it was also 111 symmetry rank of the window and We know that till here we always have to satisfy the condition, because here we have destroyed from left until the condition is satisfied, okay, let's run it and see, this has to be done by Windows, sorry, accept it, let's see by submitting. Everything is done now, brother, now let's check the time complexity once, brother, what is it looking like, look at it, one loop is fine, one loop is done, this is another two loops, what does it look like, n² has come but big off other time. Let me tell you why there is complexity, so here I have written the story for you. D time complexity is big and because of D inner loop i.e. which D inner loop i.e. which D inner loop i.e. which is Wiley's loop which only executes on a constant number of times. Outer loop i.e. look on a constant number of times. Outer loop i.e. look on a constant number of times. Outer loop i.e. look when n² happens. When will it be N square when for every outsider the complete inside look will be visible, but if I look here, for every outsider this constant is going on outside, which is the left pointer, just don't look at anything else. You look at the right point and the left point, the one on the right is iterating only once, from zero to n, it is understandable, there is no problem and that means its length is fine but the one which is not in the office is the left one. And if I look at it, then see the left side is always swinging from zero to the end. Look carefully, the left side is never resetting. What does this mean, brother? This means that the one who is on the right point is also net. The end bar is increasing and the left pointer is also increasing. It means pick off and time complexity, not big off and square. Okay brother, that's all for today, the video is over. You will get the link of the next video here, the card on the screen. I must have been there, I will meet you there.
|
Max Consecutive Ones
|
max-consecutive-ones
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
|
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
|
Array
|
Easy
|
487,1046,1542,1999
|
1,658 |
hello everyone welcome to day 14th of january let go challenge and today's question is minimum operations to reduce x to zero in this question you are given an input array and an integer x uh you can perform multiple operations in the array and in each operation you can either pick an element from the right hand or the left hand and you need to tell by performing multiple operations on the input array whether you are able to generate a total sum that is equivalent to the number x here they twisted it to subtracting that number i'll i'm saying that uh with the total sum by doing multiple operations if you can get uh the sum equal to x that means uh there is an there is a possibility and you need to return in the minimum such operation that you need to do in order to get that number x so let's look at one of the examples here so uh 1 4 two three and x is given to us as five what you can do you can pull out the last two elements three and two from the uh input array and the total sum is five is equal to five and the minimum operations that you do is 2. how did you do it out of 3 and you had first at first you had an option to pick up 3 or 1 you chose 3 and once 3 is gone you had an option to pick one and two again you chose two so you got five in this example uh it's not possible to attain a sum of four hence uh you return minus one also it is given to us that all the numbers are positive in nature there are no negative numbers input let's look at the algorithm that i have created i will be sharing multiple algorithms for this approach and let's walk through it let's take a pen so i have taken the similar exactly same example that was specified in the question uh double one four two three and the target is five and the first at the first open at the first operation you have two options either to choose one or three it's up to you what to choose so if we chose if you choose one what is the remaining array one four two three and if we choose three what is the remaining array one four two uh out of these two possibilities let's walk through these four two possibilities and number of operations that we have performed is one so we have performed the first operation and let's try all the possibilities out this is the first possible this if we let's walk through this part we chose one first and now we have uh two either one or three so if we choose one we get the total sum as two and the remaining add is four to three if we choose three uh the total sum is four the remaining array is one four two if we choose so if we choose three then we have two possibilities for the two possibilities one or two let's assume we have taken one the total sum becomes uh two the total from becomes four as specified here and the remaining is one four two uh if we choose two then the total sum becomes five as specified here the remaining r is one four we also observed that the target becomes equal to the total sum and at that point that is the point of our answer and the number of operations that we have performed we first was 3 and then we chose 2 so the number of operations is 2. does this remind you of some graft reversal that we have done in the past yes it does that is we can go for the bfs reversal approach and the level will give you the answer what's the issue with this approach the issue is it's too time consuming we don't want to go in uh in the bfs way because the time complexity would be higher let's think of something smarter than this so let's reiterate what was specified in the question uh you are given an input array and you can you need to select one as a right part one as your left part one as the right part one is your left part to find the target a total target sum or the sum of the left part plus the right part should be equal to the target how can you redefine this question you can redefine this question by saying that you need to find the longest consecutive array with sum equal to so if the total t is a total sum and uh the target sum is given by left plus right equals to target let's hypothetically take one case where this rj plus this array gives you the target what you need to identify in the input array you need to identify the longest consecutive array with sum equals to total minus target so this the longest consecutive array in your input will give you the minimum length of l plus r array and hence that would be your answer if you are able to identify the longest consecutive array with sum equals to total minus target uh you can subtract uh that length from the input array and that will give you the answer because that will be the maximum length of the array and total length minus max length will give you the minimum length of l plus r that is your answer that are the number of operation that is needed so how can you solve this we will use the prefix sum approach using uh with the help of a map what does the prefix sum approach says you calculate the prefix sum of the input array and at any point if you so let's assume there are multiple numbers here and how does the prefix sum approach works so this at this point you store the sum of uh total sum of elements up to this point and similarly at others total sum of elements until this point and if in the input array uh the subtracting prefix sum at this in index j versus that of i if prefix sum of j minus prefix sum of i gives you the target your intended target that is one of the possible candidate for their maximum conjugative array so what i'm trying to say is something like this so this is your one prefix sum some till here that the sum would be till here and if this value minus this value which is the sum of these many elements is equal to your target that is your answer we will be using it with the help of a match map which will help us reduce uh the complexity here the complexity would be order of n square we will reduce it to order of n using a map so let's take an example the same example that was specified in the question and the target that we are interested is in phi is five how can we solve this we'll use a prefix sum approach as i was telling you using a map so let's calculate the total sum is one plus one two plus four is six plus two is eight plus three is eleven and what are what is our new sum that we are searching for totals of minus target t s minus t which is eleven minus six minus five that is six so we are interested in searching the longest consecutive array with sum six so our new target t dash becomes six let's create a map and map in the map there will be one key and one value the key will be the prefix sum the sum in the array so far and value will be the index at which it occurs so i is states the index at which it occurs uh by default let's fill in the map with zero so map contains zero because it doesn't have any elements and the zero sum is at minus one index so let's start the operation you got one and since one is not there in your one is missing from the map and one minus target sum one minus six is minus five minus y is absent from a map uh you don't need to do anything it's not a potential candidate you move ahead and you add one to it at zeroth index so you got map in the map one entry gets added one comma zero that means one prefix sum occurs at zeroth index now you get the next element move on to the next element the prefix sum becomes 2 minus 6 is not there 2 minus 6 is minus 4 is not there move ahead and add 2 to it to come to occur that first index two if we fix the marker that first index and then you move ahead in the iteration uh the prefix sum becomes six prefix and becomes six and six minus six which is zero is present in the map so you found your first possibility of where the sum of the consecutive sub array is equal to 6 what is the index so that index is minus 1 so this index was 0 1 2 3 4 so this was occurring at 2 so 2 minus 1 so what is the length of the sub array it is equal to 2 minus 1 equals to 3 so the length of the sub array is 3 you move ahead with the iteration and also you add 4 6 comma 2 to your input to your map and then you have 8 minus a 6 that is 2 is also present in the map so what you'll pull out this index so 3 minus 1 equals to 2 this is your other candidate where the sum is six then you move ahead with the iteration you add eight comma three don't forget to add and you have now you have eleven as your sum eleven minus six is five is not there in the map you simply add one comma eleven comma four in your input array so the you observe that you got two possibilities where the total sum was uh total sub rsum was equal to six uh one possible length was three the other possible length was two so one possible length was this the other possible length was this and you need to find the maximum out of it maximum is three the maximum length is three you have the maximum value which is three uh what would be the answer total length minus the maximum length which is two so five minus two 5 minus 3 is 2. let's quickly code this up in exactly what we have stated in exactly the same steps let's find the total sum because we need to update our target uh search element to be searched total sum equals to zero for integer el over nums total sum equal plus equals to el and the new target equals to total sum minus x good so far we are good now let's define the map new hash map output what we need to put the base case 0 is occurring at minus one index and let's define the max length uh sub array or initialize to minus one let's iterate through the loop just create another variable for the prefix sum part integer prefix sum equals to zero prefix sum plus equals two numbers of i let's update the prefix sum that we found this prefix sum at this index in the map prefix sum at this index and let's check whether our target some prefix or minus target some exist in the map or not contains key prefix sum minus target if it is there let's calculate the length of that sub array we found a potential sub array where the top whose sum is equal to the target integer current length equals to i minus map dot get prefix sum minus target and max length sub array so this is also current length sub array equals to maths dot max length sub array and current line sub array the maximum value of this will give us the maximum length of array with the target with the sum equal to target and once we have this information what we are going to do map dot if max length of array is equal to -1 we return max lens is equal to -1 we return max lens is equal to -1 we return max lens of array otherwise we return nums dot length minus match length sub l because we are actually interested in finding the remaining part of it not the maximum length sub somebody because we have updated the target element and once we are done with this let's try this up compilation error oops again a typo looks good accept it let's talk about the time complexity of suppose the time complexity of this approach is order of n because we are iterating through nums uh but linearly uh twice once for calculating the total sum and the time iterating over the prefix sum so 2 times log n oh that doesn't make any difference it's still order of n linear time and the space complexity is equal to a number of elements that would be there in the map or that would be equal to order of n again because the prefix sum at every point you may get a new brief new and a fresh number and you have to put it in the map thanks for watching the video hope you enjoyed it
|
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 |
1,404 |
let's see code number okay i haven't done this number of steps to reduce a number in binary representation to one given a binary representation of an integer as a string s but turn the number of steps to reduce it to 1 under the following rows it's guaranteed that you can always reach one for test cases we just have to keep following these rules until it is done how big can the number get so s dot length is up to 500 so i can't fit that with an integer that's the main problem not because it'll take too long so i have to figure out how it works in binary instead adding one is simple enough and checking if it's odd is also simple you just have to check if the right most digit is a zero or one if it's a zero it's even if it's a one it's odd when i divide by two let's say i have value eight this is eight and divided by two i get four and four is this and that's two this is four what if i have ten and i divide by two to get five so you get four and one kinda looks like it just shifts across by one yeah that actually makes sense when i move a digit one to the left i'm doubling it if i'm moving it down i'm dividing it by two you know what i could do i could have a dq that can check whether what the last character is and also pop from the front and the back in constant time and when i want to divide by two i remove a zero from the right end and add a zero to the left end but then i also need an operation that checks whether the current number is a one you have five hundred zeros and ones it will take around um log n time to actually figure out how many steps but to check whether it's a one every single time oh wait a second whenever i'm dividing by two i'm guaranteed that the leftmost digit becomes a zero so i can actually just ignore that like so now i know that this is odd because the rightmost digit is one and then i could add one to that which will give me one zero actually the operation of adding one can actually take up to o of n so actually don't need to dq so i can because i am never going to add to the left end anyways or am i will there ever be a case where i have full ones and i add a one actually there will be like in the very first case if it's all ones and i add a one to make it even this will become one zero so let's make a function that divides the binary string by two it's a void function that takes in a vector called s and all i actually need to do is to do s dot pop back now i need a function that add one let's just call it add no add one what do i do with add one oh yes we wanted to use it dq right so if i find the first zero closest to the right end so i wanna increment from i equal to s dot size minus one i greater than equal to zero minus i in fact i probably want to keep track of what i is so let's do size minus one here if s i is equal to a zero then right if i is greater than equal to zero i want to actually just change what s of i is to be equal to one without added one else i need to do s dot push front i think that's the thing push front one let's also make another function called uh is one we just return um s dot size equal to one cool and then we just need to have a while width for true and um before i do that let's put everything in a dq i wonder if i can just do this stop begin s dot end if is one d break so i want the answer to start off at zero steps and then if it's a one a break and then i return the answer i'll handle the case where it's just uh a one passed in it's also how to have a function is odd so return s dot back is equal to a one if is odd um add one else it's even so half it um this should return a boolean as well oh wait a second i just realized that my dq is not shouldn't be an entertains should be chars no i don't think that makes a difference it just um uses less space oh wow oh i think um my logic for adding a 1 didn't work because when i add a one this becomes zero and add one little thing else s of i is equal to zero oh this should be a equals zero and i forgot to actually plus the answer good thing about this example is i could just do something random and it'll probably work cool let's submit that um nice what's the time complexity of this function add one could take up to 500. these operations the number of steps is order of login cool thanks for watching like and subscribe and keep reading the code i'll see you in the next one
|
Number of Steps to Reduce a Number in Binary Representation to One
|
print-immutable-linked-list-in-reverse
|
Given the binary representation of an integer as a string `s`, return _the number of steps to reduce it to_ `1` _under the following rules_:
* If the current number is even, you have to divide it by `2`.
* If the current number is odd, you have to add `1` to it.
It is guaranteed that you can always reach one for all test cases.
**Example 1:**
**Input:** s = "1101 "
**Output:** 6
**Explanation:** "1101 " corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.
**Example 2:**
**Input:** s = "10 "
**Output:** 1
**Explanation:** "10 " corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.
**Example 3:**
**Input:** s = "1 "
**Output:** 0
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of characters '0' or '1'
* `s[0] == '1'`
| null |
Linked List,Two Pointers,Stack,Recursion
|
Medium
| null |
99 |
That guys welcome back to my channel like this video we are going to two year recovery bent tree so this gives statement here you are giving any road office binary search tree bst valid values of exactly two notes of values of exactly two notes of values of exactly two notes of fifteen years went by mistake recovery without changing its structure In the switch problem, a binary search tree has given a fruit look and two notes are exactly what has been done in Benefic or what we have to do is to swap those notes back so that we get back to this - this trick becomes okay with back to this - this trick becomes okay with back to this - this trick becomes okay with this thing Also keep in mind that the structure of the tree should not change. Okay, so in the first example, you see that the real factory on the right side of this note is more than its value, so we should know that the structure of the binary search tree. Left Side Tree: The value of the left leg of any road is Left Side Tree: The value of the left leg of any road is Left Side Tree: The value of the left leg of any road is less than that of the note and the value of its light saber is always greater than that of the note, but in this condition we are seeing that its Left Patience, its value goes to it. Mills Pet has started somewhere by mistake, so what do we have to do, we have to sign both of them, from there we have to do 19 web so that we do not boil the property of binary search. There should also be helicopter back. If you look at it and then clean it, what is its loop, everything is fine, what is the value, it is less than this, it is at least, so here we will serve 341, then it will become one, again, one, it will become one, again, you are seeing in the second example. That its light magazine value is more but why is it less that it should not have been there? Then what should we do? We will clean both of them. What will happen to us after this? Binary search tree will be created then how to solve this problem. Let's see what we will do here, we will solve this problem by using inorder traversal. Okay, what we will do here, first of all we have to wait for both DJ Amit, for that we will take two Redmi notes. Here were the first and second. What will we do, what will we do in two land redmi notes, two notes ho galu, we will keep two notes, we will see which one and always type, by pointing to both those nodes from, we will keep them back in both the parties. What should we do, switch off both those modes. Will do will select the phasance account our will it will become a binary search tree again and put another domino in here we will do the previous okay this will be our cycle sugar will track which one we can take the first problems can take note which is It is clear from the mistake, okay, so how will you solve this problem? Let's see what we will do here - We will what we will do here - We will what we will do here - We will use inorder traversal in history. Okay, we will use question. What will we do? Let's start with this note. So how many will go for this, then what will we do with the left, we will go to this fort, Fennel will come back to the traveler, then look at the three, we will get the value addition momentum from this, okay, the initial I will be its value Panchami, okay, this will compare it. What is the value of the entry, is it more than the root but not more, here it is less, so simply what will you do, you will remember the ancestral value again, you will make its equal which cannot not difficult, then we will move ahead, its left side is done. It will go to its right side, then to its right, but it will go to the right, tap it will come back to two, then it will check what is the value of its surroundings, is it more than the value of the scanned note, yes, it is more, what did you do in that condition first? You will sign the equal value of the environment three layer end and the control which is in the second will be velor two and together what will we do please update on the previous update we will not only make the cancer dry then opened the camera it We will find the left, we will get clues, we will find the right, love will come back, Bittu, the administration has finally gone back for free, the guest professor has already gone to the forest, whereas Kavya, we will check whether his personality is more or less than the value. The arrangement is more dot means what do we have to do then firstly if you have signed once then you will not change it back then you will have to change again and again we will do the second one ok so here this condition is felt which can What is the value of the note, is it less, then what will you do, update the account with the value of that note, make it one, do it here and this and Pinku will keep updating this note that we will go to that note just before now. After checking, we will do it, then finally this process is done, if we get its rights then there is a tap to get back to life, finally we have got Bigg Boss, so finally we have got 341, right? If we got 341, then side with these two. As soon as we do it, our team will be formed again, it's okay, let's see what we will do here, first take and second take, okay and previous take reverse mark, what is the volume and intermediate, what will we do, will we roll the sleeves, Mr. Kailash Then we will go to its last, what is Light, its tap is back to Rahul, to the mind, then compare with the value of Vansh that you are not much add on the whisker Gilu which is one, then sign 163 and proceed further, then here. That you will go to the right side or not, it will go back. 1 has been processed, then it will come to K, then compare, this is the value of the previous one, this is what is more than the value of Sainik Pile, what is the value of Cantt note, it is more than the small note, it is not, it is simply You update it and move ahead, it will go to the night, then it will go to the last. Please, it will go to the last. There is a tap, back to the introduced. What is its value, what is the hour value of the note, is the balance of the speed more than the apk file? Yes, there are three and this is the intention of two happy people, what will you do now in that condition, there is nothing stuck in the first one, there is nothing already, so P which is the front, then update this before that and update the second one with the note. Kittu has done it, updated it, okay then finally what should we do, after considering the reverse, you will do it in Connaught, please do it right, I would like to know that it has been found, that the tap is near the back, the cream has slept at the store for it, near the piece compare. Will the victim know that it is not simply update you and go ahead in the diet you will go to the tap is back to this because file appointment and you have got both of these so what should we do neither to free mode I will switch off this, what will be the problem, will it be successful, okay, so what we had to do here, we had to consider a previous one, take one crop, add another 1 second, okay, the previous notification was on the volume line, then what do we do? We were doing these horror traversals in everyone's left, first we will see, okay, then what will we do, still value it, compare it with where we are on this note or if it is more than that, if they value it, if the value of entry is controlled If it is more than the first, then do the first day in that condition. Is the first something already taken, is it not busy with the purse, then from the entry in the year, you will now sign the proposal and assign it and what will you do in the second or its * You will what will you do in the second or its * You will what will you do in the second or its * You will send it before wherever you are. Once you have signed off, there will be no need to change fonts again and again. Barbara, if you have to change anything whenever you are, what will happen to you is that the value of the environment will be more than that of the note. So in that condition Ab Dekh people's house Preet First which is mine already has something then you will not do anything in it but second will only change it with the bills of that point, okay this is our approach here so let's see how to code it. What will we do? We will take 23 more rooms. Okay, what will we do here? We will get the free mode. Start the previous one. Andhra took the second place. Then what will we do. Come here, this border has not been cleared. We will create it. What will we do? Here the value of prevent, what will we do initially, we will invest in tree in hotstar, okay, we have started, then we will call the inverter, now you will call the inverter, what will happen with this, will you get it and the value of the skin, you will get stranded Kanodia. Here what we will do is we will set both the value of the first, we have to do the value of I, the value of the first which will be given, this will be the value of the second which will be given, do it accordingly, return I of this will become so in odd and here we see n. How to work this white in order hands free that Note 4 fruit is ok then what will you do what are you not upset about next question is here ok then what will we do here in order toe rules left side left ok then What will we do with the gas flame? We will check it. First step is the law. I don't know anything. The value of the underground will be the bill of the front. The value of the investment will be the karma. So what will you do in that condition. Here first. I will sign, what will you do after entering, then what will you do, you will check here that if the first avenger is already there, what is the value of the end route, what is your value, if the arrangement of these Kannauj is less than the value of entry, then what will you do in that condition. You will update the second. Second is equal to two. This is fine on your route. This is done. What you have to do is to keep updating the environment from the cant to the route. Then what will we do with these more routes. Our addition towards this site is now ready. What do they do now? They take us down, the loot has been looted, they submit it to the court, it has been submitted, thank you.
|
Recover Binary Search Tree
|
recover-binary-search-tree
|
You are given the `root` of a binary search tree (BST), where the values of **exactly** two nodes of the tree were swapped by mistake. _Recover the tree without changing its structure_.
**Example 1:**
**Input:** root = \[1,3,null,null,2\]
**Output:** \[3,1,null,null,2\]
**Explanation:** 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
**Example 2:**
**Input:** root = \[3,1,4,null,null,2\]
**Output:** \[2,1,4,null,null,3\]
**Explanation:** 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
**Constraints:**
* The number of nodes in the tree is in the range `[2, 1000]`.
* `-231 <= Node.val <= 231 - 1`
**Follow up:** A solution using `O(n)` space is pretty straight-forward. Could you devise a constant `O(1)` space solution?
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
| null |
641 |
hello everyone today we are going to solve this problem called design circular deck ok so if you are familiar with so I'm going to use Python 3 to solve this problem and if you are quite familiar with Python 3 you might know there's a module called collections and in this module there is a class called building class codec okay so and I really like this kind of problem because you know sometimes we will just use the collections the class the building built in class to solve some kind of other problems but this kind of problem really give you an opportunity to learn how to really implement it by yourself so I really like this kind of problem ok and so ok in this in a description the descriptions says that you have to decide this deck and deck is also known as double-ended queue so you are going as double-ended queue so you are going as double-ended queue so you are going you have to implement a constructor set the size of the queue to be K and there are these methods you have to implement so first one is to insert an item at the front of deck and that the second one is to insert an item at the rear of the deck and there's a function call TV from you have to delete the item at the front of the deck and delete last I delete the ID from the rear of the deck and get the first and gets wrong is to get the wrong item and get rear is to get the last item and it's empty and this fall is just to check whether the deck is empty or full so and there is a note here and but I think the real really important thing here is to is this the last one so please do not use the building deck library so it remakes sense because the goal of this problem is to ask you to implement it and you use a built in deck laboratory implemented it's quite stupid to do that okay so first we have to we will start from the constructor so here I will create a Tech Talks data structure at least and this because we already know this the size of the list so we were to find of this like this and we also create another instance variable called max size and the max size is to store the size of the deck which is K and okay and we also need a variable called size and this is going to track the current size of the deck okay so after that where I was usually I would start from this I will start from the easiest one or I think that it will be needed to be implemented first so it's empty is quite easy so you just need to check if the current size of the deck is equal to zero and for the method is full it's quite similar with similar to it's empty you have to you just have to check if the current size is equal to the mass size okay so if the current size is equal to max' eyes then that means the equal to max' eyes then that means the equal to max' eyes then that means the deck is full and okay so now we are going to implement insert front so for insert front one thing you have to like pay attention to is to before you want to insert something no matter you want to insert at the front or the rear you have to check if their deck is now full right if the tag is full then you can't insert anything else into the deck okay so we want to check if if the tag is not full then okay so now there's another problem we don't know where is the front of the attack and we don't know where is the end of the deck so we might need to define other variable and in this case we need a head pointer and a tail pointer and both of them are start starting from zero in that's zero so here we go back to the matter in the front and so now we can actually implement it so because it is circular deck so we may have to do this so when you insert an item at the front of the deck the pointer should go to the left of the deck right so with the pointer to minus one and because it's circular so we have two mode self max sighs all right and then when we when the pointer is pointing at the right position we can actually assign the value to the position okay so do this and because we insert a new element into a deck so the size shoes size of the actual US 1 and when we finish and return true and if it's not is full the dag is for at a moment then we have to return false right so that means we can insert anything else into the attack but there is a tricky thing here because there is a case that now we might encounter something like this so for example if we have the size of the tag now is 4 and we are just starting to inserting new element into this empty deck then in this case had a point ahead until are pointing to the first Edmund okay and if this is the case then if we do what we just done here we will mix the first element right because here we say is that ok but if we recheck the daga is not fall then we first we would we will move the head pointer to the previous one which is the last one in this case alright and we insert the valve here okay but you can see that this will break the whole thing because if now we are going to insert another element at the tail then we will insert the tail we will do this the same thing here right like we will move the pointer to the next one and we insert another there here and in this case there will be a empty element between head until so to prevent this situation we have to check another condition which is if the deck is empty so if the now the deck is empty then we will just we don't have to move the pointer before we assign a value right we just assign a value to the current position so we just do this first we just assign the value to the current position and the same thing because we insert a new element in attack so the size plus 1 and return true ok so here we have to change to elves elf okay so this is the insert front okay so now we are going to insert last so you might so the process might you might be able to imagine that it's quite similar right so if self is empty and self Dec value and sell the size plus one and return true and L if now self is full so head oh no self tail okay so tell so when you insert a new element at the other rear of Dec the tail pointer should move to the right of the deck so plus 1 and again mold max size and self Dec cell until assigned value and cell size plus 1 and return true helps return false okay now we are going to implement the method delete front okay so just like the case we are inserting the new element when you want to delete some something from the deck the first thing you have to check is to check if the tag is not empty right if it is empty then there is it makes no sense to delete anything from the deck okay so first thing we have to check is not empty okay so it's not empty and we are because we are implement delete from so we delete the element at the head pointer itself okay so just like insert those these two inserts methods we in this in delete method we are we also need to check if it is if the size if the deck size is equals is equal to one or not okay so if it is not equal to one and self had if it is not equal to one so it's not equal to one we have to move the pointer and because it is a circular deck so modis self dot makes eyes and after that we have to - one size have to the size we have to - one size have to the size we have to - one size have to the size as 2 minus 1 so here if that's if the size if not is not equal to 1 then we have to move the pointer so that means if the size is equal to 1 we don't have to move the pointer so you can think about it just like what I said before so if the size if the text size is equal to 1 that means and now the head pointer and the tail pointer are pointing to the same element so in this case you just have to remove the element but you don't have to move the pointer right ok and for delete vast is it's quite the same as delete front so if not self dot empty and self Dec self dot cell equals to none and also we have to check if the size is not equal to 1 if it is not equal to 1 then we have to move the pointer so minus 1 and mold self dot next size and also we have to do size minus 1 and return true okay and else return false okay and get from so now we are going to implement get from and get here so we just have to return the value which is appointed by the head pointer but one thing we have to check is that we have to make sure the deck is not empty so if it is empty then we just return minus one and same thing get rear just return self okay so I make a mistake here so it's actually Dec now Q and also here we return the admin pointed by tail pointer and we have to check if it is not the deck is now empty or we have to return minus one okay so now we try to run the code and what okay so here you know it's I we have to forgot the indentation run a code again okay try to submit it oh my god what's wrong okay so maybe I have done some things dude it here okay so let me check here's as true false true none okay so maybe we insert cat from is empty TD from user carrier get here okay so yeah this should be only one equal sign okay so wrong again there's some meat okay so yeah okay thanks for watching
|
Design Circular Deque
|
design-circular-deque
|
Design your implementation of the circular double-ended queue (deque).
Implement the `MyCircularDeque` class:
* `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`.
* `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwise.
* `boolean insertLast()` Adds an item at the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise.
* `boolean deleteFront()` Deletes an item from the front of Deque. Returns `true` if the operation is successful, or `false` otherwise.
* `boolean deleteLast()` Deletes an item from the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise.
* `int getFront()` Returns the front item from the Deque. Returns `-1` if the deque is empty.
* `int getRear()` Returns the last item from Deque. Returns `-1` if the deque is empty.
* `boolean isEmpty()` Returns `true` if the deque is empty, or `false` otherwise.
* `boolean isFull()` Returns `true` if the deque is full, or `false` otherwise.
**Example 1:**
**Input**
\[ "MyCircularDeque ", "insertLast ", "insertLast ", "insertFront ", "insertFront ", "getRear ", "isFull ", "deleteLast ", "insertFront ", "getFront "\]
\[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\]
**Output**
\[null, true, true, true, false, 2, true, true, true, 4\]
**Explanation**
MyCircularDeque myCircularDeque = new MyCircularDeque(3);
myCircularDeque.insertLast(1); // return True
myCircularDeque.insertLast(2); // return True
myCircularDeque.insertFront(3); // return True
myCircularDeque.insertFront(4); // return False, the queue is full.
myCircularDeque.getRear(); // return 2
myCircularDeque.isFull(); // return True
myCircularDeque.deleteLast(); // return True
myCircularDeque.insertFront(4); // return True
myCircularDeque.getFront(); // return 4
**Constraints:**
* `1 <= k <= 1000`
* `0 <= value <= 1000`
* At most `2000` calls will be made to `insertFront`, `insertLast`, `deleteFront`, `deleteLast`, `getFront`, `getRear`, `isEmpty`, `isFull`.
| null | null |
Medium
| null |
165 |
hey everyone it is site hope you are doing well so let's start with the question so the question is compare version number okay so you have given two version one and version two you have to compare them okay and version num consists of one or more version joining by a dot okay and you have to compare the version comparing the revision is from like left to right you have to compare so if it is one point zero point one and another is one point zero point two so you have to compare from left to right and you have to return whether if version one is less than version two you have to written minus one that means version two is greater if version one is greater than you have to written one otherwise if it both are equal then you have to return zero okay so let's see with an example okay so let's see with few example so first of all like version how version is represented it is basically you can say major like whenever you deploy your version you are giving the version name as like this version miner then a patch like there is some error then you give the patch version of that okay so let's take example like one point zero point one or one point zero point one oh it should be zero one okay so as you can see we have let's take this as an example okay one point zero one and another is 1.001 and another is 1.001 and another is 1.001 okay so we need to compare the version and how we can compare is we need to compare it before dot like if we divide this remove this dot we have two entities one is this and this major version then this is minor version similarly if you can see we have this okay so we need to compare okay so we will compare this to this so these both are same so we can't identify which is bigger okay now let's compare this okay so if any version or if any like this is minor is consider any like taking any leading zero okay it should be eliminate okay so after eliminating the zero it will become something like this and this will also become this so if we compare both the both are same so this will give the result as zero so that's why we have an output of zero okay let's take one more example as two point zero four point one okay let's take two point zero four point zero now let's first convert this so we will compare this these both are same we'll move further we'll now compare this so we removed leading zero after removing lead zero this will become four and this will also become four so this both are same now when you see this is one and this is 0 2 so after removing the leading 0 it will become 2 okay so now as you can see 1 is greater than 2 so that means version 2 is greater than 1 so we written minus 1 here okay let's take this example point one and one point one okay so if we compare this and this so you can easily see like one is bigger so we just written minus one here from here like we'll not go in the right side because this is bigger okay so let's see how we can approach this okay so we got the approach how basically we will approach the question like we'll compare every this but how can we split on the basis of dot like this is a string so how can we split it okay so what we can use is we can use a regular expression okay and what we will do we will like in the string we have a function of like in all the language we have a function of split or splitting it with regular expression and we can mention like uh split this on the basis of dot okay now you will ask me why i used to backslash so in this basically two backsplash i use because java compiler will convert this to backslash into one uh backslash and this will dot so it will just uh evaluate like this like you have you can consider any character before this after dot you have to split okay so that's why we have taken two backsplash so what we will do we will split this and it will give the output as uh you can say a string array okay so if we split this after split your v1 will become a array and it will be like this one and this will be a point uh you can say let's say in a string format so this will be sorry this will be zero one similarly your v2 will become our split one and this will become 0 1 okay so now we have got the 2 string array ok so what we need to do we just need to cast this string into integer similarly cast just string into an integer and just compare okay now there might be a problem uh when you can say your v2 is in the case 1.01.1 okay then it will be uh array of one like string array zero one and one okay now if you compare it with v one you can compare till second index like till one this index but after that there is no place like you can compare this so what we will do we will consider the 0th here like we can represent this 1.01 as one as like this also 1.01 as one as like this also 1.01 as one as like this also okay so i hope you got the approach how we will cast this it will be more clear when we write the code for this okay so first step is basically we need uh we need to split this into a dot area basically version one dot split and we'll give this two backslash and a dot because we need to split them on the and this will be an array so this will return the array similarly we will give our v2 name version 2 dot split okay now we'll loop over this so what we will do for now let's take it like this let's take two variable and i zero and j equal to zero we will do while i is less than v one dot length and j is less than v1 v2 dot length okay so this will be in the string array so first we need to convert this into you can say integer so first equal to integer dot pass end and we'll give this v1 uh i so this will give me first similarly we will get the second integer dot and v2 j okay we got the two numbers so what we need to do we just need to compare if f is greater than s that means we have a number which is greater than second so if version 1 represent f so we will just return one from here will not go further and we'll give one more condition else if s is greater than one that means second version is greater so we'll return minus one or equal we need to check in the further process so we'll not return the equivalent okay so this will do the when the v1 length and v2 length are same but let's say if not if they are not same so we will do okay we'll need to do for v1 also and for v2 also so while i less than v1 dot length okay the same work we have to do we need to take the integer parse and v1 i uh we'll check if f is greater than zero that means we found a number which is greater than second so we just written one from here okay the same and i just missed this part so we need to increment i plus also and j plus also uh in the same we need to increase i plus also okay we need to do the same for the second part also so just copying that okay one second so we'll copy it and j v2 second this will be v2 of j and if second is greater than 0 then we need to return minus 1 because it's a second number and we do j plus okay and if there is any guess like you don't return one and minus one so at the end that means both version are same so we return zero okay so it's look good let's run the code so this is accepted let's submit it so this is accepted and the time complexity for this basically we are just going to the maximum of v1 length or v2 length so this will be a big of n similarly the space complexity we take a version array basically create splitting out string into a area so that will be of big o of n also hope you like it thank you for watching my video
|
Compare Version Numbers
|
compare-version-numbers
|
Given two version numbers, `version1` and `version2`, compare them.
Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers.
To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`.
_Return the following:_
* If `version1 < version2`, return `-1`.
* If `version1 > version2`, return `1`.
* Otherwise, return `0`.
**Example 1:**
**Input:** version1 = "1.01 ", version2 = "1.001 "
**Output:** 0
**Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ".
**Example 2:**
**Input:** version1 = "1.0 ", version2 = "1.0.0 "
**Output:** 0
**Explanation:** version1 does not specify revision 2, which means it is treated as "0 ".
**Example 3:**
**Input:** version1 = "0.1 ", version2 = "1.1 "
**Output:** -1
**Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2.
**Constraints:**
* `1 <= version1.length, version2.length <= 500`
* `version1` and `version2` only contain digits and `'.'`.
* `version1` and `version2` **are valid version numbers**.
* All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
| null |
Two Pointers,String
|
Medium
| null |
1,489 |
hey everybody there's a slurry you're watching me solve this problem live during a contest I'm gonna stop the explanation and then it's going to go into some code review some times and then just me working on a palm let me know what you think about this format hit like button to subscribe one join me on a discord link below and I will start now or yeah decide what is fun find critical and pseudo critical edges in minimum spanning tree okay so who what is there to say about this one there's a most high so in the contest only a hundred and twenty one people sounded so you know that yeah this is a pretty hard problem and not even people didn't even bother submitting it so this is that very hard problem I was able to get at the way last minute with a lot of code I heard a hundred and five lines of code but a lot of it is that I was a little bit out of practice so you could definitely clean this up and I was just trying to get it at the end because I stopped it about five minutes to go in the contest so I just wanted to you know like it was a freebie if I didn't get it right so yeah so the idea is that we call from and a lot of this it took me a long time to prove and I have like if you look at the live solving of this a lot of it is just me doing nothing it seems like I was just thinking about it and basically if you could see this I have a notebook that I putting out for competitive programming but it actually doesn't come up very often for a lead code but this time I needed it so and I was just drawing little things to join hedges and trees to kind of figure it out one key thing to know before we store is knowing that N is less than a hundred and when n is less than a hundred and also the other one is rates as less than a thousand so what that means is that and that this part actually doesn't matter that much to be honest maybe because the only at most two hundred edges anyway but it just makes certain things a lot easier but basically cumin that n is a hundred we can do things more liberally so my idea was so basically okay let's go over some observations first the first observation is noting that using cous close algorithm or I think it's Crisco just don't now premiers is the other one but using a push goes album and hope I say the name right haven't said in a long time but basically is a minimum spanning tree album and there's a lot of computer science algorithmic fundamentals in this form so it's hard but the idea is that you know one at a time and this is the part where I wish I had a pen finger but you just but it's a little bit almost like so it's greedy Costco album is greedy and the observation is that for Costco you always want to insert the same rated edges at roughly the same time I mean if you just need any minimum spanning trees or custom for the cultures album then it doesn't actually matter what ordering it is but for this problem we're trying to get a critical edge and a critical edge is such an edge that when you remove it you it increases the minimum spanning tree right which is another way of saying it I don't think it said it too actually no it's just say it this way but I think I didn't understand it but so basically we go one by one given that the rate goes from one to a thousand what I did was I vote a four loop i I do it you I used Union fine for this and then if it's done we set it to done afterwards meaning that if we have more than one component then it's done oh so I we have only one component damage Weber minimis management it's done right otherwise I construct I keep track of all the edges that we added or we use this round but with just all the edges of the same way we basically what I did was and this is really hard to explain but basically what I did was I constructed a new graph that consists of only the parent so basically the notes that are the notes that combine to make the new graph so basically if for example at a very basic case let's say you know you have a 1 is equal to 2 - it is a node 3 connected to equal to 2 - it is a node 3 connected to equal to 2 - it is a node 3 connected to 4 and now we're trying to process and it may be connected to 5 say and now we're trying to process 1 2 4 as an edge and 2 to 5 as an edge way and but because that we combined these into one super node that's a super one and this is super 2 so now we have edges that goes from super 1 - super - right and in goes from super 1 - super - right and in goes from super 1 - super - right and in fact we have two of these and now come into play later but basically that's just idea of combining notes as part of the kuzco's album and then on each last processing do you look at the edge that allows you to yeah and then you just process them together because basically at the end of processing an edge wait you always have the same components so that's the part I had to prove for a little bit while and by drawing a lot of diagrams but basically that is the case because you can prove that if you didn't if you had another case that later then you could always just choose that edge now so that it's a little I know it's a little bit anyway we definitely try to prove it at home it's good it's a little tricky so they say after that now I try to find in cycles and what that means is that if there's a cycle then you only then every edge in that cycle is not necessary because you only need a subset of them right so basically for example the really basic idea is like the triangle right like with one connected it's connected to two is connected to three and then one is connected to jewelley so you have a triangle yeah you have a triangle and then don't you only need two of those three edges right so that's basically I mean you have a cycle that means that any of those three edges are not necessary because you can remove one of them and then they'll be still be fine so that's what a cycle means for minimum spanning tree because you have a cycle you remove one edge you will get a tree right so that's kind of how we structure it and then to keep in to note is that it doesn't have to be a psycho start from the beginning where you can imagine that you know there's an additional edge from 1 to 4 so it looks like a triangle with a little string dangling on top and in that case the 1 to 4 is critical all right so that's right end of the cycle - I got that's right end of the cycle - I got that's right end of the cycle - I got confusing to the backwards but that's pretty much it I did a lot of albums I mean I've been everywhere so that is the implementation detail but that's kind of the idea and it took me a little while to get that quite right because I just had off by ones and stuff like that because I haven't implemented cycle counting in a long time and also this is for me the way that I implemented us as we kind of notice there's actually um they're duplicate edges in this super graphs right because in the beginning because when you combine these notes to at least this is the way that I did it when you combine the notes you have these super edges way and then these super edges can have duplicate edges so the standard way that I would have done a DFS where you keep track of the parent it's not good enough you could you actually could do it with a parent edge because now if you have multiple edges going to the same node then by definition you could loop back right so yeah implementation is no tricky but I just do it there for search yeah so let's call the implementation a little bit so that's I by explain - favi part of it but the by explain - favi part of it but the by explain - favi part of it but the implementation I use union-find to look implementation I use union-find to look implementation I use union-find to look at the edges where is this Oh so for each weight which we reprocessed already into the dark we process this hmm oh yeah we process each edge so you could think of it as sorting it by the rich and I'm putting them together and then we process them all at the same time we do a new unified if this is a tree we're done but we still have to cut through some calculations over it done we returned the edges that we must have and then just that we maybe need so basically I here I constructors super graph by using the two-parent index graph by using the two-parent index graph by using the two-parent index ester identifier for the super node and then I just look at well I get to psycho and we'll go over to psycho next but just assume that you know the psycho that's what it does and I'm gonna put orden all the edges that are all the edges that you need in there or you don't need maybe yeah you don't need in there no you put all the edges that you need in there as part of it I think I did this the other way by accident that's why cuz I anyway I'll go over why in a second because I was talking about critical edges so that actually makes sense now that I think about but yeah and then after we get all the psychos and put it put in all the edges that I could and consider which why we go again basically this is just actually I could have if I just look for GW now then look at this but again I was I had a couple minutes left so I washed it but basically yeah we just put it if it's in the things that we are in it then we put in must if it is not in it then we put it in maybe and then we have to dad we just V Union we just update the graph of the Union fine so they get cycle part is a little tricky as I said I used to parent edge and step parent but the rest of this is basically finding a critical edge which is or that's the tester strategy that I took but basically the idea is keeping track of the minimum time and of when you visited a node and then for you to know see if that is this is a lot of math but slash algorithms but basically for each tree or each TFS tree if there's a back edge you mark that as being earlier and then you mark that current edge as a back edge otherwise if you're not and you're not able to go back then you consider it as a critical edge and it was a critical edge that means that this edge there's no way to be a cycle from this edge so you put it into the must miss for me I know that's a little hammer is a little bit tricky leave a comment in the YouTube video let me know your confusion and also join it this coach I know and I'll be happy to explain a little bit further depend on your confusion there's a lot of math in this one so it's hard for me to figure out like what level to kind of talk about it maybe I'll do another video in the future to kind of now that I recollect or the basic feedbacks because there is of course the things you need to know about this promise minimum spanning tree Kuzco algorithm a greedy point of the cuzco Algrim so that you could prove certain things and then critical path slash t FS / packages right so these are slash t FS / packages right so these are slash t FS / packages right so these are like three and a half things maybe that you need to know three and a half four ish things so it's a really hard problem I would not feel that bad if you don't get it immediately and also this video may not be enough because it's hard to explain all four of those things from first principles but that's how I did this for the last one okay let's see if there's a maybe people are just really good in that one and that's possible Christy because for the last one it is if there's um so they'd sort by edges and then they yeah they merged them I mean this merge is just Union fine original make sure yep this also is Union fine and then just then fine I guess this is the same way and okay this is a large scrolling 15 minutes mouth right after that everyone has a lot of coach I don't think and if I don't feel bad knowing that my album is roughly right I mean it's a minute so it's good but it's not to off everyone's doing Union fine as well it's just that um come on wait this one oh no mmm no this is because this one doesn't have how do you this is very easier than the way that I did it for finding a critical path and I'm not quite sure why that is well they do it in H at a time oh no they don't they do it all together oh I see oh I didn't know I didn't think that was fast enough so basically what they did was okay so I guess my album is faster than this one but basically what they did was that for each edge just construct a Costco again or well for each edge see if that for each edge see if you need it by processing the rest of the set so I think that was fast enough if that was fast enough I would have so done it this way but yeah but I do is that basically it's just itself doing a cycle thing that I did with crazy math in that crazy math but like it's just layered what they did was that you know given a psycho I mean it's essentially saying the same thing but they did it more naively which is that we remove an edge that's it we remove this edge and see if they're still connected if it is then they're good otherwise wow I didn't know so that takes all of 200 times 100 times around you know I guess that makes sense I did a little bit slower so if I did a thousand times 100 that's why I don't think I could do a thousand times 100 times a hundred that's five times slower hmm okay well I don't something today I think seems like most of the albums are doing the same thing and also they didn't C++ the same thing and also they didn't C++ the same thing and also they didn't C++ so that makes it easier yeah okay I think the thing is that in C++ think I think the thing is that in C++ think I think the thing is that in C++ maybe you could get away of it I don't think I could get it away with it with Python I could be wrong on that one but because they say that's what they did here as well so that feels a little bad cuz that was the hard part of how I solved it was that and I thought that would be too slow but cool q45 critical and pseudo critical edges in minimum spanning tree so this is a really hard problem really tricky problem for me anyway it required learning about minimum spanning trees and I actually took this a little bit harder than it needs to be but yeah well yeah at this point to be honest I was just drawing a lot of stuff on a notepad to kind of just try to figure it out the idea behind this is that I recognize that this so minimum spanning tree is a standard Quantico standard greedy album by itself not that I had to prove it but I was trying to figure out a case where greedy maybe is not good and I was just trying to figure that out but after that yeah otherwise I was just looking at the sample example cases and trying to understand a little bit I think at this point I was a little bit incorrect and that I don't I thought that the there are pseudo critical edges only the last once you add but that's why I was playing around and trying to prove to myself but thankfully there are a couple of educate a couple of test cases where that already isn't true but yeah so I am gonna skip a little bit ahead because I really just was trying to do proofs on my notepad and book for a long while feel free to stay but you know I'll have a link below so you could jump along with me but yeah not sure I'm gonna finish this one welcome back yeah so basically now I've settled on I basically prove to myself that cuzco is good enough and I'm trying to find the critical mat just trying to play around with a little bit by trying to solve it and of Cuzco you know that you're gonna have to do Union fine and that's the century of what I start off here and this is just standard Union fine I don't know if I recommend you know doing it my way but just you know play around with how you would do it yeah so far still standard Union fine techniques and because the edge weight could go from one to a thousand I was just a little bit lazy to do the sorting by roughly the same really but because they're only given at most two hundred edges but right now I'm missing one condition still I just thought I could start playing around with two kuzco's and then kind of see like help me visualize it a little bit yeah this is very basic kuzco's algorithm for calculating Union Flag and basically what I'm saying is if we plus s or these edges and we got one component then we're done again at this point I was under the mistaken assumption that only the last edges that you process will be maybe and the rest are on the must and for must I mean that you have to have them meaning that they're critical may be meaning that it's pseudo critical in the definition of this problem so this is wrong but my assumption here at this point was that okay if this is done now let's look at all the edges that we just add in and you know yeah and now I notice that I need to index so I'm just looking up way to put index I'm gonna just put on edge I didn't want to spend time looking up combining them so that's why I did it this way it's a little bit awkward for Python but you could ignore that probably but this is my first attempt again I was wrong on this one bit and now I'm just clearing up some syntax errors the way that I write that is because that's the way I write it and see passports and that works in C++ so I see passports and that works in C++ so I see passports and that works in C++ so I was had to fix that oh yeah and I wanted to make sure that my scope is why I did that but I also this is just cleaning up changing my union-find to be based off different union-find to be based off different union-find to be based off different inputs usually my experience is that you only need one Union fine things but in this case I was not so here I got an answer it is not right for this sake in case I think I know it this is right but I'm still trying to think I try to prove the greedy wrong because I'm still not convinced at this point but I do get the right answer and I can't really prove it wrong so let's see what Larry does here so do so the case that I was trying to figure out is that and that I'm trying to think about handling yes I thought that there may be a case where when you add an edge that you don't that it might not be necessary basically their edges done that right now I'm rethinking my initial thought that the you can only add sooner or every edge that is before the last series of edges are definitely critical edges so I was thinking about I was like that doesn't seem right so that's what I'm trying to write codes to get about I do implement this a little bit incorrectly most basic of what I was trying to do is say that okay like if and this is for the one step before the last one even though that's wrong as well but I think I was thinking about it now but basically let's say you have a triangle of a string on it right so like 1 to 2 something like that triangle go the string on it then in that case you definitely don't need all 3 of those edges right so that's what I'm trying to implement but incorrectly well yeah because I assumed that in that case they all have the same parent so basically I do a deed OOP by the two components that I add but that's not sufficient because multiple components can be added to the same component at the same time so that's kind of the trouble that I was handling with dried thing I do submit on this one but that's basically what I'm trying to solve in this part of it I mix them up yeah but I did get a wrong answer so I was like okay that it's fine I did submit it I wasn't super confident about it so I was just like okay now we have an answer that we can think about and that is the triangle case that we talked about so I'll I mean before that I was considering only like a circle case I suppose okay but yeah and now back to trying to figure out how to do this but basically at this point I suppose end up spending another half an hour on this but I knew that no so there a couple of components of things that would say one is that looking at now I know the output and outcome that I definitely did it in a way that was more complicated than necessary basically I did it and we times elog year or something like that where you could do it in Rita times Yi square but in any case from here what I did I need it is psycho finding and it's something it's an album that is not that hard it's not that easy either but it's not impossible which is why I grind but that set is an album that if you had practice it's really okay just uh okay but if you're out of shape as I was it would take a while but you actually did not need to know no doubt album you could have just did a more brute force algorithm in constructing the tree and that would've been fast enough but I did not know that at the time so again I'm gonna jump a little bit forward to dad so stay with me there'll be a link below thank you so we don't handle the transitive I got to do a deficit with packages like that you this was not true welcome back so at this point I knew that what I wanted was I need to find a psycho yeah I needed to find a psycho slash well I actually did the critical path which is that and this is way fun computer science II but I was using deff for search and packages to go okay if this edge allows me to reach earlier that I have that means that this edge is if this edge does not allow me to go back to earlier place with a back edge then that means that this there's no cycle containing this edge and that's kind of the algorithm that I end up trying to implement and it took a long time but yeah and you do that with a deaf first search so the entire complex is relatively fast but it turns out that you don't need it for this album for this prom given the constraints but I did it anyway so that's why I took a while otherwise a priori cap gun in it now which if I had just kept on coding on a more naive way and the more naive right is just running the minimum spanning tree and seeing whether it is connected the same way and basically at this point I converted the graph into an alternative graph that has the original graph but using so basically using Union fine and you if you think about Costco is just about you know and given find in general you have two nodes you combine them into the center one super node and that's basically the idea that I have here in reconstructing the edges and basically now I'm given these edges that we constructed I just recreated a new problem before these edges and then I go okay let's try to run a deaf were search to calculate the trees and this is for now this is very standard def for search of psycho finding is it's just basically given an O and a parent and you don't go up to parent I do make modifications here later on as will point out but again I am actually very vast deal of this algorithm so that's basically what I'm trying to do here and this idea of packages comes up on critical edges and other similar recursive tree algorithms but that said I don't know if I recommend meeting this it's just that some once in a while you need it's very rare for an interview well it is it's very rare that you need both these things on an interview and in one form but to last you on this one well yeah right now I think I was just trying to look through some old code on my computer just to make sure did I get just make sure that I get the parameters correct so I had to pass and edges I forget I mean at this point I was just forgetting whether like some of the initial edge case or edge conditions or base conditions and I was a little divided between hair so a little bit tired but I was a little bit divided between doing it by using a effectively a global versus passing it in normally I would probably do it in Kabul but I really wanted to pass it in because I wasn't as familiar as I used to be so then I don't have to deal with and also because I call this multiple times I don't have to worry about scoping and clearing out data and stuff like that and again I have to put back the index yeah basically now I'm just thinking through a little bit how to go for it I think right now I was just thinking a little bit about how to deal with the parents in a because in this case in a super know grab multi edges that or not as you know as it's not a there are multi edges which in some cases to not so or usually they do not need it but uh again I'm falling because the coat that I was referencing to be honest is in C++ I was referencing to be honest is in C++ I was referencing to be honest is in C++ because I bought it a long time ago so that's why some of my syntax is a few buddy C++ II and that's Python II pythonic yeah all of what I'm writing is a basic part of those back edges recursive tree algorithms they're the one that I remember is the critical edge one so yeah so definitely look that up it's kind of hard to figure out what's in scope for an explanation so maybe I'll do another video on that in the future oh yeah now I just have a step in type wearable and now I'm able to start on my recursion I think yeah I have to put in the visitor way and then just set the step and the package up to the current time step I forgot to increment it here so I do later go back to fix this and this is just there X is equal to parent so that we don't go down to your parent but we actually need to change that a little bit of a support yeah if we already wizard it then we just this is pretty straightforward we set to current notes package is to go to the earlier step either here or the yeah the time in which the time you know whatever you want to go but that's already set up otherwise you just you know go to that step so there's a lot of debugging after this which is why I'm wanted to commentary or add commentary to this point so that I feel like learning how the debug is a really important skill and happens in real life more than anything so yeah and now otherwise go to the W do a deaf research and then you calculate you get the min of either your current node or basically it tries to go try to calculate the forest and you can go back in time and if ya have to try and look at the indexes but if you are not able to well if you are ya not able to and I can't see okay and I'm just setting up the answer which is that in the numbers once we get to cycle then we do stuff we go okay that means that we have to add this edge into the answer if yeah if the answer is that is a quick I did a little bit weird but well yeah I have a type 1 else I think yeah but basically I after I wondered deficit or to get psychos it should tell me whether an edge should be and maybe or should be must and then we just at the end if it's done then we return it so now just fixing a laugh syntax errors because like I said I'm I guess my dears C++ kind of I love it and I my dears C++ kind of I love it and I my dears C++ kind of I love it and I look at the ends I'm like okay that's not right at all right I'm like I'm next and to be honest this is way this is where practice makes perfect which is that if you are confident about your algorithm then you know that's your implementation and you're covered about your implementation then you may second-guess your algorithm right in second-guess your algorithm right in second-guess your algorithm right in this case I was not sure about my album or my implementation which makes this a little bit harder because I wasn't sure if that's correct like maybe I implemented correctly but I just didn't like the algorithm just didn't work right so the first thing I notice is that you actually need to not just the parent like it's okay to go back to your parent but not your parent just not the same edge because they could it could have multiple edges right so that's kind of I add that if statement and then that was roughly the same to be honest but I knew that was at least a correct way to handle it so I was okay with that in that like oh wait I needed that fix anyway and at this point where I'm pretty low on time we have about 10 minutes left in the contest yeah and now yeah I realized that I was actually I got to know it's backwards which is that I shot one if the back edge if the edge this back edge is before the current time meaning that using this edge allows me to go back before then ten damage that there's a cycle or the other way well yeah so then now that means that this edge is critical because oh sorry if you're not able to go to a time before you first process this node that means that there is a critical edge and that it is not part of a cycle so that's kind of the thing that I fixed I just fixed her names but they're also one more bug at least one more bug and some of this is just a little bit our practice because I think I mixed up the definition of what to put in and what to not put in and what makes it critical and what's not and I've had to denly put the edges that would have been part of a cycle under that critical one I forgot to acquaint my one so that's one decode and yeah I just had to and then as soon as I do that well wait I meant nanoka so that's one it again and then I got roughly two right answers but not in the same place so I was like that's that right like it the thing with debugging this one is that we're straight up missing edges that I know that we're processing so I was trying to figure out why that is the case and I do remember why which is a little bit sad but it's because I was a little bit hasty and implementing I printed out I was like okay this there is stuff in here so what is going on unlike earlier and yet there's a short story is because yeah here I knew that I had them in the wrong order that's fine so I have them in the right order but I'm still missing edges and the reason is because the way that I did it because I have two if statement a little bit too early because we do the check and the Union step at the same time so not order it doesn't all come out at the same time and you guys see me fix this real quick so but yeah but that's kind of me on this contest it was very interesting I liked it let me know what you think about is well and I will wait hang out with Dettol a B C's weakest part is bug but when you see it you will see it anyway I'll see ya down a Mary in the pen and trying to disco chat up Union it again yeah why not about five minutes laughs I mean I know maybe I celebrated too much on that one bit that's our problem I didn't expect to get it to be honest and there's only five minutes left people got it really quickly
|
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
|
pizza-with-3n-slices
|
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**.
|
By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it.
|
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
|
Hard
| null |
1,269 |
Hello friends welcome to Cod sura in this video we'll be solving lead code problem 1269 number of ways to stay in the same place after some steps though this problem is marked as a hard level problem I would say this is a medium level problem and if you have solved yesterday's problem or have some understanding of dynamic programming please do go ahead and solve the problem first on your own and then only watch this video because I think you'll be able to solve this problem if you have some understanding of dynamic programming please don't be fooled by the tag of heart having said that let's dive into the problem in this problem we are given two inputs so what are those inputs one is input is steps and the second input is the length of the array so what does this mean so we have an array of length two so just two so initially you are here now you can do three things so what are those three things one is you can stay in the same place one is stay in the same place or there is one more option that is you can move to your left just one step you can move to your left so can you move to your left no you cannot move to your left in this position why because there is no minus one in this array now what is the third option is you can move to your right that is + one in this case to your right that is + one in this case to your right that is + one in this case can we move to+ one yes so now initially can we move to+ one yes so now initially can we move to+ one yes so now initially you will be in this position you'll be in this position what is the problem asking the problem is asking after three steps you have to be exactly at the same position all right so you started at this position after three steps you have to be at the same position now how many different ways are there to do this now let's look at the different ways one is you are very intelligent person and you think of I will stay in the same place any at the end of three steps I have to come to the initial step so let me stay at the same place 0 so this is the first way then there will be another person what they will do they will stay in the Second Step they will go plus one in the last step they will again return back so this is one more way of doing it what is the other way 1 0 so now we found three ways let's look at if there is any other way to do this yes there is one more way what is that zero so initially you will be zero so you will go to one and you will stay in one and come back to zero now totally how many ways can you reach the final position that is zero so the total number of ways was four so this will be our answer and if you are facing difficulty in understanding this question so do consider solving this problem first that is lead code 70 it is I think climbing stairs it's a easy level problem if you finding difficulty please do go and solve that problem first and do uh continue this video next and there is a quick announcement that we are having a workshop on dynamic programming in the upcoming week and we mentioned this in the telegram community and we are a telegram community of 350 plus people I mentioned the link in the description so do consider joining our telegram Community now before diving this before diving into the solution what is the first step that we have to do we have to identify which is the solution that we have to do so here if you look since there are three choices you have to make at every step so where is this leading us to this is leading us to dynamic programming why because at each step we have to make a choice and there are three choices at every step now let's try this out and find it out all right so what is the first step that we have to follow in dynamic programming we identified the choices so at every step we have three choices some may be valid and some may be invalid say for example if you are at this position minus one is an invalid step but at every step we do have three choices we identified the choices now we have to draw the relationship between those choices let's draw the relationship between those choices now say you have two more steps remaining two more step steps remaining and say you are at position one now how many ways in how many ways can you go or how many choices do you have one is in all the steps the number of remaining steps will get reduced so now you have 1 + f of 1 plus again F of 1 you have 1 + f of 1 plus again F of 1 you have 1 + f of 1 plus again F of 1 why is there a plus because we have to add all of them why we have to add we have to find the total number of steps so this we are clear in all of them the number of steps will be reduced so instead of taking two steps we'll be just taking one step in the next step so what are the three choices we have from one you can directly visit Zero from one you can stay at one or from one we can go to the next step that is two in this case this may not be valid but still we have to write this and these are the three choices and this is the equation that we have now once we have the equation what is the Second Step that we have to follow the second step we have to follow is the recursive tree so that is what I'm doing here let me R write the array length that will be equal to two and steps what is the initial steps we are given three steps so now at what position we are this will be our Index this will be our index and this will be the remaining steps that we have to take so now let's follow the path and let's identify so this we are trying to move to minus1 so this will be min-1 one this to minus1 so this will be min-1 one this to minus1 so this will be min-1 one this will be zero that is staying at the same place and this is + one so now if you place and this is + one so now if you place and this is + one so now if you directly look here this is the invalid scenario because we cannot go there minus one is not a valid scenario now these two are valid scenarios right we can move to zero that is we are staying in the same place and we are moving to the next position again we have three options once we have come here again this is the wrong option these two are valid scenarios and I won't be explaining this uh the right part let me explain this so once you are at this position we are arriving at the base cases what are those base case the base case is you don't have to take any more steps that is the number of steps have become zero do we have to continue the tree no this is where we have to stop the tree so is this a valid scenario no this is not a valid scenario is this a valid scenario this is a valid scenario but this is not what we want in the answer this is the only thing that we will be wanting in the answer let me change the color so this is a valid step now for this again what is the valid step this is the only valid step and all the other things will be invalid this is the invalid though this is not invalid that is not the end position that we want right this is not the end position so these two can be eliminated now if you look this graph or if you look at this tree very carefully you can identify some what is that this 1 comma 0 and there is 1 comma 0 here as well so there is 1 comma 1 here there is one comma 1 here as well so can we just store the results somewhere and directly write the answer so from this how many steps are going here so 1 0 equal 1 so 1 0 equals 1 and 1 one also equals 1 can we write this yes there is only one step and directly can we instead of doing this chart and going through this once again can since we have already computed the answer can we directly write this as just one and can we also write this as one so 1 one there are four scenarios where we'll be able to reach the final position and an interesting thing that we noted down here is we have to save the states instead of recomputing once again right so now the next question is can we save this state with just one parameter or do we need two parameter say for example this 2 1 and this 1 one are different all right this 1 Z and this 2 are different in each other so we cannot just store the results with just one parameter but we'll be requiring two parameters to do this so we require two parameters so where is this leading us to this is leading us to our two-dimensional is leading us to our two-dimensional is leading us to our two-dimensional Matrix to store our results so that is what I have drawn this it is the same example that we are looking into and what is the base condition is so this is index 0 and this is index one let me write this in blue color so index0 and this is index one remaining step is 0 1 2 and 3 so for this box for sure we know that this is equal to a one why because you are at index zero and you don't have to move any step further so the uh here it will be one now let's go to this chart and see what is the index 0a 3 0 comma 3 so this will be our answer now what is this calling to 3 comma 0 is calling us to 2 comma 0 and 2A 1 so 2 comma 0 uh 0a 2 and 0a 1 are there in this no they are not at fi so what is the final thing that we will call it is 0 comma 0 and 0 comma 0 once again so 1 comma 0 and 1A 1 are 0 1 and what was the other one 1 comma 1 both can be filled with one so 0 1 can be filled with one and 1 comma 1 can also be filled with one now once we have filled this the answer flows and the options are filled and finally we will have four at this option if you are to fill this table or if you have to fill this uh table do fill out and you will see the answer 4K so this what will this approach be to up essentially what we are doing we are calling this and the though the answer is computed from this corner we are calling this repeatedly again and again say for example in just this small case scenario we hit this right we hit this twice but if you look at a large tree you'll be recursively calling them again and again in order to avoid that we can use a bottom up approach so what we will be doing here so we think of it see we should be filling the table why not fill the table in an ordered way and avoid this reputations all right so that is what we'll be doing for sure we know this will be one now let's fill this so what will this be this also we know to be zero because the remaining steps is zero but you are at a different index so this will be zero now from this all you have to do is look at the previous this value and fill this so just add this one so this will be one so you will add these two for this will be two this will be four so the answer is four in this case let me explain this with a bigger scenario so that it will be easy for you to understand so this will be 1 0 for this box what are the options that you have got one is this option what is that essentially we are planning to stay in the same place so and what is the other option is to move into the next place so we will add one plus 0 it will still be one now interesting case is with this box what are the three options this box has three options what are those this option and this option so it is sum of 1 + 0 + 0 though this is 1 you have to + 0 + 0 though this is 1 you have to + 0 + 0 though this is 1 you have to look at this carefully because it is the sum of all these three and in this case it will still be zero and if you look here this will be two now this will also be two and again this will be one and if you look here this is where the interesting scenario occurs and this will be equal to five why this is 2 + 2 will be equal to five why this is 2 + 2 will be equal to five why this is 2 + 2 + 1 and but anyways this is the answer + 1 and but anyways this is the answer + 1 and but anyways this is the answer that will be required in this case now let's dive into the pseudo code of the problem and this is the first step we have to do why we are taking this it is because say we have an array of length 10 but all we can do is we can take three steps then it doesn't matter right if you have an array of length 10 all you can do even if you do plus one + one even if you do plus one + one even if you do plus one + one this is the max position that you'll be able to reach so can we reduce that yes that is what we are doing in the first step then we are creating an array and then we are filling up the array what we are doing we are filling up in the same order that is we are filling in this order we are filling up is this order and we are moving in this direction and you can also move in this direction but this is what uh I have preferred and finally at every step you will look at the three options that you have and you have to add this if scenarios because in some cases it will get give a invalid or ar outof bound ex uh exception finally you will be rning the answer and there are few similar problems that you can solve in order to understand this concept even better and if you are somebody like me you would have thought that there should be a direct formula to understand this problem right yes there is a direct formula and that is what we have done in this problem also and this is something called as binomial coefficient and this is something very commonly in dynamic programming interviews so do consider knowing about this concept in a very deeper way and these are some of the problems that you can solve to understand this concept better thank you for watching this video please do like share and subscribe
|
Number of Ways to Stay in the Same Place After Some Steps
|
market-analysis-ii
|
You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** steps = 3, arrLen = 2
**Output:** 4
**Explanation:** There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
**Example 2:**
**Input:** steps = 2, arrLen = 4
**Output:** 2
**Explanation:** There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
**Example 3:**
**Input:** steps = 4, arrLen = 2
**Output:** 8
**Constraints:**
* `1 <= steps <= 500`
* `1 <= arrLen <= 106`
| null |
Database
|
Hard
| null |
146 |
yes today I'll be doing on 146 which is called Lau cache and this pop-up states called Lau cache and this pop-up states called Lau cache and this pop-up states that we want to design an event a structure for at least recently used cache it should support the following operations get input yet whoa get about you and it will always be positive of the key if it exists in the cache otherwise it would send negative one put will set or insert the value if the key is not already present when the caches reaches is associated invalidate the least recently used items before inserting the new item so the cache is initialized with the positive capacity and one thing that we should consider is that we want to make sure that get and put option operations are all one operation or I guess like complexity and here's an example that they go through there create a slit capacity size to when we put one into the cache would have those two keys and they'll map to the same number but two will be recently used and one will be least resilient to use but once we get one becomes most recently used and to pm's least recently used when we add three would evict at least recently used item which would be two then for the cache would only contain three and one and because it only contains three and one when we tries to get two we get made of one so again when we put four and what happens is since there's only three and one in the cache three is just been news right here one's been used up there therefore one is at least we only use so when we put four and one becomes evict it so now in the catcher it's just four and three therefore when we try to get one we get negative one because not now when we get three and four they do to return the correct values okay so if you haven't tried this problem I recommend pausing the video to give it a shot otherwise I will get started with it I will copy this community of clutter pad so that I can debug it as I go so I think I'm going to take it slowly I guess so let me think about what kind of data transfers I want to use so if once you do a least recently used we need some sort of collection to store our items and we need to be able to rearrange those items as they are used in some sort of list so if we just use a regular Python list this would work but imagine if we had a list and an item in the middle just got recently used I have to put it in the front of the list to indicate that this a certain ordering on how these items are recently used so if I put the item in the front I'll have to ship all the items that were what that were on the left of it right one and that would actually be Obed time but if I rather than using like a regular Python list I can use a linked list then to move an item to move a note out of its position would be constant time and to move it to the front would also be constant time so because of that I want to use a linked list to store that information to store the information about recently use so I think that we would also need to consider is that when we try to get a key we need to be able to get the key in oh one time so in order to that we should use we can't just use only lists by itself because we would have to loop over each of the linked list to find the matching key and because of that we should actually use a map that would map a key to a node and then Nicolas and then once we have to note in the linked list we could prioritize it to the front to get that bit recently used and also that node would also contain the value of the cache key all right great let's get started so initially in the structure functions as a capacity so since we're getting it back to pasady we should might as well save it onto the objects and as I mentioned before we once use a linked list in which case we have to create a node class that won't be a I guess the nodes of the linked list so in this node I will have a value and this will also have pointers to the next node and since we want to stitch or I guess since we want to move items to the front and the back unless we wouldn't need a doubly-linked unless we wouldn't need a doubly-linked unless we wouldn't need a doubly-linked list and in which case we need a previous and next pointer next that's nuttin first and previous another and the user of this object could set those values after but then the values should be initialized so to encode a linked list all we will in need is pointers to the head of town and what I'm going to do is I'm going to create a dummy notes for the head and tail and that way we can always access elements near the head of tail without I guess looping through the entire objects so see I'll put my head here and this will be a node and I will make it have a value H so that I will be able to know that's a head and I don't create another IOT for tail and now initially our linked list will be empty but it will pop the head and tail that will point to each other which is not to say that the head on next is the tail and tell that even if you go to do the head okay so this constructor looks good so far let me write one function that would test this kind of just uh I guess we'll print out the data of this object so what I'll do is I'll have a function called start and it will just create a stream representation of this object and what I'll print out is results and then I'll say that's I'll fun with the head and I'll say that this is the turn note I was a wall that note is not none then I want to add the note value no value to the results and I also want to add a I guess at that to separate the values so I'll add a dash there like this but I really don't want to add to - this but I really don't want to add to - this but I really don't want to add to - the for the tail pointer so if note is equal to depth up tail then I will not have this doctor otherwise how the - have this doctor otherwise how the - have this doctor otherwise how the - great so let me return those results and let me create a cache objects so I've created with dice capacity - and then created with dice capacity - and then created with dice capacity - and then I'll find out let me see if there's anything obviously wrong so when I print out the cash this cooked ones forever because it's an infinite loop since I never a modified the note but I didn't know that next is or nobody knows about that next so I'm actually looping over to like this so I save it again oops let me save this and now we see that this it goes from h2 T this is exactly what we expect which is good so we can skip started with maybe using a function that puts in I don't so let's say if we want to put 1 then I would need to add this node to the linked list and yeah I'll pledge to start with that I'll add the note to the linked list and but we need to somehow know if the node exists or not in the list because you don't want to be adding duplicate notes because if we the put function is supposed to either insert or update a note depending on if it exists or not so I would need an object to map key values to the note so I'll follow this map for simplicity and in the foot function there's two cases if the not exist or note did sexist so I have no case that the note does not exist and then in the map and the date option so if he is not in the map that we want to insert I always want to set so if you want to insert then we would create a note with the value on its value and then we want to add this note to the front and since I feel like we're going to use a function that adds that moves notes to the front a lot I will just have help move to what just take another and that should basically I need to do other things for example I need to add this note to the map so South map so he is and then since we won't be doing some evictions depending on the size I will need to increase a size bearable and because I am increased x ry I need to advise to zero so this looks so good so far let's write a function call so no and back to this we had a linked list that was like this and we wanted to add a note and then we would and we would need to move will have to add a note here so this is the before this is what one add and this is the after result so a couple things we have to update is what the head is pointing to and what the note one is pointing to and we also have to update note the note that's being passing to point to the head and note one so let's first create this connection myself that head next and then note that previously people to go ahead and now we can create the next connection is right here so note that Mexicans who knows what but what is node 1 no one was it was originally had that next so we have to store that value break so no one's a good head so and now I'm not one that beautiful equal to no that's too massive and that should be it I think that's so I'm putting this on one here and I'm also putting the cash afterwards so now actually specs h1t see if that is true that's not quite true cuz I have not to use self a header right great a 20 okay now we need to probably handle some other cases for example if we insert if we I'd say let's handle the case where we add another item this arm at automatically work let's see yeah I should automatically work and that's now panel case that we want to update a value so if you want to put one and set that to be something like new like 100 then we should expect one two still exists but now one shouldn't be moved to the front the reason why it isn't moved to the front is that this condition is false therefore we need to handle this case so we need to set the night so to set the note we will first get the note from the map itself that map LP and now we would just set the note by using the setter and since we just used it we need to then also move that note to the question great let me think so this one's a bit tricky because not only we have to move this notes the front we also have to remove the note from the linked list so for example if we had to note that looks like if you had a linked list of effects this where the note that the noted question is let's say it's right here then if we just called our move to function and the new Nicholas would look like this the node will be in front but and one will still have a note next point to that points to N and N two was have a previous pointer that next that points to and as well because this function never modifies what is this function never modifies and one an end to like where the note used to be it just moves it to the front assuming that the note it doesn't exist in the linked list yet so let's write a function to remove that note from the linked list then we can move it to fun so remove so like this then we want the final results to just be without that note in which case we need to get the previous n1 and n2 and we just have to point them to each other so no one will be know about tedious and no to leave all that mess and it's conveniently it's convenient that we have dummy had a terrible note because even if the note was the last note didn't know that next wolf still exists because he'll just point to the dummy no okay so we have no want to know to and we just want to point them to each other so note 1 dot next to secure - right - so note 1 dot next to secure - right - so note 1 dot next to secure - right - and now - and just for safe of cleanup and now - and just for safe of cleanup and now - and just for safe of cleanup we can just remove the note that an accident all that to use so that is truly removed from its isolated from that linked list all right so since remove it we add it we thought the change of size because we're just setting the value so let me try running this and we should respect h1 to cheat all right we don't get that because the we're printing out the value is not the keys so this is actually correct all right cool let me then think of what else we need to do we need to also give it to items sell for example if we put three here then we need to evict the last the least recently used item which will be two but I think what's gonna happen now is we're gonna add the two anyways or the new guy anyways so yeah three sir but what we really need to do is we need to evict this too so after we increase the size that we can check that the size is above the capacity and if that's the case we'll remove the note and then we can decrease the size to the capacity so if self that size is greater than the capacity then we should remove the last note which is self that tell about previous and good thing we also remove and just remove that then each piece of ties all right I see how it goes great this looks good so now let's see what else you have to you I guess we don't have to write the get function but this is all for the put function and this might be it for the put function all right so the get function I think again there will be two cases if it's not in a map and we want to return negative one so key two things is in the map then we want to return negative one and I just realized something once we move this note we have to remove from the dictionary and let me update the stir function so that we are also printing out the dictionary so that we could deep make sure that we don't miss any bugs so let's see unfortunately the star of a dictionary doesn't look nice oh it actually does look nice so this is the note but the note doesn't have a stir function so let me just create a serf function on the node so and then I'll just say something like to turn value so whoa I think I have to do okay so one maps to the nub would buy 100 to masses and Obadiah to three master node with value 3 but the linked list only has three and 100 so when we added this when we removed this note we also have to remove from the map so felt that map the T needs to be deleted but which key needs to be deleted it would be the this would have to be the key of this will have to be the key of the last element and unfortunately we only have the values of that loss element and in order to get the key of the last element we really have to store it in the note so the note should really be a pair of key and value so when I put an item in rather than putting just the value I just need to put the key value and then okay so actually alright so what I can do is I can have a two parameters for the note it will take in the value and also a key which case I will have to update this I'll set this to none initially or default it to that doesn't break our test cases so when I add this key here I then have the access to the key on this tail down removing so I can do self that tail that II and delete that one the map I see if it's worse self that to know that well it should be the self that tell that previous so this is a know that I want to remove although since I'm calling the blue function I really need to move from the map first so that lets help that tell that pre-match the same I think that once pre-match the same I think that once pre-match the same I think that once removed but let me just move that to a variable and then I want to delete out that to remove that key and I want to all right so now our Nicolas matches our map great since we have a key as well bleep I don't get all right so let me do one more thing in this third function let me add a new line there so that the heparin outlets better all right okay so we successively evict at something and I think the last thing we need to do is finish the get function so the get function which are native one when a value does exist so if I call gets I'd say five which would be negative one yep I see neither one here and then if I get a buyer that does exist have to return the note but I should also prioritize that note so if I try to get the key one then the I should get the value 100 and also the linked list should be updated so let me prints whatever when I call it gets one currently this is not implemented this will return nuttin because this not the code is not there right yeah I just ran stunts so I have to handle that now so otherwise I have the node that map Becky and I want to be sure to note that value but before I do that I want to move that note to the front and we get 100 which is good but this palm the palm is that the move to function move to front function let's see palm is that when I point out the cash there's an air it probably is doing an infinite loop which is not good so move to fun no so the reason is doing that is because I have to when I move and notice when I have to remember to remove it from the after remember to remove it from the list verse because move to find a students that is not in the linked list all right great cool so it looks like everything checks out let me put this build in here see if it's working so I'm going to run this kind of great this looks like it matches let me submit this cool yeah thanks for watching if you liked this video please click on the like button but have a good
|
LRU Cache
|
lru-cache
|
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Medium
|
460,588,604,1903
|
938 |
friends today I'm going to solve it could problem 938 range sum of PST so here we are given a binary search tree and we are given the node root node of the binary search tree the two integer values low and high and we need to return the sum of all the values of the nodes whose values are in the range low and high so let's see how we could solve this problem so we are given these binary search tree and we are given a range low and high so we need to return the sum where all the values uh where the values of the note lies in the range high and low so it's an inclusive sum so this should this property should always be satisfied this condition so even if this condition is satisfied that is only when we add the value of the node to our sum so this is what we are going to do if this condition is satisfied now the point here is like how are we going to Traverse this tree because we need those values of each of the node right we need to check the values of each of the nodes with the left and the with the low and the high range right so how are we gonna reach if each of the node so basically what we could do is we just need to Traverse the tree in one way or another so um the easiest would be or to use the depth first search so I'm gonna use depth first search to Traverse this root and this tree so their first search means we move from a given node we go to the left and then um of that left sub tree so basically from a given node we go to the left subtree and then that sub tree all in that subtribute to the same thing again so basically here this whole tree we start from this node and then we move towards the left of this node so this becomes our new sub Tree in towards the left when we move towards the left this is our sub tree here now in this subtree the root node is this one right so we reach this root node and that from this root node as well again we go towards the left sub tree so this becomes our left subtree now this single node is also a tree so when we try to move to the left of this sub tree of this note root note the value there is no root node here right the value is equals to null so when the value is equals to null we return back to our root node we try to move towards the right the values again is null so we return back from here and then we return to our previous root node and then we try to move towards the right and then we do the same for here for this also so we try to move towards the right and for this right subtree again since it is a tree we try to move towards the left since there is no root there is no nodes towards the left we then move towards the right and on each move we keep on checking the values of the node and if the value rise within this range then we add to our sum else we just keep on moving and at the end we return our sum so let's code this solution so what we need is we need the value sum which we will be required which will be returning at the end and now we need to create a DF as solution so I'm just going to create a function DFS function here and then we also need to check if we need to pass in a node here and we are not need to check if the node is null then we are going to return back to our previous node else if you are again gonna check if the value of the root node is greater than equals to the lower range and the value is less than equals to the height if this condition is satisfied then we add to our sum the value of the node and then we move towards the left of the node and then we move towards the right of that node so that is how we'll be doing this let's try to run our code oops okay so one mistake I did is I did not call my DFS function so we are going to call the DFS function from the very root of our tree and run the code cool let's submit it so the time complexity of this whole function would be Big O of n because we are iterating over each of the nodes of the uh of the tree so it's often and the space complexity is a constant space complexity
|
Range Sum of BST
|
numbers-at-most-n-given-digit-set
|
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`.
**Example 1:**
**Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15
**Output:** 32
**Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32.
**Example 2:**
**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 2 * 104]`.
* `1 <= Node.val <= 105`
* `1 <= low <= high <= 105`
* All `Node.val` are **unique**.
| null |
Array,Math,Binary Search,Dynamic Programming
|
Hard
| null |
562 |
hello friends now less of the longest an eye out can see reach if one Ahmet ryx as lemon is given a zero one metrics and finding the longest eye of conservative one in the metrics the line could be horizontal vertical diagonal and anti dark so see this example we can find that the longest so consider one is this guy so the result should be three how to solve this problem basically I think it is obvious that we should use dynamic programming because say we are at this place there we have four directions which is the horizontal we can use its previous longest I consider one plus one and the vertical we can use in the previous row the same color the long gates are considered one plus one and this is the tag no the same idea this is anti diagnose and every time we update the current value we will compare the result and the current value so we can get the maximum considering one the term complexity should be all M times an M is the rows the number of rows and is the number of the colors one point we needed to pay attention to is that usually where we use a deep here there are sites should be robes plus 1 and the colons plus 1 but in this case you see when we are here we should compare the previous column and where we are at this place we should when we compare the anti-diagonal should when we compare the anti-diagonal should when we compare the anti-diagonal we should have the value of the next : we should have the value of the next : we should have the value of the next : so basically we have two more columns in the DP array so let's do it educator if the an e-coat so let's do it educator if the an e-coat so let's do it educator if the an e-coat or not or m da less equal to zero gesture 10 0 then we get to the number of the row so you should is the number lens and the color so she's mu zero dollars we will use a deep here it should be 3d and the first dimension is the Rose one field even when we add to the last row we only needed a previous row and when we add to the first of all we need its previous row so you shouldn't Rose +1 and Collins and I said shouldn't Rose +1 and Collins and I said shouldn't Rose +1 and Collins and I said we need two more and there's a third that measure should be four because we have for direction to compare as a by default is a very is zero and so we need a result in the at first L equal to zero then we just iterate this amps all right - also start from zero I less then if I - also start from zero I less then if I - also start from zero I less then if I J equal to 1 we will first update a current place there we use the zero to represent the horizontal line there will be previous in a previous the same row but the color shouldn't be color shoulda be lesson 1 less than 1 0 last one will update without ego to the max result in the DP I plus 1 J plus 1 and 0 this is the horizontal line and the vertical line is repeat if he is a current her place what should be the deep he the is a row to be lessons and what so should be I the same color J + 1 DC the one dimension press color J + 1 DC the one dimension press color J + 1 DC the one dimension press one risotto where you put your mess as result TP I plus J plus one dimension okay so now we will consider tag no J plus 1 to coach with chips so if you see the current index is I J so the previous place in the horizontal line should be M minus 1 J minus 1 so in this case the previous point is should be I J and the truth plus 1 up till this resulted in Max without epi J - and resulted in Max without epi J - and resulted in Max without epi J - and there we should a competitor and he diagonal plus 1 3 if the current indices IJ the previous point in the same and he diagnosed should be I plus 1 also I minus 1 J plus 1 so basically if the case should be I and the collar should be J plus 2 and if there will be 3 plus 1 we update after the result without in the DP I plus 1 J plus 1 3 so finally it will just return this result some thing is wrong blessing what's wrong if currently caught you want yes we the current mmm yeah will be previous this is horizontal so the same row ah this place to be the current not to the previous value okay thank you for watching see you next time
|
Longest Line of Consecutive One in Matrix
|
longest-line-of-consecutive-one-in-matrix
|
Given an `m x n` binary matrix `mat`, return _the length of the longest line of consecutive one in the matrix_.
The line could be horizontal, vertical, diagonal, or anti-diagonal.
**Example 1:**
**Input:** mat = \[\[0,1,1,0\],\[0,1,1,0\],\[0,0,0,1\]\]
**Output:** 3
**Example 2:**
**Input:** mat = \[\[1,1,1,1\],\[0,1,1,0\],\[0,0,0,1\]\]
**Output:** 4
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 104`
* `1 <= m * n <= 104`
* `mat[i][j]` is either `0` or `1`.
|
One solution is to count ones in each direction separately and find the longest line. Don't you think it will take too much lines of code? Is it possible to use some extra space to make the solution simple? Can we use dynamic programming to make use of intermediate results? Think of a 3D array which can be used to store the longest line obtained so far for each direction.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
128 |
Hello guys welcome let's go straight to the video language problem me this and the longest corridor sequence from this problem me to the front ginger green the length of maximum quantity consultancy okay what is the quantity sequence positive sequence pure sequence like late to 1234 and 789 and late Se 60 Ok And Monitor Se Zone Died In Just A Few Tips Number To Do You Can Find Very Long Time Complexity Close Ajay Ko Se Time Complexity After Lord You Turn Off Intent Complexity Ok And Verdict Related To Time Complexity Will Have To Take Care Love You All Subscribe And See What He Does Soul Exist To All Elements For Toys On Rent In Another Day To All Elements For Example Will See This Agreement Which Always Stand Distance From The Set And Not Log In This Particular Case Will Try Search Ignore Very Fine Tank OK What is the Mean When Did n't Change the System and Connecting 1110 Smartphone Grade One Position Elements But in Internal Matters Not Changed Which Includes Connected to Before She Does Not Connected to Any Previous Change Your Destiny 125 and Values from this Values from this Values from this is not review nor two way get meaning of elements select this element single element no one can start this that grand slam single guide user can get connected with chicken wings developed single right nine same year 2012 search for another day another element in the The Length Of The Longest First Form Subscribe My Channel Thank You All The Best Tags Element Mix Element Will Be To 9 Will See You Will Strive To See Its Predecessor Of Track Per Example Of Various Channels Coming From Previous And avoiding to in this case prevalent this year former vice president of these remains suite one is present in every saint and restoring set developed officer all dowry take off when contacted for brain research institute of law and complexity to search the are sorry don't want to win Over 800 Unit Certificate Google Look Upon The Limits In Over Night Complex Because Decided To Dinner Playlist Sunao Indra Set Kiya Looking For *Em Looking For One Set Kiya Looking For *Em Looking For One Set Kiya Looking For *Em Looking For One And What v5 Vicent Element Backward Tools Getting Connected From Creating Follow To Is Not Single Red Color K Connected Zone-2 of all these things is already connected with someone Zone-2 of all these things is already connected with someone Zone-2 of all these things is already connected with someone so quilling notice element flat ignore it so and latest mobile suvvi the change but you can potentially form and this forming switch m25 that dashrath will look at one time from elements present at all the Vice President Was Presented To Know What You Were Looking In The World Channel Subscribe Now To All Present In The District In Scheme Of Quilling Note 3 Not Doing Better Than I Will Not Nil Subscribe Computer Element Which Element President Will Continue To Check 1212 98100 Free Element 110 Abe Connected Off Way Safari Element One Can Get Connected So Way Can One Connect Two Three Look For Not Present in the Land of the Length of the Answer Will Return of the King Is Back to 16 Elements Who Did You Know Quite Similarly One Piece of Mind With Nod to Speak on Western Wear Look at Chanel for Weeks But Similarly Captain Ignoring Twitter Ne Ignoring This Element Hair Suvvi Cover All This Eliminates All Redmulser Part Of The Same Change Ladies Scientific Nordham Liquid Account Below Us Apni Delhi Will Count And Similarly 1.05 Separately But I Count And Similarly 1.05 Separately But I Count And Similarly 1.05 Separately But I Miss You Will Keep Continue Roadways Bus Stand Silicon Tolly Once I Will Account For Lifestyle And Starting From One To Give Power To All Elements And Once Again Save Sometime Subah Dad All Images Free Battery But Will Consider All The Elements Yadav Connected To Relationship Arrangement For It Will Not Waste Time Online Poker Online Apply For Ruling And Opposition Leaders Will Change Your Destiny exit is senior notification navodaya result snowden intersect means it's good things will work for change noc service started looking for the china 1999 and wear look what is the present tense not present element single element mid search the answer is not present at the event will Rule 90000000 Not Present In Just 120 Days Paint Welcome Par Keep Answer This Great Hindu Sorry Renu Winters Ignore Balance To This Report Got Varun Service Six Subscribe Our Approach And This Point To Take Off The Subscribe To's Playlist Has Been Ringed And Then OK in this particular case vihar to first form declares state in which they want to release that were looking for elements in the oven timed and simple dhel images of the weather in to the point let's all elements dot in delhi over click on current elements And Subscribe Elements Thanks For Flat Se Real Looking And Three Light Bill Tried To Search Kuttu Jahar Ignore Three Wicket Spinner's Meeting To Attend Of Will Count All The Values To Win Three Wicket Spinner's Meeting To Attend Of Will Count All The Values To Win Three Wicket Spinner's Meeting To Attend Of Will Count All The Values To Win Or Counter Aggress Nuvve Cutting Half Lens For Purchase Of Change With Me To will include them in the students who deals in this will strive to draw previous limited to it's ok search previous elements found no satellite so it's third point previous element subscribe Video free mode to turn on this is not able to find no place for elements In a special start China MLA's lips routing photo in tears to start from 100MB left side change from 3 will guide you Sachin for free s possible Play Services search software center change conscious next element of this map laddu question tunes start point current element is OK Khel Not Withdraw 1033 Subscribe Like Comment Share And Increasing In 12th Class 12th Previous Record Label It's N Apart Answer Visible After All This Answer Is Equal To Max Of Kar Undertaker Vs Contest Se 021 Lakshmi Ka Ras Ko List Spinners Ki Half inch midding from gold problem among western brothers real transparent value will return to that our design latest submit nc vision and gift world updated on that sudarshan accept girls reaction right side thank you for being patient andar salim
|
Longest Consecutive Sequence
|
longest-consecutive-sequence
|
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
**Example 2:**
**Input:** nums = \[0,3,7,2,5,8,4,6,0,1\]
**Output:** 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Union Find
|
Medium
|
298,2278
|
137 |
1:37 single numbers to give me a non 1:37 single numbers to give me a non 1:37 single numbers to give me a non empty array of integers every element appears three times except for one which appears exactly once find that single one you algum should have a linear time complexity could you implement it without using extra memory yeah I mean in general I don't like these kind of files without reason but uh let's see uh yeah this is some kind of crazy XOR thing again a lot of people like this one though but that's maybe because they have a clever solution which I about let's see what does it mean for a number to appear three times well two of them cancel out and I'm obviously try to do it with well in or one extra space yeah I have to sense that it's gonna be some clever XOR thing but yeah I mean I just want to get it I mean these are the type of so earlier today I was talking about like back in the day you would see clever II program II brainteaser stuff these are the type of problems that uh I think like ten years ago you would get on interview sometimes that's okay so I think nowadays people are slightly get at least in their trendy part of you know circle while you type things so I don't know if you know like cuz we talk about Midwest and other places so they might still use twenties or evenings but like two ten years ago like definitely something that you in New York could you see a lot of these pointy sou things way like oh yeah just do some extra trick like it's less and less because it seemed no but yeah I feel like these are problems are like not very useful per se like XO charts I mean it's fun as brain teasers but I don't know if it's super useful and I mean I guess you could make to our informant program bombs so maybe that's you know a judgment or whatever but okay so I've been playing so you can't just EXO happy right really I don't even have a great dog processes I'm getting through this to be honest a little bit I'm just like my first toy is just X owning everything or in some way to partition the egg source which is not super useful I mean yeah we if you saw everything then the two of them would tend to out but you still have you step essentially the entire list XOR which is not super useful maybe oh yeah I forgot the cone coda naive solution that if I'm an interview I will bring out first of all is that you just put everything hash table and I mean I know I got to describe that solution too much but well but on it but I just want to point out that on an interview I would definitely still point it out because you know as an interviewer I don't assume people even know about hash tables because they're people could don't to be like so I as an integral II like I would pointed out just to kind of make it you know make it clear that I know that's a thing but obviously it takes off and space and so like you know and also make the palm trivial and so forth but yeah but I was still pointed out just in case yeah I mean I think people have gotten better over time and he said like phone screens and stuff like this but I think like in general a lot a good amount and if you know hash tables solutions and like you know really ahead of a lot of people I mean it's not sufficient to do well in an interview like give me a lot more than that but there's a lot of people who do not just to be frank so it is what it is we're just you know but okay I mean this just like the type of problem that Phoebe action was talking about maybe earlier where like it's so binary where'd I go I'm just like running full of sand the arrows in my head I don't like where I'm one including them and I'm tossing them away with argument you know so it's just me not even talking about me because it's so weird but a linear time which you only go for the same away like you know X amount of time extra memory which is kind of yeah definitely yeah I think what I think about it so one thing that I would mention is that linear time does buy you some hints so there's a lot of in the sense that you know there's a lot of restrictions on what you can do right and what that means is that well you know like one meta algorithm you want to call it that is just like multiple paths food away in some way which in general requires additional memory whether it's constant or you know cause if you do multiple pass and you'll do anything then like I mean well I was so like I think like the extra memory is also a little weird yeah but I think the extra memory also like facing is a little particular like I wonder if you could like edit stuff in price because if that's the case then like maybe that's a our a hack but like for me that still I don't know that's like a low-level don't know that's like a low-level don't know that's like a low-level optimization but not like I don't know no I don't like it in general I guess is what I'm trying to say so oh yeah so yeah one of those is off n is just going through the list multiple pass another way to get out of n is having to or I guess in theory multiple pointers where I give a window finger.you algorithm well you know finger.you algorithm well you know finger.you algorithm well you know you're scanning it that way but and then yeah and then you kind of because you're doing that it sort of end because you only have you basically doing a for like a pass but Co currently with some like offset that's also end time so those are the two things that I'm thinking about how did use that is another story obviously and I can I think I want to ask for a hint and only in the sense that in a sense that I don't know if they like it I don't want to waste so much time to find out that extra memory means that we just store stuff in place in the input away because if that's the case like that's somewhat cheating I mean I don't know you describe it cheating or whatever but then like because you could do that in place or not in place another way would you come over and memory or I don't like it's all one extra memory but it's still open memory I want to say like it's the size of the end point I don't know and someone so that's the question I would ask because if that's the case that changes a lot of things like that we could play around because I generally don't like yeah I mean I know it's a hint and that's what I would kind of like but it's both a hint and a clarification I feel like if I was in an interview then that's it's what I would ask to be frank I'm like hey can I modify things in place because sometimes that's a restriction and in general I prefer not because I don't know like I'm is more functional I guess but like you know that changes things because essentially then you know like you're doing of and space anyway because maybe you have to be clever on like certain things but yeah I don't know well I think there if we could figure out a way no I mean if we could modifier in place I think I have a no event algorithm wait is that true yeah if we come out of five things in place I have a no event algorithm I think maybe no maybe that's not true then think about this for a second I think of some like 2.0 thing but maybe I think of some like 2.0 thing but maybe I think of some like 2.0 thing but maybe that's not true maybe I lied so one thing to think about is like maybe some kind of wanting X or type thing yeah what a weird ishbal oh because now you get to see me struggle team your poster wet hmm well the zero is also a little tricky to handle as an educator possibly and we have to think about it why not hmm yeah it's also well I was also saying like it's even worse than algum problems it's almost in its binary so maybe I guess it has more relevance Turner and the other one with the Murphy one but uh oh yeah I would say it's a no spoiler alert I also did the similar thing with single number three where are you sent you like point around with it and then essentially some just at an answer and then kind of got it so I am afraid that uh if I end up this way so I don't know how much explanation I could do what before I get the answer like there's no linear path to the answer which is kind of a little annoying to make progress on and also is this is even worse T and I want in the sense that like once you get it you probably get it just like a brain t like exactly a brain teaser I just want you know word you know but uh can you running mixer what does it mean no that doesn't make sense okay well if you do an X or you century cancer so yeah one LM but you need to know that is more than one now I'm trying to think about like what does it mean at the enemy so no just 2x or all the numbers so because I'm so this is like similar to one arm or my current thought process is just similar to what I was trying to do single numbers to worry and see if I could learn something from dad but like maybe not cuz in that forum you take a bit and try to figure out that way okay I'm gonna for now assume that you can do some in-place editing of the can do some in-place editing of the can do some in-place editing of the input away so what does that change for me here well what hmm and you can't do it twice cancel things out whether also cancel out to the number you're looking for hmm well it is well that's okay well let's look for the examples maybe I could figure out that my end of it that's crying through this a little bit yeah two to three twos and in binary just ten tenth and your lovin how do you so the X sorry it's zero one right yeah it's a creamy next door am i it's just like one of those great earrings so these two could oops these two could cancel out what does it mean hmm okay and that doesn't make sense well for I would say if this is the case it is a binary form I think the one thing that you could try to think about it's just in terms of bits well I mean that's what I'm doing but I mean like one bit at a time and what I think is what does this mean well so what is a zero mean in this case because and this may not apply to the more general case I'm glad I think and I'm glad I could you know I could show some empathy toy here situation but on oh yeah this might not be general but for so maybe there's something but for it to be zero that means hmm tell me that isn't necessary mean much maybe because if I do too you know something like that and that these Cantor's on we start the same exact same number 110 yeah this yeah I think one thing that mmm yeah maybe one strategy I don't think about and it's something that we talked about earlier is that maybe I would try to do something that's not linear and then see if we could kind of optimize it to be zinnia but I want to do it without extra space so okay so it would just an over N squared yeah there's a trivial n square algorithm where you just kind of go through it see if it even appears twice that's all you need and you checked it for each element right okay so it's at least I would point that out I guess but it's their way to generalize it yeah a lot of this dream with this form which is coming me with a Paxton face no this is only a medium to I guess it is what it is I feel like also for a lot of these prompt people have seen it before as the years ago oh my gosh is this which is maybe fine the only other thing I would think about that's not related to pay to some kind of some numbers relating to the sum of the numbers maybe yeah for now I'm okay yeah just thinking about one I mean science meeting to chat yeah and I hope that yeah I mean sometimes you like I was saying earlier sometime you just get unlucky and that's part of the luck is that you know just knowing the some of their way to buy me anything hmm I mean in this example a desperate and I'd like in a general case oh yeah well something like that I'm just thinking about this um situation can we do something with some maybe not she's still trying to figure out like two odd number out but they're odd numbers of the other ones and there's no easy way to change the parity of that thing why do people like this one so much I guess when you see I would say if I'm interviewing I hope I don't get this far though maybe after this I would just remember the answer and you know but uh I'm quite I did not see this before interviewing or whatever or the other way around and there we going before saying this but uh in terms of X or all these taboos cancel out so I don't know how that buys me anything I need to figure out a way to subtract two of these hmm Oh ah sorry don't you make I am I might have with I interpret what you meant by the general version of just pause okay times is that huh no I don't think I've solved that well with K is even I think it's trivial right but if K is odd but just like in this case we'll just have to bomb I guess then well that's what I'm trying to figure out that what K is even like the XO trick works this why is trivial X is odd then Orton tears outside yeah then we have this problem which i think is the same as nothing like that all the same of ksi maybe I'm maybe 2x or is just right airing and I'm like sweating with Dicker's amount of time in it I mean I decided I'd uh I mean it's I just some more excitement I feel like in some weird way because like what else can you do and then your time and we decided maybe some kind mmm and you can really like double some of this stuff my family oh yeah I mean and I think we always kind of talked about what you might yeah but usually a hash-table better and yeah I mean I hash-table better and yeah I mean I hash-table better and yeah I mean I guess the code per se cannot really yeah they can't check to see if you haven't used extra memory other than complaining about it well like you just get a bad percentile or whatever and so I mean but like you know but uh in this case the center gives me an EXO of oh one which is what we talked about on you that doesn't tell me anything right because that's just the same as this right so I don't know if I could and this has to be something really quite away because these two palms maybe that's at least an insight these two problems have the same X all right so how do I differentiate between them no way around this some maybe oh yeah I also agree with that because I think you could reduce their pay is you go to add case to this and then that's standard ish maybe I mean busi but happily and kg goes even is also uh I mean we already talked about it come on time so well how do we do this in a good way well you can't even you can't get to this easily so can you take your furniture some will understand I'm tell you mom is a 91 Lucille 2 I'm not saying you subtract us really tell you anything about the rest of the suffix I'm still doing sell for the next egg so I mean I was thinking of something like a conquest thing yeah I mean I would definitely start like just hacking on random stuff for sure if there's a min interview maybe I'll just do the n square one but then like try to figure it out a little bit more can we do this bit by bit can we even figure out what the bit of the final answer is because we can then like you said we could do some oh love with x and thing like in this example both of them have the same bitwise and there's no easy way to differentiate between these two well do you know that the answers 1 well worse on the one bit thick so these two are the same so there's no way to differentiate the last bit is zero one is there well maybe a good cow no Kenya well in this case you can print maybe not Jeremy no I guess you can maybe that's it but yeah I think you gave me a great idea but yeah okay yes exactly no I think that's exactly what yeah I think you gave me the idea of the weft times n and I think just counting the number of I mean I don't know what I mean by maybe well me because of one extra memory or like literally one integer right and just do a bit by bit is that consumed cheating I don't know or like that's you know it's that good enough like the tray one wearable that's how you would do it yeah that I mean we have I know like we arrived today in this century at the same time where you sent on both times end but yeah because this I'd oh there's one bit left over yeah I mean there was about three essentially sorry yeah I mean that's off the farm did but it's all one space good ok well that's better than nothing at least I think similar to oh man maybe that's I mean what you said it's also true but now actually well now I want to think about maybe not XOR but instead looking at things in a binary maybe we could look at it in trinary ternary Kristine in that case yeah because in that case in ternary you sum up all the things in that base or in that digit in the ternary weapon tape sanitation we're saying the same thing lovely maybe and then the mod of that is the answer for that digit I think wait is that obvious it was some advice to me no I think I have two right answer though tell me of a funky or like working forward I mean I it just take all of one extra memory which is like one where well I think you just count - uh yeah well I think you just count - uh yeah well I think you just count - uh yeah because okay so you look at a base right let's say you have base K which is in this case three actually not K but yeah base 3 then because something appears to be x you'll always be dirty by three except for the number that's left over for that digit right so I think in that case I mean that's I think that's the answer which I think now - that's the answer which I think now - that's the answer which I think now - was talking about and I think we came in and exactly the same time wealthy I'm gonna stand by maybe you did a little bit earlier but I didn't look at the chat at that exact instance but up and I think your weight which is stand like okay let's look at all these add paste were doing some talk about Roy maybe I'm understanding that particular piece there's something by - is so nice but so there's something by - is so nice but so there's something by - is so nice but so I have this somewhere and this so what does that mean I mean it um not sure but I mean type yeah PD action I'll get back to you in a second I think I mean I think I have a working solution it is all of one solution which is that okay well let's look at the last digit wait which is that stitute of a pastry number I mean I don't know if that's going to work but we could I mean I have a working solution now I think which is you looking so Fe uh yeah well go for it I just want to because I have a working solution I want to get this out and then we'll explore that engineer bread is that okay I just don't want to like half focus on two different possible solutions maybe I mean a lot of these farms have multiple solutions probably to be honest so but yeah I don't know but if you look at you but let's say you do take a mod V which is the last digit of the number then you sum it all up on the one digit by digit maybe that's what you man I misinterpret it but with some 1000 up that digit is the first digit on the base tree of the result I think that's why because it reappears n times or if that digit because if every number on a based we-we shows up three number on a based we-we shows up three number on a based we-we shows up three times then by definition the sum of all those digits would be you know zero right my tree except for the number that for you only once so that's what I think I'm gonna do just a base three yeah so that's v times I okay I mean it's all one extra space but I think it's me I have no dimension one gave me my extra memory maybe we could put it somewhere but uh but it's at least we have an all of one extras a solution like yeah I mean it's a bit ya know I'm super convinced this works I don't know if this is extra memory corn quote but oh yeah maybe I like I'll let y'all work on that other possible path while I do this okay how did I do this in a quaint waiter it's ten you have to like okay uh yeah let me work on my solution and then we could play around with another solution I think I got a one that tests all one space so I'll just do it that way I'm not going to try to fit in one we're above it what do you mean by extra memory this is not good enough I mean I it's a solution that I still like the answer to even if it's not good enough so I'm where that's why I'm we started we did you say yeah okay you know say nope that's just you're so terrible since we're already using more memories I know you will need this then um okay why am i doing no I can't do it this way because I'm modifying you them I'm almost modifying things in place I don't in fear we need to it just makes the computationally order commentation easy because you could do some more manipulative math to get digits of a number though I mean we could talk about yeah actually I mean it still uses the same number of space it just takes more connotation for each one so I don't think I'm worried about that per se well okay otherwise it's um okay am i doing okay so some of the teacher this dad stuff this time - did you place and did you this time - did you place and did you this time - did you place and did you shift enough and turn the area someone like that maybe that's enough maybe I'm missing by a little bit but ok oh yeah switching languages well maybe ok I shift this little bit too early I mean I'll still say I hate this one even if I don't know what then yeah can you tell without actually any extra space yeah I don't know but I don't think so degree matters I mean it's going to do a bunch of stuff what do you mean by index sorry let's just try what number okay and this stuff is just yeah like I don't need to find this in place I could do some shifting and what division as a result I check apply just change this to define the digit price and then get the mod good well yeah so that's not I don't consider that excusing extra memory what you've been cheating yeah okay fine I'm just doing it maybe and maybe doesn't terminate because I changed something oh yeah because test doesn't terminate oh I see what you mean I wasn't I was reading about in what it cost what you meant yeah anyway you need to index so you can talk about the tree any it's just my UI okay so this is Tim okay y'all know let's submit this it took wait these point is oh man oh this negative numbers I hate you well I mean we could fix it's not a insurmountable but Wow [Laughter] maybe there's a more clever a solution we but as a result of that you still XO for like X or e thing for crazy century we're just doing stuff with like a nine binary representation of numbers pronoun oh my god how did I do this I mean it's not impossible it's just yeah it might it just makes things really complicated because a lot mind is negative for some stuff for example I hate you and everything you stand for they come hmm can you mind fire usually yeah because it takes them because both these could be free in the answer so I yeah and this is destroying my mojo a bit also need to use the restroom again enjoying you too much of this milk tea when that baby will sleep but uh maybe we do have to do something place for you in that case just to make it easier okay maybe I'd stop to think about the negative numbers which I don't think I do I bring this society I mean it makes my ending condition I was a wah so well just like adjust to this actually uh I mean I think that's what I for the first half of the me trying to solve that's what I was trying to do by can't point around the bits in binary when you look at the ternary which is kind of what I'm doing well it is what I'm doing you know you because everybody appears to be at it at a place they can't survive no matter what the digit is right so that's how I'm trying to do it now I'm just trying to negative port which is kind of annoying like I think this is right for positive numbers but now I have to figure out like yeah modifying just the wine area I hate everything as promised also what why is this different than my other output did I do this really I chased this part of the code which I guess is you know okay I mean it's fine maybe I have to double check this as an ending condition - his compliments tough to request - his compliments tough to request - his compliments tough to request Explorer subtraction uh yeah sorry my brain is like toasted on this one now yeah I mean yeah I would say to post a where to point I do I mean I like this I like the solution to this want to be honest not gonna lie that's it okay is that still that right and I start to figure it out why is it you have negative numbers and I should think this is a cool climate problem not for interviews I don't think it is an interview farm but here's a cool brain teaser otherwise but uh but now I'm naked numbers got me thinking how do I handle it well I guess you could just count the number of negatives can you yeah I guess you just kind of double negatives if it's 7:10 its negative if not and you it's 7:10 its negative if not and you it's 7:10 its negative if not and you know and then you kind of accentuate what you were saying PB actions were saying with two's complement except for this is like threes complement in so okay well now we do you think more variables bit no I think we do you on that point we're committed I mean maybe some other finagling I have to do it's fine negative not simple and really do you century and sir is something like did you its negative someone like that oh this - teacher maybe take this - teacher maybe take this - teacher maybe take this time story but it ok you start really right there let's just try a lot of negative numbers took this is why for the other ones because this is not gonna be true I shoved out there we go that's kind of cool but I forgot my other number I just want to keep it up I should put in a text pad somewhere everything right now but uh yeah great to have your PD action but uh huh well I don't do any modification I changed dad actually I mean I don't know - what - our album is but I actually - what - our album is but I actually - what - our album is but I actually changed it to not I mean I initially had to use modification but we look at the code now there's no modification you know for better or for worse okay that's just the one negative numbers just in case and also acted quite test0 just oh well I mean the negative is just if you will another I don't know yeah I don't know but I would love to see that answer maybe well maybe this is the first time I put tradition and don't get the discussion forum together and we could talk about it afterwards that's your longest come on okay huh I mean it's a binary frame we could talk about everyone I mean okay if nothing else we got an answer that works in you know like we were saying linear time times there are don't number of ternary bits or not bits I guess they're not caught but turned area digits which is you know a lot of three or I don't know what the biggest number is but log of 3 of 2 to the 64 or log base 3 of 2 to 64 which is like say I don't know 50 or something like that I don't know someone calculating it to it I would just forget me about to attempt a C la-based we 2 to me about to attempt a C la-based we 2 to me about to attempt a C la-based we 2 to the 64 yes okay that did not tell me anything I guess lager 2 to the 64 time stuff whatever it's less than 64 away so x of n so yeah so that's linear for some definition of linear and yeah and we use constant number of extra space or one extra space yes oh yeah 32 so I said 64 because I'm swinging table was pretty oh right 32 for integers for sure less than 32 excuse me I mean you get a better precise number but that's fine because it's not to worry because this is a lot to be operation but and we use all one extra space I don't know Jason extra memory one maybe we'll look at it together just for me to learn because we spent a lot of time this farm for me not to like it's gonna bother me tonight how long do you spend as well uh Wow one was an hour dang and it is just a medium I don't know if this is like a gnome solution that you already know the answer to maybe that makes it easier well maybe I don't know what C I'll take a look in the second album for me I could clean up to code a little bit with them but I think I use reasonable variable names in general here maybe I could pick some stuff up the wild loop and like make this a particular digit or something like that but I think that's okay yeah and yeah I don't expect us to very and I don't expect this to be an interview poem if I'm wrong and well now I know the answer or one answer and we'll look it up together nobody ever lends it to maybe Python because this is a penny pretty slow so yeah it happens I mean it happens sometimes like we definitely like given me some times I will get the fan so I'm like I should know this but I'm having a brain fart or like cranking out on it this is I don't feel like this is one of those forums well maybe I see a solution it that we'll talk about maybe I do so you know hold my word to it but uh well yeah ah as a medium I don't know it's just one of those brain teaser things where like if you know the trick it's fine like ten lines of code like now two is saying but like I don't know if it's useful and or whatever but uh but yeah I would never ask you something real problem it's a brain teaser so I think I've like I said earlier I think I've seen these kind of problems before similar maybe not just one clearly not just one but you know it is what it is I don't know I think the difficulty is just decided by whomever voted upon and kind of you know and these things up especially for these points this is one it's very hard to kind of Concord grate them correctly because I feel like a lot of like it's very binary right like or bimodal where like I feel like a lot of people know the trick because they've seen it before and then they're like solve it immediately or like we don't then you may or may not you find you get it so I don't know let me look at this guy's far oh man this was supposed to be a short one yeah oh yeah it's very subjective so I don't know we'll see I mean I now I posed to path some way do you mean single numb some to your single numbers three or whatever is you mean fashioned way we have to the third version of this problem there's also a medium but I got that because it I guess that one is more binary I forget what the exact problem oh yeah just two different numbers I got that cause I was binary and Ike was stuck on the binary mode for well maybe there's still a binary answer so I'm going to look at it with you guys so we'll kind of see it um I don't know I mean I ain't no I mean I end up doing him yeah I well I mean with no extra memory if you could do it Oh linear memory then hash table is the obvious answer wait sorry yeah I mean my - dad I don't know sorry yeah I mean my - dad I don't know sorry yeah I mean my - dad I don't know all right buffer - dude this is the all right buffer - dude this is the all right buffer - dude this is the first time I've done this on stream where I'm just like dying to know the answer so let me go Wow - discussion answer so let me go Wow - discussion answer so let me go Wow - discussion forum with y'all and then kind of see where it goes oh there is a bitwise number so I can K minus one okay like each bit in the calendar so I'm just gonna read it really fast as I can just start look at one bit yeah um well M has M bits in binary form wow this is a lot of reading man it is midnight this is the time for me to eat this right now what is M each pit in the car well okay now look at another one maybe that one just so long challenge me thanks wow there's some stuff about turn Aries maybe not maybe I without reading the description let's see we start at zero he looks through all other ways but just disarray and they're not twos and not once yeah I mean I think this is just yeah I mean I guess like I mean I don't know the exact mechanics out to go sit down and really think about it but I guess this is just keeping track in a way of like it like in a way individually keeping track of pace from yeah like base three and in each like kind of what I did except for like all together using very clever bitwise operations that I don't have to scale what thinking too I mean I'm not gonna read all this but that's my guess and yeah I mean I would have to really think about it on a day where it is not midnight but a general way tend to yeah well I mean I think this is oh I see I think this is fair I think this is what it is saying okay that's actually I think I get it now kind of I mean not in a good way but and you still need a lot of different states but basically it's still similar to what I mean it's similar to our idea except for that like it's basically the general concept with these forms and you have to design you know like a circuit that makes this true but essentially you'd have to design your new not an XO operator but like an operator that counts big not bitwise but in base M for whatever bit in this case is based way when faced we you have to go from yeah I mean kind of what this is saying right which is that let's say your current count for a digit if you will is zero and you get something that has one or two and then you kind of keep on doing it repeatedly and then and you kind of design and if like a they hear they got a bit circuit but which is kind of I guess it's related to kind of a logical operators circuit and then kind of just do it that way right and it's kind of actually this is exactly what we do except we because we don't do it at the same time like we don't do it at the same time we're just doing digit by digit but if you do it and this kind of you know crazy bitwise function like if you do it that way then you do it all the digits at the same time in parallel kind of because at the century or every digit moves up zero to offer some previous state and then it goes to whatever it is might three like it adds that digit with foot input number and then March it by you know I think the idea is converting just have a scratch pad I guess but like but basically the idea is similar to what we end up doing but basically you have you know an existing number for a in a digit X and then you add it to an incoming number of a digit let's say Y and then you might that by three and then you store it into the new X and then you kind of represent that in an operator generically I guess and because you do it in bitwise functions then like it allows you to do it all at the same time because you could think about you digit kind of counting it at the same time but I think I to be honest if that's to you know I think the way I did it I like it more I don't know if I like it more but it feels more intuitive to me and it also scales to whatever base it is you just changed it to worry too and for whatever and it is and it's you know and it's fine and get to do the negative no more attraction looking back it's kind of cool you know I'm just frustrated at the time because I still was trying to figure it now but yeah uh I don't know he's dead does anyone have any questions I don't know I could explain that much better but may say what they do is I guess the solutions in general just have I mean have like a finger of each digit is a state machine dad you know I have yeah like a state machine from and you have n minus M minus one state where m is the base that you're doing or in this case is 3 so you have to in this case the three states where like the state s 0 1 & 2 and independent incoming number or & 2 and independent incoming number or & 2 and independent incoming number or digit you go to different states right and I think oh not this one not this solution but was it oh yeah and this kind of distribution arises for me it's just that like this is a way to represent all those big transitions and incoming and so forth I mean that you enjoyed in coming here and kind of like keep track of it and this is just I mean using a and B but it represents is just but this just represents the number three or yeah and I'm we're using two bits right so like it's you centric what I was doing example they're doing because they do it but bits they do it in parallel which is definitely faster and don't get me wrong by an order of a lot three times or someone like that way or a lot yeah a lot three of the biggest number or something like that or the number of digits in base and but I don't feel bad about how I did it given though I took me a while to get after that so yeah so people did too there is a binary cone called binary solution but it's just a binary way of encoding a base end solution right so I think like logically it's the same I want to say even though they clearly better like the way they did as a career better solution to get me wrong but like I don't feel ashamed doing it without the way I did because you sent rejoined the same state machine except what they do things more empowered like if you want to think of it definitely maybe I could have yeah I don't want to think about it too much more to be honest it's been like an hour and change on this one but uh but I think a little bit of a post-mortem think a little bit of a post-mortem think a little bit of a post-mortem because I don't think this should be in any way bombed but instead a crab done this faster my I should have thought about I mean this is more mathematical I think so maybe it doesn't for that reason it's also not you know like I was still trying to think about something binary years we sold and I don't think there's an easy way to binary uh yeah it just yeah they're solution also like it's very specific to the fact that this is based way right so it's not a generic solution at all we're miners I mean you have to you know change some magic constants but mine is a generic solution I think Lenny pace that fits an int or whatever but you know that's always gonna be you know an issue anyway but yeah but um no I totally forgot I was gonna say sorry what was I saying oh yeah post modem me how do you think yeah definitely should have thought about things in different base more I think I was stuck on just thinking of pure binary and there's I mean it turns out looking at the solutions like there's no way to do it in pure binary at least not no way to do in binary it's just no way to do it thinking about it and binary I mean their ways are just in like their ways were encoding like I said encoding the number and in binary and somewhere and then kind of figure out the circuit from that which is it's cool and pretty or whatever but just maybe some way I could bring up an interview I think the way I did is probably more intended so in that case it still took way too long and I should have my thing I mean I think like you know y'all with me for a while little while so I think I was stuck on the X or thinking a little bit too much as it turned out it was in the red airing and inherent in that XOR is that is based off the fact that is a binary representation or base to specifically which is my binary means but I want to say that in a way that is more general and if you go back like looking at this generic solution and if you change to three to two it actually still works right so it actually makes sense even in that case so yeah so was it say about that so in that sense EXO it's just a very clean operation because you know even if the way they did it you could rewrite X or to like you know well X or you could write it myself but you change it to like a series of if statements and not statements right so in that sense like an X or just happens to be what comes up a lot in computer science officer is it easier and cool way well I think it's a point you say I really like this form though because it forces me to kind of think about why X all worked for binary and stuff like that and now I feel like I definitely learned a little bit about this type of form I don't know if it's how practical it is and stuff like that but I might ever like it's an interview question so maybe in that sense I would end up giving it thumbs up you know I kind of hate on it earlier but that said it's an interview problem why still terrible so I would recommend it but I don't know you need to know about it I don't know what you can do about it sometimes you can't prepare for every you know everything right like every point is you can't prepare for all of them but I'm glad I did this one but I would hope that I sign into good question because I feel like you don't really learn about it much like if you've seen it before it's great and it did take me I mean I guess I got into adventure so maybe I could have been a little faster maybe if I did it interactively with an interviewer they would poke me a little bit like now don't think about it in X I like it and I would spend less time maybe I can squeeze it in that way and the coding is kind of well it'll be quick after that but uh
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
796 |
foreign welcome back to my channel and today we are we guys are going to solve a new lead code question that is rotate string with the help of python so the question says given to string s and Gold return true if any if and only if s can become gold after some number of shifts on S a shift on S consists of moving the leftmost character of s to the right most position for example s is equals to A B C D E then it will be pcdea so uh just so for starting to solve this question guys to subscribe to the channel hit the like button press the Bell icon button and book maruti playlist so that you can get the updates from the channel so I hope that after reading the social many of you understood this question but if you still not have understood this discussion let me explain it to you with the help of some examples mentioned below so the example number one says it's a true so how it's true because if you shoot some characters off even if you shoot some characters of s it will be it can be converted into a coal like if you shift to B here and E here first of all if you shift this into this you will be getting the gold you can see c d e a b and if after even after Shifting the values however you can see even after Shifting the value of s you cannot get the goal because the sequence of the characters here is not uh equal to the goal Okay so let's start coding this section now and to do that let me explain it to you how I'm gonna solve this question so if I return Gold Plus gold what I will be getting here is I will be getting um let me write a comment here for example number one I will be getting c d e a b so uh as you can see this s is somewhat between here a b c d e right you can see so this solves our problem here and how now we can say that return uh LAN but first of all we have to check that both of these lines are equal so if they are equal then we can move further land gold because if they are not equal we cannot say that we can rotate it not for in the on the first moment we will say that we can they are false so first of all you have to check their length are equal and then you will be seeing that return uh Lan s is equal to Lan gold and uh we'll be saying that s in this Gold Plus gold so I will just take this value and paste it here and just remove the return from here and this solves our problem and if I run this code now see it has been running successfully so this was all in the question guys I hope that you understood this question and if you have not still have understood this question please ask me in the comment section I will try to sort it out thank you guys for watching this video and please do subscribe to the channel and see you next time
|
Rotate String
|
reaching-points
|
Given two strings `s` and `goal`, return `true` _if and only if_ `s` _can become_ `goal` _after some number of **shifts** on_ `s`.
A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position.
* For example, if `s = "abcde "`, then it will be `"bcdea "` after one shift.
**Example 1:**
**Input:** s = "abcde", goal = "cdeab"
**Output:** true
**Example 2:**
**Input:** s = "abcde", goal = "abced"
**Output:** false
**Constraints:**
* `1 <= s.length, goal.length <= 100`
* `s` and `goal` consist of lowercase English letters.
| null |
Math
|
Hard
| null |
1,736 |
hey everybody this is larry this is day uh no this is q1 of the latest weekly contest 225 latest time by replacing hidden digits um hit the like button hit the subscribe button join me on discord uh my energy is a little bit low today because of some situation with my life um but you know let's see you know this is my hobby so um let's see what i can do here uh let me know what you think of today's problem for latest time by replacing in digits so this one is a little bit uh straightforward if you just do it before us i think you can do this in a greedy way but the problem of doing it in a greedy way is that um you just have to prove it right and during the contest i was a label lazy about proving it i think the key thing to note is that you can actually i mean that's not a key thing to know because i didn't take advantage of it but if you wanted to in a more efficient way note that you can actually separate the hours and the minutes um but again you know they're 1400 or 1440 or something like that minutes and a day so knowing that i just perforced it um and my code is actually kind of messy especially for q1 but hopefully the idea makes sense i have a padding that just basically adds to zero i think you can probably write this in a much uh more pythonic way but i wrote it this way because i'm i don't know and then match uh is just matching two strings where uh the time component might have a question mark and i just make sure that you know uh the question mark auto matches whatever the x on the side but otherwise from that as you can kind of see i brew first the hour and the seconds and basically i you know i get the hour and the second and then you know that's pretty much it um we could talk about complexly but as these are two constant loops uh this is gonna be over you know 1440 or whatever which is all of one maybe um but this definitely does not run in um you know like it does not vary depending on your input so this is all one c time in terms of space uh you know you're doing it in a smarter way you say uh you can definitely do it in constant space uh technically i create a lot of strengths the way that i do it um but even then it is quite constant space because at most there are like 14 40 strings times two if you want to say that i copy over them to best every time um but yeah um during a contest i'm gonna opt for writing it as quickly as possible um at least in a way that is um not as many edge cases like as few edge cases as possible and that's what i did uh let me know what you think you could watch me during the contest next slowing on the clicking button hmm hey everybody thanks for watching thanks for checking out this problem let me know what you think let me know what you're running into and i will see you hopefully next time bye
|
Latest Time by Replacing Hidden Digits
|
build-binary-expression-tree-from-infix-expression
|
You are given a string `time` in the form of `hh:mm`, where some of the digits in the string are hidden (represented by `?`).
The valid times are those inclusively between `00:00` and `23:59`.
Return _the latest valid time you can get from_ `time` _by replacing the hidden_ _digits_.
**Example 1:**
**Input:** time = "2?:?0 "
**Output:** "23:50 "
**Explanation:** The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.
**Example 2:**
**Input:** time = "0?:3? "
**Output:** "09:39 "
**Example 3:**
**Input:** time = "1?:22 "
**Output:** "19:22 "
**Constraints:**
* `time` is in the format `hh:mm`.
* It is guaranteed that you can produce a valid time from the given string.
|
Convert infix expression to postfix expression. Build an expression tree from the postfix expression.
|
String,Stack,Tree,Binary Tree
|
Hard
|
785,1750
|
664 |
64 string printer so there is a string printer with the following two spal properties so the printer can only print a sequence of the same characters each time at each turn printer can print new characters starting from the studing form and adding at any place and will cover the original existing characters so let me just explain the description about here so we are having a pror we going to print out the string a BBB so how it going to print it can print 68 at the same time and then in between it will so yeah this is the still a and then it will cover some a and then this areas will become big so it will be the minimum of two times yeah so this is the definition of the description it means yeah if you print some letters so for example a but in between you can also print a b if you want to get a string of a and this is a difficult problem yeah we have to use some examples to explain how can we solve it optimally um so I'm going to try to yeah F some examples so for example we're going to print out this like a b say a yeah so for a normal case if we just want to print out three letters a b c if there's no this a at the right side so how many times yeah if all the characters are different so it going to be the three times so minimum it going to be three times but what if at the end there is a character that is also the same as the first character so it going to be three times yeah so this seems St yeah but it is also straightforward because the greedy idea is yeah so for me if I just print out a letter A so why not I just print out all the letters for a here and then in between I will covered by a b and c and I get the same result yeah so the greedy idea is from here but actually for solving this problem grey idea is not enough we have to use the dynamic programming yeah so this is the difficult part because it include gy and it include dynamic programming this that makes the problem difficult yeah so that is one case so for the letters if the first letter equals to the last letter what it going to be so our definition for my DFS IG is the minimum of typing minimum of turs for typing the characters from I to J so for example from this a to the last a it the DFS Will T the minimum time but what if the first letter equals to the last letter it is both a yeah so for this situation actually we can minimize the problem from I to i z minus one but it will be the same so this means this DFS equal to DFS I to Z minus y yeah but this is not IUS one why um let me so this is J minus one but this is not IUS one yeah because there are some testing cases we can prove it yeah because if we would if we have the same character normally we can save it we can just save it because later on we're going to use this character definitely we going to C it as one time but we cannot C it as two time so for example if we have 3 a yeah if for DFS I to J if we just go to the first and the last character so it going to be yeah DFS i - it going to be yeah DFS i - it going to be yeah DFS i - one I - one and Z minus one + one yeah one I - one and Z minus one + one yeah one I - one and Z minus one + one yeah so this going to be the result but there is still a character a so for this a there is another time so 1 + 1 it is two there is another time so 1 + 1 it is two there is another time so 1 + 1 it is two times but actually it is one time so this is why if we have the same character from the first to the last so what are we going to do so our DFS would become I to J minus one we should not C it as what we can't count it because we have the same character we're going to count it later so this is the difficult part yeah and another case is if this character is not a so for example if this character it is B yeah now this character is B what it going to happen so this a and this is B yeah so for this situation we have to use the r DP so the r DP idea is from character we're going to cut it from the different cases for example we're going to cut it from this a to BCB so for this a there's one time what about this BCB as you can see B and B is the same so there are two times so 1 + two it is there are two times so 1 + two it is there are two times so 1 + two it is three or we can cut it um from here this ab and this is C so for this AB there are two times because they all different and for this C there are two times so 2 + 2 it is four times are two times so 2 + 2 it is four times are two times so 2 + 2 it is four times but we're going to always check the minimum time so the minimum is three it is cutting from here yeah it is cutting from here this is going to be the minimum time yeah so this is the final solution if they are equal we're going to use this formula if they're not equal we're going to cut in between and check the minimum now let me go to the code Editor to finish the coding so we're going to use a DFS so in this DFS I going to play I and J so the definition of the DFS is so the definition of the BFS is from the position from I to J what is the minimum of prings so it is two so this is the I'm going to prepare a variable n it will be the length of the Str and I'm going to return I to n minus one uh I going to return this I is zero and J is n minus one now I'm going to finish writing the DFS part yeah but before that I need a cast because this is a dynamic programming and then I'm going to write the main function so if I equal to Z it means yeah I have a one character if there's only one character how many prings so I need one at least yeah at least I need one time of preting because I have to print it out yeah if I equal to Z now I'm going to check if s i equal to SJ so this means if the first character equals to the last character so I just need to return this I to Z minus one yeah because here I can't use IUS one I + 1 I can't use IUS one I + 1 I can't use IUS one I + 1 plus one as I explained earlier because this is not right this formula we cannot plus one yet we have to plus this one to the end to the final return it going to return a one but we cannot plus one and then we're going to Che the minimum value of all the different sptings so it going to be the minimum of DFS I to I going to use a K plus DFS k + DFS I to I going to use a K plus DFS k + DFS I to I going to use a K plus DFS k + 1 to Z and for I in range I to Z so the meaning over here yeah this is okay so the minium here is just that yeah let me clear it so the minum of this line is just that we're going to check so if this is a for example if this is a and this is B there's some characters in between we don't know and then we're going to S the different splittings we're going to split one by one as you can see this K first starting from I so this DFS I it means the first character a and if this k equals to J minus one so J minus one + 1 it is minus one so J minus one + 1 it is minus one so J minus one + 1 it is this character B yeah so we're going to enumerate all the different cases and check the minimum value so finally we're going to return this minimum I just write it in one line for Simplicity so this is the entire code the code is not so difficult but it's really difficult to think about this testing case if you can think about this tting case yeah normally you can solve the problem now let me submit it to T if it can pass all the testing cases as you can see it pass all the testing cases and the time complexity is I * z uh so the I is from I is n the I * z uh so the I is from I is n the I * z uh so the I is from I is n the length of the string and Z is also n square and here is a for Loop this for Loop is also in so it is in cubic normally we can guess from the con if it is 100 normally this is a cubic operation cubic time complexity so that's all for today thank you for watching see you next time
|
Strange Printer
|
strange-printer
|
There is a strange printer with the following two special properties:
* The printer can only print a sequence of **the same character** each time.
* At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string `s`, return _the minimum number of turns the printer needed to print it_.
**Example 1:**
**Input:** s = "aaabbb "
**Output:** 2
**Explanation:** Print "aaa " first and then print "bbb ".
**Example 2:**
**Input:** s = "aba "
**Output:** 2
**Explanation:** Print "aaa " first and then print "b " from the second place of the string, which will cover the existing character 'a'.
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
546,1696
|
604 |
hello guys now a Chinese of the design compressed a straight iterator actually is probably similar to the previous progress all which will give up give us a stream we will compress it and now we are given a compress the stream we want you recovered so and also this program I think if the similar cuter read characters by culinary default Robin we need a global pointer to indicator our position in our stream as you see the product design employment that they are structure for compressed thus reiterated this should do supposed to the phone operators of operations next and the health next the Gibbon compress the string will be in the form of each letter followed by approach integer printing number of this letter existing in their original untrusted string next if the original string still have unprotected return next Lantern I was returned whitespace health knack to charge whether there were anywhere near to be impressed okay so basically and I said we need our index to our condition and we also need a couch actually to cover how many the hominid the current charge has been impressed of compressed so we gonna cut those all we need are straight and then we also need our courage so we do I have next in which situation we do not have next so it may have made larger than 10 so we'll read achoo Oh more so we should try to make sure we have read older it is a chart at index it's digital right okay and the 808 which will be as chart yes okay every time we call this next we should make a cow - - - because we use a should make a cow - - - because we use a should make a cow - - - because we use a below one character yeah okay thank you for watching see you next time happy Cody
|
Design Compressed String Iterator
|
design-compressed-string-iterator
|
Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.
Implement the StringIterator class:
* `next()` Returns **the next character** if the original string still has uncompressed characters, otherwise returns a **white space**.
* `hasNext()` Returns true if there is any letter needs to be uncompressed in the original string, otherwise returns `false`.
**Example 1:**
**Input**
\[ "StringIterator ", "next ", "next ", "next ", "next ", "next ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[ "L1e2t1C1o1d1e1 "\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, "L ", "e ", "e ", "t ", "C ", "o ", true, "d ", true\]
**Explanation**
StringIterator stringIterator = new StringIterator( "L1e2t1C1o1d1e1 ");
stringIterator.next(); // return "L "
stringIterator.next(); // return "e "
stringIterator.next(); // return "e "
stringIterator.next(); // return "t "
stringIterator.next(); // return "C "
stringIterator.next(); // return "o "
stringIterator.hasNext(); // return True
stringIterator.next(); // return "d "
stringIterator.hasNext(); // return True
**Constraints:**
* `1 <= compressedString.length <= 1000`
* `compressedString` consists of lower-case an upper-case English letters and digits.
* The number of a single character repetitions in `compressedString` is in the range `[1, 10^9]`
* At most `100` calls will be made to `next` and `hasNext`.
| null |
Array,Hash Table,String,Design,Iterator
|
Easy
|
146,443
|
41 |
hello let's try to solve a lead code problem today we are going to solve number 41 First missing positive so it's a hard problem and even we did it many times it's really easy to make mistakes because we if we did it many times we basically know how to solve it but there are still some tricks we may forget it's time we did it so we are giving it a photo integer array norms and for example this is one two zero which is the smallest mixing positive integer so what is the smallest missing positive integer for this example this is a three because there's only one the two yeah so zero doesn't matter so three is missing so we're gonna return three for the second example we don't have number two so we're gonna return number two for the third example we don't have number one so one is the smallest yes because we always return the smallest integer one so we start to return one but there are some conditions we need to confirm yeah we must Implement an algorithm that runs in on time and uses all one auxiliary space it means we must do it in place we cannot use any other memories like that yeah and we must run it in your own time this means we cannot use the thought sort the nums and then find it we have to use it in place so we have to use our half table but we cannot Define a take memory of the half table we have to use the index of the array nouns yeah now let me go to the white label first to explain it and then go to the code Editor to finish the coding yeah so here let me give you an example for example we have a number like 1 2 and 0 inside of the array what we should consider is a yeah how many positive integers this can hold for example if the situation is like one two three yeah we don't have yeah we hold all of them one two three what is missing the most important table is four yeah similarly for the first array one to zero the first mission is three yeah because we have one and two three is missing so what is the series for the positive integers giving a array the length of the array is L yeah because later on I will use l as my variable so here I will use l as the length of the ring if we have a lens over a ring and it is l so what is the ruins of the positive integers it can hold of course it is like 1 2 yeah it can be a what it can be two it can be 3 right it also can be four yeah right so if we are giving a ring the length of the rule is three yeah like that so missing positive integer can be one two three and four yeah so this example is 4 and this example is three what about 1 we can directly have a 2 3 or 2 yeah so the missing positive is one what about the two we can have one and three yeah we can put as many examples as possible we know that the missing positive is two so the rinse is one two three and four so that is the first one but for this number phone it means if we didn't fight any yeah so for example we have all the values like one two three we didn't find any negative because later on we will use the negative values to attack if we find a index or not yet if we didn't find any negative values here I use minus sign yeah it means we're gonna return the length of the rate plus one and we will gonna return this four yes but if we find it must be one two and three yes so for this situation basically we're gonna use the three Loops so the first Loop is the third negative and zero to infinite here I use infinite because the infinite can avoid many testing cases and if we don't use this infinite we're gonna yeah make a lot of mistakes for example the first loop we're gonna turn this one to zero we're gonna check if this number is more than the length of the real we're gonna give it a infinite if it is zero we're gonna give it a infinite so the first loop we're gonna flip the here though and negative to infinite so for one it is still in ruins it is 1 for number two it is still in Ruins because it is less than L and more than S more than it's more than zero and less than and equal to l so 2 is still there but for this is zero we're gonna give it a infinite if cos this is zero doesn't matter because our ruins is one two three we're basically gonna find a value between 1 2 and 3. so the zero doesn't matter so we give it a infinite yeah or you can give this zero uh L plus one it's also the same but for me I will use infinite because for my second loop I will still use the infinite so what about the second Loop so the first Loop is basically flip the zero and if some numbers out of the ruins to ethernet if there's a number like four uh yeah 4 is still okay but if yeah if a number is four like if a number is four we know three is missing so we'll give this number to infinite because it doesn't matter we're gonna only conserve one two and three yeah so this is the first step the second step is we're gonna turn the power table to negative yeah so what we are going to do this is the half table basically for array we're gonna use the heftable index here is zero like zero index one and two but here we're gonna use this zero to represent one represent the two and two replicate represent three because it is a straightforward we can use this index to represent any numbers like 2 3 4 or any others but here we need one two three y because we're only gonna to find a value between 1 2 and 3. so here we're going to use this index as 1 2 and 3. for example the first number this is a one how we are going to do it yeah here is a one two and infinite we're gonna use this one here at index is zero yeah but we're gonna use this one minus this one this number one minus one it's a zero yeah because we're gonna we don't use this to represent because it's not enough we have to start from the zero to represent one so this one will minus one we got a zero so at this place we're gonna give our miners yeah because the miners is something we find yeah for example this is a two minus one it is still one it is at index one so we give it a minus but what about the infinite so the infinite balanced matter because we don't consider any infinite yeah now let's go to the third loop we're gonna finish our yeah finish the all the mess all other Loops to solving the problem basically we're gonna need three Loops so the third Loop that we're gonna find if we find a number that is a positive it means we find so what is positive the first one not the second one not what about the third one yeah if it is positive it means we find the number what is the number it is the three but what if we didn't find it is still a negative value it means we're gonna return four it's like this case we're gonna return L plus one we're gonna return four so why it always works because by approaching these three loops we're gonna find which value is the smallest yeah so the first step we're going to find any value that is a zero or more than the length of L yeah we are sure that numbers doesn't matter because we're going to find some ruins between like one two three so we give it here infinite and the second loop we're gonna take the numbers to negative but the infinite is gonna still be here the third step is after gonna fight this positive e infinite yeah now let me go to the code Editor to finish the coding yeah if we find any problem I will go to the Whiteboard to explain more Yeah so basically I'm gonna Define uh L is the length of nums and we're gonna use the three Loops the first Loop is a flip basically flip uh to infinite yeah so for I uh in enumerate nouns if this number in is less than or equal to zero it is a negative number yeah or is bigger than l so here the first step is the flip negative two negative and zero to if yeah so if it is a zero or negative or it is auto blue range yeah or it is out of the Rings so we just need to flip the num's eye so the num's I so the times nums I so the two in yeah so the first step is set negative and zero or out of greens yeah let's make it set out of ruins so that is a means not into one two and three not between one two and three set out of range to infinite and the second step is to set is a set negative set positive to negative yeah we have to perform such steps otherwise basically we cannot solve the problem so it is like a template or something because we have to use the index and there are a few lead problems we need to use the index as hash table to solve the problem so set the second step is to set the power table to negative it will still be the same for i o in enumerate nouns the we're gonna the first step is we're gonna set this uh to have its absolute value because if we didn't do it there's a minus value for each of the steps because here it seems okay everything is a positive but here if something happened for the following Loop it may produce negative values this is about why we have to set the N to always be positive yeah and as I said the numbers end through the minus one this is a 4 here so this is for here because we want to if we find a number this number minus one it means at this position at the first index of position this number at this position we will set it to negative yeah so how to set it to negative it is a positive it doesn't matter but if it is a negative we're gonna set it yeah so if this is a positive value the absolute of it and we're going to have our manners it will be so it will be a negative value because this absolute will always be positive yeah so this means if this number is a power table value it will be set to negative because this is minus right so if this number is a minus value yeah do you think that it's possible yeah if this is a minus value so this will still be minus so everything in the safe because minus value item is that value is important it is a yeah some value will find in place of the array so it is still okay yeah so we're gonna use this syntax to check all the conditions yeah and the third step is to find the result still it will be the same for Io in enumer with nouns so if we find the value if this earn is a positive value more than zero we're gonna return I plus one if we didn't find we're going to return L plus 1 as I explained to the situation if it is one two three we're gonna return four here yeah no let's have to have an attack if we made any mistakes or not yeah so here is a set out of the range here is the set positive and positive to negative yeah this is a nums and minus one this is a minus and minus 1. so here is a condition we have to suck this infinite because for the first step we have set some value to infinite we have to tax the infinite condition so if L is not equal to infinite we can set it yeah to the negative value if it is infinite is not possible because infinite minus one it will out of the index will out of the Rings yeah now let me run it to tags if everything is okay yeah at the same time everything is okay no let me submit it to check if it can pass all the testing cases yes as you can see it passed all the testing cases and it's pretty paused and it's pretty fast the little difference for my solution is that I use infinite and why I use Infinity is because I think infinite is easy to solve such problems of course I can use l plus 1 but it's basically the same and also for here this is very important we have to set this one otherwise between these Loops it will set some numbers to a negative number and for this negative number you will make mistakes because it will out of the Rings for such nouns so here we have to always set this in to a positive first yes and if this is not equal to the infinite is set by the first Loop so we're gonna set it yeah we're going to set this number to a minus value yeah if it is a minus it will still be a negative value so if it is positive definitely we'll set it to a negative value and for the final step we're going to find if there's still some opportunity we have a positive value if we didn't have the positive value we're going to return the length of the Ring plus one now let's analyze the time complexity for this method so there are basically three steps and each of the
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
5 |
hi guys welcome to the tech grant today we are going to solve the lead code problem of longest palindromic substring do like and share the video subscribe to the channel to get further update and also i've started a new playlist for those who want to start with data structure so do check that out as well the link will be there in the description so this problem is a pretty common problem and it is all asked in a lot of interview question and there are many methods to do it we'll i'll just show you one of the method which is the brute force method if we use so in brute force method if i am given a string like this so what we can do is we can create all the substrings that we can create from each of from the given string we can create all the substring from this string and then find which all our palindromes and which is the biggest palindrome which is the biggest paranormal number which is present here so it will be something like this and other substrings so you create all these substring and then check okay this is palindrome yes this is palindrome and it is of length one this is not a parent room this is a palindrome this is of length three and so on and finally you get what is the maximum parallel now the challenge with this brute force method is to get all the substring for a given string you need to give a time complexity of order of n square and on top of this you will give a time complexity of order of n for finding the palindrome number so this in all makes a time complexity of order of n cube so order of n cube it will be very slow so we need to think of some other approach with which we can reduce the time complexity so what we can try is we can go through the string once and at each point basically we can check whether the left and right strings are matching or not if they are matching then that particular substring is a palindromic substring let me explain it with uh with an example here so if you see the string that we have taken here is b a d which is the string that was given in the question so when i start my execution i will be at the first character of the string and i will check okay if on the left hand side and on the right hand side if the characters are matching then that will be a paranormic substring so in this case nothing is matching so the largest palindrome that i can get from b is one now i move to the second step so i reached a so i'll check left side of a and right side of a since these two characters are matching so the num the biggest length of palindromic sequence or the subsequence that we get in this string is of size 3 okay so i will replace this number with 3 because 3 is the maximum number and i will also store the starting point for this case since the starting point is zero so i will store the starting point so i will say start point is zero and max length is three okay now i was at a i checked these now from this particular point i cannot go further towards left so i will move to my next point which is b when i start from b i will check the left and right these two are matching so again i can say that okay for start point uh this will be the start point so for start point one i will have a max length of three and uh i can still go to left and right because i have elements remaining so if i see here b it is not matching with d so this cannot be constituted as a palindrome sequence so still my maximum length is 3 now suppose there was a b here in place of d so in that particular case what would have happened is i would have a longest palindromic sequence of length five starting at zero okay so the idea is you go you traverse this string one character at a time and when you reach a character you go towards left and right and check whether the left and right are matching or not and go towards left and right till we have a matching sequence so suppose we had like a here and this set also a so when i reached b i will go as long as the left and the right so the left and the right are matching i will keep on increasing my decreasing my left and increasing my right i will go as long as these are matching so this will give me the maximum length and the left most character that i reached will give me the start point so when i have to find the string which string is the longest palindromic string so i can just do substring of the original string starting at the start point and maximum length start point plus maximum length so like i described in the excel so let us code for that so before getting the longest palindrome let us write a function to get the palindromes and basically check for the palindromes what i described if we start from here will go towards left and right so let us write that function so let's get palindrome will get the string s will have a left side movement and a right side movement and we'll put a check that we need to go towards left till we reach the end of the string on the left hand side and same goes right hand side we'll go towards right till we reach the uh the length of the string or we find that the left and right characters are not matching so we'll have the condition like left is greater than 0 and right is less than s dot the length of the string and we can put a condition as care of left if this is equal to s dot carat right so if all these conditions are satisfied so we'll move towards left and we'll move towards right otherwise if these conditions are not satisfied and we are thrown out of the loop in that case we'll check for the max length so for that we have defined the starting point and the max length like i described in the excel so we'll say okay if max length is less than my right minus left minus one so this one is to take into consideration we'll be starting from the same character so the length will be minus one and also it is zero based index so if this is the case then we'll assign max length is equals to right minus left minus one and my starting point i need to give my starting point also so my starting point will be so suppose i started from here so initially my left was 0 1 2 right was 2 then i went one towards left and once towards right so my starting point was 1 and my left was one and my right was four then again i went one step towards this so my left become zero and my right become five but in this case it did not match so i have to take the substring from here from a so which is left plus one so my starting point here will be left plus one so here i will get my starting point and the max length now we just need to call this and uh when i call this i will call it with the string s and left and actually not like this we need to loop through the string for entire equal to 0 i less than s bar length and now i call this so when i call this i will give my i will pass my string i will pass my i as starting and end point okay so this will give me the longest palindrome now suppose there is a case like this where rather than an odd length we have even length character so there is no if we give pass if we pass as the starting endpoint as i we will never get the palindrome for such kind of string so to handle this we will make one more call and this time we will say i and i plus one so i'll make these two calls uh to handle the odd uh for handling the even length of the palindromic string even in this particular case uh the if the length is odd but still we have something like this so the length of the palindrome is even so to handle all this kind of scenario uh we need to go towards left and right from here basically so we'll make the same call two times but once with i and i as the starting and end point and second time it will be i and i plus one and once we get the maximum of the maximum length of the substring so we'll simply return from here and i will say s dot substring and how do you substring you say starting point and from starting point you get the length of the substring so this is what you return so let us see so it is accepted let us submit the code it runs fine and this solution is in a time complexity of order of n square because for each of the string you are visiting the left and right again so you are visiting basically the same character two times so this is order of n square and there is uh and if you see here i'm faster than only 45 percent of the guys who have submitted the code here so there is a way to do it in a linear time in order of n there is an algorithm for that so that is available on internet i'm not going to go through that algorithm in this video i'll make another video for that so do check out for that video and thanks for watching see you in the next video bye
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,869 |
hey guys welcome to today's video in today's video we're going to look at a lead code problem and the problem's name is longer contigous segments of ones than zeros so in this question we given a binary string s and our task is to return true if the longest contigous segments of ones is strictly longer than the longest continuous segments of zeros inside the input s else we have to return false so if you take an example here you're given the string s you count the longest continuous number of ones it is two the longest continuous numbers of zeros is one since two is greater than one representing ones and this is representing zeros since two is greater than one you return true as the output and here in this case ones appear two times and zero appear three times the number of zeros are greater we return false as the output now let's take a look at the example and see how we can solve this question so I've taken the example three given to us here as you can see you can make out that these are the longest contigous ones so ones appear two times and this is the longest contigous uh sequence of zeros and zero appears three times the number of zeros are greater you get false as the output so let's see how we going to do that so we iterate through the input string is from left to right we start from the Zero's index until the last index and we keep track of the number of zeros and number of ones so zero is a variable which is initi Z and ones is to count the number of ones which is initially zero so corresponding to these two variables you create two more variables tracking the max number of zeros and also max number of ones these are also initially zero now let's start with the first element I is pointing at the zeroth index it is a one so increment one until now the max one is equal to 1 go to the next element I is pointing here it is a one so increment one so it is two now previous Max was one now current one is two so update Max variable of 1 two go for the next element it is a zero if it is a zero increment the zero index and you reset the other variable which is one in this case to zero because this trick is done because it is broken by a zero so you reset the ones for the upcoming ones now you compare the max zeros Max zeros was Zero initially it is one now so max of 0a 1 you get one go for the next element is a one so update the count of ones and reset the other variable to zero because this streak is broken by a new one and this will remain unchanged because Max of earlier it was two Max one will remain two go for the next element is a zero so increment the zero count variable and reset the previous one to zero because this streak is broken now and now compare the previous Max now compare it with the previous Max was one and current Max is also one so max zero won't change go for the next element is zero again update the zero variable and also update the max0 is updated to two go for the next element it is a zero again so you increment the streak of zero and compare it with the current Max zero Max 0 was two it will become three now go for the next element is a one so increment one count and reset the Zer value to zero because this triak is broken by a One max value won't change Max one won't change because it is two and current is one so max of 2 comma 1 will still remain two go for the next element is a zero so increment zero variable and reset the one value to zero because this streak is broken by the this zero Max Z won't change because Max Z of uh 3A 1 is 3 and in the next iteration you reach the end of the string and now you have the ma zeros which is three and you have Max 1es which is two since max0 is greater than Max one you return false as the output because this is the condition mentioned here so we are returning false now let's Implement these steps in a Java program so coming to the code you have to return a boan value true or false as output and this is the input given to us and these are the four variables which we declar to keep track this is to keep track of the number of zeros this is to keep track of the number of ones and this is to keep track of the maximum streak of zeros and this is to keep track of the maximum streak of ones we're using a for Loop to start from zero index until the last index of the input string is and extracting one character at a time and storing it inside the character variable CH if it is a zero increment the zero count variable and reset the one count back to zero Z and in the else block if it is a one then you increment one count and reset the zero count to zero because the streak will be broken and in each iteration you calculate the max Z by comparing the current Max Z with the zero count and you also calculate the max one by comparing the current Max one with the one count so this will happen for all the elements inside the string and once you come out you compare the max ones with Max zeros if Max 1 is greater than Max Z you return true else you return false and if you return false it means that this condition is passing which I've shown you in the working example so we return false so the time complexity of this approach is O of n where n is the length of the string s and the space complexity is O of one because we are 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
|
Longer Contiguous Segments of Ones than Zeros
|
longer-contiguous-segments-of-ones-than-zeros
|
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_.
* For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest continuous segment of `0`s has length `3`.
Note that if there are no `0`'s, then the longest continuous segment of `0`'s is considered to have a length `0`. The same applies if there is no `1`'s.
**Example 1:**
**Input:** s = "1101 "
**Output:** true
**Explanation:**
The longest contiguous segment of 1s has length 2: "1101 "
The longest contiguous segment of 0s has length 1: "1101 "
The segment of 1s is longer, so return true.
**Example 2:**
**Input:** s = "111000 "
**Output:** false
**Explanation:**
The longest contiguous segment of 1s has length 3: "111000 "
The longest contiguous segment of 0s has length 3: "111000 "
The segment of 1s is not longer, so return false.
**Example 3:**
**Input:** s = "110100010 "
**Output:** false
**Explanation:**
The longest contiguous segment of 1s has length 2: "110100010 "
The longest contiguous segment of 0s has length 3: "110100010 "
The segment of 1s is not longer, so return false.
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
| null | null |
Easy
| null |
268 |
this is one of the simpler problems and yet I find that this problem is asked in a lot of coding interviews why is that so well you are given an array of integers that have numbers in the range of 0 to n correct and you have to find the missing number the main reason this problem is asked in a lot of places is that because this problem is a entry way towards bit manipulation let me show you what do I mean by that Hello friends welcome back to my Channel first I will explain you the problem statement and we will look at some separative cases next we will look at a Brute Force solution and see why that is time consuming going forward we will try to find some Optimal Solutions and then ultimately use the War gate to arrive at a very efficient solution after that we will also do a dry run of the code so that you understand and visualize how all of this actually works in action without further Ado let's get started first of all let's make sure that we understand this problem statement correctly in this problem you are given an array with distinct integers and the property is that all of these integers lie in the range of 0 to n we will see what that means and what do you want to do you have to return the only integer that is missing from this range so let us try to understand it even better with a given sample test cases for a first test case what do you see that this array has three elements correct so the value of n equals to 3 and that means the range should be 0 to the number 3 so you are expecting 0 1 2 and 3 right and you can see that one of the number is missing so in this particular test case you can see that okay 0 exists one exist you cannot find a two so 2 will be your answer because you can see that 3 also exists so for your first gift 2 will be your answer correct now similarly let us look at a second test case you can see that this array has two elements right so it means that you're looking at a range of 0 to 2 and that means you will look for element 0 and then 1 and then you have to look for 2 as well correct so in our second test case also two will be your answer because then only this complete range will be finished right now let us look at our final test case you can see that this array has a lot of elements right in fact this array have nine elements so the value of n equals to 9 and hence you are expecting elements from 0 all the way up to nine and if you try to find the missing element you can see that 0 is there one is there you have two three four five six seven and you cannot find an eight right so in your last test case 8 will be your answer because you can see that you can find 9 and this completes your entire range 0 to 9 right now I feel that you may have understood this problem statement even better so if this of the condition first feel free to try the problem once again on your own otherwise let us dive into the Brute Force solution and start to solve this problem a good developer always tries to come up with a Brute Force solution first that is because a fruitful solution can guarantee you that okay a solution to this problem exists so let us say I have the sample test case in front of me that has nine elements right so you can say that okay the value of n equals to 9 right and now what is the most obvious way that you can think on how to approach this problem what you can do is you can start from 0 and then go all the way up to nine right and what you're gonna do you're gonna iterate through this array again and again to check each element you will start with 0 and then you Traverse the array you see that okay you found a zero so cool perfect now you will look at element one once again you start from the beginning go all the way up to the end and okay you found a one perfect similarly you will do for two and you found a two then you will do for three and you will find a three similarly you will keep on finding elements and ultimately you will reach 8. once you reach 8 you Traverse through the entire array and you do not find an eight correct and hence that is the missing number so you can simply say that for this particular test case it will be your answer right and yeah this solution is absolutely correct and it will give you a correct answer every time but the only problem with this approach is that you are iterating this array again and again right you are checking every element and that will take up so much time think about it if this array had a lot more elements and you can see that okay the range could be 99 as well right then what will you do will you keep on traversing this array again and again this will take up so much time right and hence what you need to do is you need to start optimizing the solution and what could be a better way to optimize this solution Than Mathematics itself so what do you do about it so let's say I have this sample test case again with me right and once again to calculate the value of n you just calculate the total number of elements right so the value of n equals to 9. according to the program statement this array should have all the integers between the range 0 to n right that means 0 1 2 3 all the way up to n correct and going back to the basics of mathematics what is the summation of numbers when you are given a range 0 to n technically what do you need to find out Sigma n and that turns out to be n multiplied by n plus 1 whole divided by 2 correct so this will be the total sum if you have all the integers between the range 0 to n so one approach that will come to your mind is okay if this array has nine elements then what would be the value of Sigma nine that will be 45 correct so you know that if this array had all the numbers then the summation of all the digits should be 45. so now what you can do is take this 45 and start subtracting each of these elements one by one so what you're going to do is you're gonna do 45 minus 9 and then whatever is the remainder subtract 6 from it then 4 then 2 and then one by one just reach to the very end subtract all the elements and you will see that you are left with a certain number and what will be that will be the missing number right so in this particular test case When You Subtract out all the elements of the array you will be left with 8 correct and once again this is your answer right so did you see what did we just do over here we just did one iteration of the entire array so no matter how long your range is you just have to Traverse it once and in that one iteration you will arrive at your answer so this is an efficient solution correct and technically speaking you cannot go faster than this but I have a concern that when this kind of a question comes up in an interview your interviewer will ask you okay can you approach this problem in some other way as well and that's a indication that your interviewer is looking for a bit manipulation technique basically your interviewer wants you to use the war logic so let us see what is it all about in this video I will just cover the very basic concept of what a sword logic actually is I will create separate videos where I will explain all of the logic gates and how they work but just to give you an overview you might be already knowing about the and or logic right so what that technically means is that one and one will be equal to one and zero equals 0 and then similarly you have different rules for or logic as well right so one or zero will be 1 and 0 or 0 is 0 right so you can form a truth table like that similarly you have one more operator that is called the zor operator and what you do is one zor one that will also give you something and usually a law is represented by this particular symbol so there are some properties that you must understand about this sword operator before you go ahead and solve this problem so let me just give you a brief overview about it and let us look at the properties of zor so first of all the basic property of word is that the zor logic is commutative simply means that A or B will be same as B War a and you can understand commutative property by means of addition or multiplication so you know that a plus b will be equal to B plus a correct because addition is commutative and similarly a multiplied by B is same as B multiplied by a so both addition and multiplication are commutative you can understand that a divided by B will not be equal to B divided by a that is because this division operator is not commutative so what I'm basically trying to say is that if you do a war B or C or D that will be exactly same as a verb C VAR B that means you can have all these operands in any order right and that is one property that you must be aware about the second important property is that if you do absorb with zero then the result is always the actual number that you started with so if you do 2 or 0 3 4 0 5 or 0 all of them will give you the original number so 2 over 0 will be 2 3 1 0 will be three five or zero will be five right so this is one important property that will play some part and the last property that you must know about is solve itself so a or a will always be zero so any number if it is word width itself then the resultant output will be zero correct so what I simply mean is that if you do three or three that will be zero if you do 9s or nine that will be 0 again so what we're gonna do is we are going to take help of these three properties and try to come up with a solution so let us take up a sample array and you can see that I have five elements right that means the value of n equals to 5 and I am expecting every element between the range 0 comma 5 in other words I need all of these elements 0 1 2 3 4 and 5. now to approach this problem what will I do first of all I will score every number in this range 0 to 5. what will this give me this will give me 0 1 0 2 0 3 0 4 and then four five right and now what do you want to do next is you want to war this entire thing with the zor of all of the input variables just try to observe what is going to happen I take up my first number 2 and then solve it with 3 then I bought it with five then I saw it with 0 and then I wore it with one and now what you want to do is just War both of these things together what do you see over here since we already defined that zor is commutative that means I can shuffle all of these numbers anywhere right I can put the zero over here I can put this 2 over here and I can just change the its ordering so what will happen it will become 2 go to five or five six were fixed and so on right whatever the integers are and once they become together what happens 2 gets resolved with 2 3 gets resolved with three five gets word with five one will get war with one and zero gets war with zero and you know that if we draw a number with itself what do we get a zero so all of these numbers 2 over 2 3 or 3 5 or 5 they will all become zero right and what are we left with you can see that where Jeff left with four all of the other numbers they get Zord together and become a zero so in the end we just get 4 0. and from the last property that we know any number that we bought with 0 will give you the original number itself so in the last result we are gonna get four and you can see that indeed 4 is the missing number right and this is your answer so you can see that this technique will work every time because if you've got all the input integers and then you War them with the range 0 to n this range has that extra integer correct and all the other integers will just get resolved with themselves and turn out to be zero so in the end you will be left out with the actual missing number right now let us quickly do a dry run of the code and see how this works in action on the left side of your screen you have the actual code to implement this solution and on the right I have this sample array that is passed in as an input parameter to the function missing number right and by the way this complete code and Swift cases are also available in my GitHub profile you can find the link in the description below moving ahead to the dry run what is the first thing that we do first of all we initialize a variable that is going to store the zor of all of the integers right so here is my variable and now what do we want to do first of all we want to sort all the numbers in the range 0 to n so what will this for Loop do this for Loop will take up each integer one by one starting from 0 and go all the way up to the nth limit so if the length of array is 9 it will start at 0 and go all the way up to 9 and it is gonna bar each number with the previous result and in computer science this is the operator for VOR that is how you were to elements so now in this all Zord variable you have the war of Rage and now what do you want to vote all the numbers given in the input array and once again you will start a for Loop and then you are gonna for each number in the input array with the already existing zor so this is zero out all of the matching elements and you will be left with the only missing number and thus what you're going to do is you're gonna return that number as your answer right the time complexity of this solution is order of n that is because you iterate through the array only once and the space complexity of this solution is order of one that is because you do not take any extra space to arrive at your answer I hope I was able to simplify the problem and its solution for you as for and final thoughts I just want to say that I know that this problem is very simple and probably you do not even need to use the zor logic gate to arrive at an efficient solution but the importance of this problem is that whenever you are trying to come to an interview then the interviewer will try to Gorge how many different ways you can arrive at a solution and then he can assess okay do you even know about bit manipulation because bit manipulation is a concept in itself and sometimes bit manipulation can help you to arrive at some Solutions in a extremely fast way because it literally works on zeros and ones and that is how your computer architecture also works correct so while going through this problem did you face any problems have you found any other problems that work on bit manipulation techniques sure I'm gonna create more videos where I specifically focus on bit manipulation problems and all of these logic gates in general but until then tell me everything in the comment section below 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 I also have a website study to help you website study to help you website study to help you out also let me know what problems do you want me to solve next until then see ya
|
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
|
1,022 |
Hello hello everyone welcome to our channel co with honey and today will be discussing the easy problem evening of root to lip binary numbers 102 the like delhi challenge problem seethe [ seethe [ seethe 11sau loot explain time related subscribe explain number 90 number two the Park And What Is The Decimal Values Of December Decimal Values Of December 10 Of December Decimal Values Of December 10 Of December Decimal Values Of December 10 201 120 Days That Nine If You Want To Explain It Withdraws Into A Bird Extra Bittu Right Side subscribe The Video then subscribe to The Amazing Subscribe Like Subscribe and subscribe to the video That Vijay Actually Double Of This Will Value Avoid Having Observed That Not Every Lutb Squid Luta Does The Equivalent From This Point To Our 0 Power Plus To Uvi Subscribe To Oak And Here You Can See But 50 Se Z Cash Withdrawal Laptop Subscribe Now To to we will give us cats printed 299 subscribe The equivalent from this point to you will get this position in the last two years paper this foreign position that and bad energy 93002 11095 like to power in the plus 2 power to a plus Chaudhary Kallu son became two powerful, one move decimal value vacancy in more number one more nothing will change subscribe to subscribe and subscribe the Video then subscribe to subscribe Remind Me Three Layer Problem Tips and Video then subscribe to the Page if you liked The Video then subscribe to the Page if Hua Tha Contek No Hai Ki Jhaal Hotshots Poche Amazon Subscribe Channel Bollywood 10 To The [Praise] [Praise] [Praise] subscribe and subscribe the Video then subscribe to the Page Subscribe Tapkeshwar Going Towards Each Time You Will To Maintain Amazon Se Or Lighter Siron And Welcomes You Will Like Sid [ Like Sid [ Like Sid Subscribe Subscribe Hai Lekin Soumya Festival 2025 Vacancy The subscribe to subscribe Representation Adhed Number subscribe to subscribe Video subscribe The Channel and subscribe the Channel Please subscribe our Channel and subscribe If possible then see this is very smart simple so this point to simple question that present guest and whenever you in counter will take this a 114 time Complexity Oye In This Page Completed Open Do Subscribe Sohan Seervi The Amazing Subscribe You Must Try Boxing Day Test Parameter Balance subscribe thanks for watching this Video
|
Sum of Root To Leaf Binary Numbers
|
unique-paths-iii
|
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`.
| null |
Array,Backtracking,Bit Manipulation,Matrix
|
Hard
|
37,63,212
|
443 |
given an array of characters cares compress it using the following algorithm these are the rules that we should follow the first rule is if in the list of characters that they have the number of like a distinct character is equal to one we are going to just add that character like this example we have one a we are going to just add a year no numbers and if the number of that uh distinct character that we have is bigger than one we are going to add that character and the number of that character that we have right so something like this here we have two a we are going to say a two we have two b we are going to say b two we have three c we are going c three but we have another rule here if the length of the number of that character that we have is smaller than ten we are just going to add it here but if the number of items like uh the number of uh times that we have that character in the list is bigger than 10 like this example that you see we have 12 b we are not going to add 12 here we are going to add one and two if we had 13 b's we were going to add one three if you have 23 beads where we are going to add two three this is how it works we are not going to add yeah like as one input we are going to use it at multi as multiple inputs considering all these rules what we are going to do to solve this problem we are going to use two pointers pointer p and pointer i let's see uh what we are going to do with pointer i if this is the list we are going to iterate over every single character that we have and with pointer p we need that because the question is asking us to do it in constant extra space so we cannot use another list we should do it in constant so that's why we are going to use the same list and we are going to update these values as we iterate over right and so this way we are not using extra space so we are going to set as long as i is smaller than the length of the characters that we have the characters list that we have we are going to say count is equal to one why we are going to say count is equal to one because we are not going to have an empty list this is one of the constraints that we have here the list at least has one character in it so we can say we can start from count one and then we are going to say while i plus one because we have count one here is smaller than the length of the characters that we have because we are not going to be out of range and if the characters that we have at index i is equal to the characters that we have at index i plus one okay so if the character that we have in i is equal to the one beside it what we are going to do and we are going to have i plus 1 here because we are comparing each um like value that we have at index i with the one beside it and uh if we get to here if we don't say i plus one it's gonna be out of range so and we don't want that so what we are going to do we are going to say if they are equal they are going to add one to the count sorry and then we are going to add one to the i so i is going to move forward so let's have count here so it was one and now it's going to be two and then we compare if i plus one is smaller than the length yes it is if i is equal to the one beside it is not what we're going to do now we need to update um the value that we have at pointer peak we are going to say cars at pointer p is going to be equal to cars at pointer i right and then we are going to move p1 step forward right for the first one it doesn't make sense that much and but while we are moving forward is going to make sense more so and then we need to check if these conditions are like one of them is true so we are going to say if uh the count that we have is bigger than one so this if it is smaller than one we just add that character and at this step we are done but if it is bigger than one we need to do um one more thing what we need to do we need to add uh the number of times that we have that character in the value in pointer p right what we are going to do here we are going to deal with these two conditions uh as a same thing so what we're going to do we're going to use a for loop we're going to say for digits that we have in we need to because we are going to iterate we need to have it as a string right in counter we are going to say characters the place that p is pointing at is going to be equal to digit which is a string right and we are going to move p one step forward with this condition with this for loop that i have here i'm dealing with these two so it no matter if it ten if the number of uh characters that we have is smaller than ten or bigger than ten with this for loop we can deal with that if it has only one it's gonna add one if it has more than like uh one that account like more than it's gonna the value if it's more than 10 it's gonna uh deal with that with this for loop right and then what we need to do we need to move the pointer i want a step forward here it's going to be here and this value is going to be updated to 2 and then count is going to be equal to 1 again and let's go through this b so you can better understand this code so um as you see here i is going to point at b and p is going to point at um point at two and after updating that it's gonna point at b here right and uh what we're going to do we are going to say um it starts from here count is going is it going to be equal to 1 we are going to check if i plus 1 is still within the range and then we check if i is equal to the one beside it and if it is what we are going to do we are going to add one to this and we are going to move this forward and then we check again we add one to this and we are going to step one step forward and add another one to these one is the forward and so on right so we are going to how many uh do we have one two three four five six seven eight nine ten eleven twelve we have 12 of these and i is going to be all the way to the end and we are going to once the forward i plus 1 is not going to be smaller than character and uh so what we're going to do now we are going to update the uh p at is pointing at um these and they are going to put b is and then they are going to move p one step forward and then we check if uh count is bigger than one it is bigger than one so we are going to iterate over the string of this uh characters that we have and we are going to put one here and we move p forward and then we are going to put two here and we are going to move forward p and now if we had let's say uh three c here two c here right so now as you see now it makes sense why we should update p at this point because it's not always like the examples that we see as for a and b and like as we move forward it's gonna like move forward in the number of characters that we have counted and the count of uh that character and as you see here now i is smaller than like um this is another example so i is smaller than the length of the characters and the one beside it is equal so what we are going to do we are going to and it was starting from one so we are going to move forward and then this is going to be two and then we are going to add c here and we are going to add two here and this is how it works so the time capability is going to be linear and the space complexity is going to be constant thank you
|
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
|
1,976 |
foreign welcome back to the channel so today in this video lecture we're going to be solving this problem number of ways to arrive at destination so this is yet another problem in the diastra algorithm Series so basically you in a city that consists of n intersections and they are numbered from 0 to n minus 1. that means you have a graph of n nodes and the nodes are numbered from 0 to n minus 1 with bi-directional roads between some bi-directional roads between some bi-directional roads between some intersections that means there are bi-directional edges between those nodes bi-directional edges between those nodes bi-directional edges between those nodes the inputs are generated such that you can reach any intersection from any other intersection that there is at most one Road between any two intersections that means take any two intersections we can always reach from one of the intersections to the other intersection okay now you're given an integer array 2D array roads which connects which represents these edges these bi-directional edges each of these edges bi-directional edges each of these edges bi-directional edges each of these edges has some weight associated with them which represents the time which a person or an object takes to travel from one road from one node to another node also you are given an integer n which represents the number of those nodes that we have so what do we want to do is we want to know in how many ways we can travel from intersection 0 that is node number 0 to node number n minus 1 in shortest amount of time fine so because there are multiple ways to arrive at the destination node n minus oneth node in the shortest amount of time so we want to count those no those ways those paths which takes the shortest amount of time to travel from node number 0 to node number n minus 1. and that's all we have to return the answer may be very large so we have to Output it return it modulo 10 raised to the power 9 plus 7. so let's better understand the problem statement using an example so let's take this example here we have seven nodes which are numbered from 0 to 6 so 7 nodes numbered from 0 to 6. now we want to find the various parts which starts at node number 0 and end set node number six consider only those paths which takes the shortest amount of time to travel from zero to six so let's explore various parts one of the paths would be just move from 0 to 6 along this bi-directional road which has a which bi-directional road which has a which bi-directional road which has a which takes a time of seven units so just move from 0 to 6. the time would be 7 units for this case another path is move from zero to 4 then from 4 to 6 and the sum would be 5 plus 2 that is 7 unit is the time travel from 0 to 6 along this path that is move from zero to one then from 1 to 3 finally from three to six this takes in the time of two plus three five plus three eight units take another path move from zero to one then from 1 to 3 then from 3 to 5 and finally from 5 to 6 this takes in the time of 2 plus 3 plus 1 that is 6 plus 1 7. one more path move from 0 to 1 from 1 to 2 from 2 to 5 and from 5 to 6. now moving from 5 to 6 is optimal then moving from five to three and from 3 to 6 so we take this path this do not add an extra shortest path we just take this row to move to node number six so the time would be for this case would be 2 plus 3 plus 1 that is five plus one six plus one seven so these are the various parts that we have here now you can see that now these are the basic these are the shortest path that we can have all other paths that we explore will be will take time longer than this the times that we have enlisted here so out of these you can see that the shortest time take is taken along this path this and this so how many paths do I have along which I the shortest time is taken there are four such paths first one is just move from zero to six the second is move from zero to four then from 4 to 6. third one is move from 0 to 1 then from one to three to five and from five to six fourth is move from zero to one to two to five and from five to six so there are four total paths now so the answer is 4 for this test case so how can I solve this problem what is the strategy to solve this problem let's see that now it's simple we want to find the number of possible shortest path from node number 0 to node number six that's the problem statement fine now we know what is how to find the shortest path just use diastra algorithm to find the shortest path distance to move from zero to six and while we perform diastra while we execute the diaster algorithm we keep track of the number of ways to arrive at any node of the graph in a separate array let's call it ways so we'll take two arrays the first one is the usual distance array the second array is ways array what is ways array this calculates the number of ways to reach at any node of the given graph containing six nodes so let's take a priority queue as we do usually in diastra algorithm so in the priority queue push the source vertex 0 along with its distance that is 0. now pop out the top node run the usual while loop that we do in the diaster algorithm pop this node from the queue so we have node number 0 and its distance is zero now Traverse its adjacent nodes node four six and one and update the distance for these nodes we can see that so first of all we know that this distance array is initialized with very large number while the distance for Source node will be initialized to 0 and this ways array is initialized to 0 while this 0 this node number 0 is initialized to 1 why because we know that ways to reach the source node that is node number 0 is always one this there's only one way to reach this node that is just start from that node now Traverse the adjacent nodes node number four six and one and for node number four the distance that we that the updated distance would be we can see that the distance for the parent node 0 is 0 so 0 plus 5 is 5 better than the distance that we already have for node number four yes because already we store Infinity so we store five for node number four while we see the number of ways that we already have in this node number four we can see that we are visiting this node very first time so we're visiting this node first time that means whatever the number of nodes the parent node for node number four has will be the number of nodes for this node as well because we are visiting it for the first time that means the number of ways to visit node number four will be same as the number of ways to arrive at node number zero because this is the first time we are visiting it so just store that for node number 0 we have one way to visit and so it will be for node number four as well we put one here now we Traverse node number six so for node number six again we update the distance because 7 is better than infinity so we Update 7 here and we put one here we put the number of ways to arrive at Road number six will be same as the number of ways for row number zero that would be one similarly for node number one as well it would be 2 because 2 is better than infinity and the ways would be one now we have these three nodes into the priority queue node number four with distance as five node number six with distance as seven and node number one with distance as 2. now we can see that out of all three nodes since we are pushing them into a Min Heap this node will be popped out in the next iteration so this will process this node that is node number one so Traverse its adjacent nodes node number three and node number two so for node number three the distance that we calculated would be the distance for node number one is two so two plus three is five is better than infinity so update 5 here for node number three and the number of ways to visit node number three will be same as the number of no ways to visit node number one because we are visiting node number three first time so it will be one now move to node number two and repeat the same procedure for node number two we're visiting it first time so two plus three would be five the distance will be updated to 5 while the ways will be same as the ways to arrive at node number one that would be one fine and we also push these two nodes into the priority queue that is node number two where the distance as five and node number three with the distance as 5. now pop this node out of the queue that is node number four so pop this node number four from the queue and it Traverse its adjacent nodes that is node number six so for node number four node number six is the adjacent node so update the distance for node number six the distance that we already have is seven and here you can see that node number the distance that we calculate through node number four will also be seven five plus two is seven so it is not better than the distance that we already have that means whether we come to node number six through this node number 0 or this node number four the cost or the time stays the same that means these are counted as two ways one will be just move from zero to six the second will be just move from four to six and the number of ways will be the number of ways for node number 0 plus the number of ways for node number four so what are the number of ways for node number zero it is 1 and the number of ways for node number four it is also one so the number of ways to arrive at node number six would be 2 at this point so 2 is better than one so I will update one with two fine so I hope you're getting now we have Traverse node number six and we visited it second time so we're not going to push it into the priority queue because we have already computed the best answer for node number six that is seven units of distance now pull the next node from the priority queue that will be this node number two so pull this node number two and Traverse its adjacent nodes that is node number five now update the distance for node number five it would be the distance for node number two that is 5 plus the edge weight that is 1 that is 6 better than the distance that we already have for five yes we have Infinity for five so we update the distance to six also update the number of ways to arrive at node number five since we are visiting node number five the very first time the number of ways would be same as the number of ways for node number two and it is five so update the answer for node number five with two and push node number five into the priority queue update the nodes update the distance for node number five to six okay so now out of these three nodes that we have six three and five pull this node three because it has the shortest distance now for node number three Traverse it's adjacent nodes that is node number five and node number six now when we Traverse node number six we are traversing it again we have already visited node number three and if I visit node number six through node number three the distance would be five for node number three plus three that is eight is not better than the distance that we already have for node number three that is for node number six that is seven so eight is worse than seven so this is not counted as the shortest path to arrive at node number six so we just discard this pair or this node now we Traverse this node number five so let's calculate the distance to calculate to arrive at node number five so if I arrive at node number five through node number three the distance would be the distance for node number three that is five plus one would be six and it is same as the distance that we already have for node number five that means this is counted as the another shortest path to arrive at node number five because the distance is same so that means the number of ways to reach at node number five will increase by the number of ways to reach node number three because till node number three we have like some ways to arrive at node number three now from node number three we can just move to node number five so whatever the number of ways are there to reach at node number three will also be the number of ways to reach node number five so just add the number of ways for node number three into the number of ways for node number five and that is five so we have five ways to so that is one so we have one way to arrive at node number three so add one for five as well so for five we would have three ways now fine three ways right yes we have three ways because well it's not three it would be two ways because one is from zero to one then from one to two and finally from two to five and the second would be from zero to one then from one to three and then finally from three to five so we have two ways to arrive at node number five through row number three and through node number two fine so for node number two and three we have one way to one way for node number two one way for node number three so we add them that is two and that is our number of ways to arrive at node number five now we pull another node because we haven't updated the distance for node number five we have we already have the shortest distance for it so we pull the next node from the priority queue that is node number five now pull node number five from the priority queue and from node number five Traverse the adjacent node that is node number six so Traverse node number six and we can see that the distance to arrive at node number six through node number five would be the distance for node number five that is six plus the edge weight that is one so six plus one is seven better or it is the shortest path or it is not the shortest path yes it is the shortest path because for node number six the shortest path length is of seven units and definitely it is one of the shortest path to arrive at node number six through node number five so add the number of ways to reach at node number five to the number of ways to arrive at node number six and that would be there are two ways to arrive at node number five and two plus two would give me four so add 2 here and this will give me four so we have four ways to arrive at node number six now and six and we're not gonna push this six into the prior to queue because we haven't updated the distance array now pull the only node from the parity queue that is node number six and for node number six the distance that we already have is seven and this is indeed the distance and this we can see is the destination node six is the destination node so we return the number of ways right from there and we quit our while loop so we return four will be the answer so this is so in this fashion will be solving this problem all we had to do is just to just use one more array ways and keep adding the number of ways to arrive at any node by adding the number of ways to arrive at their parent nodes if we are arriving at the current node through the shortest path fine so that's the idea so let's just jump to the code implementation part we just have to use one more array there's no meaning in writing the pseudo code because the pseudo code is just the dash algorithm itself okay so this is a solution class where we have a count paths function initialize which takes in the two arguments the number of nodes and the roads Vector now here declare adjacency list of pairs of size n and prepare this adjacency list from the given roads array so we have bi-directional edges so we have bi-directional edges so we have bi-directional edges so create bi-directional edges fine so this is a d J now from here also declared two arrays let's say distance array of size n initialize it with one E15 very large number and a ways array of the same size initialize it with 0 initialize the very first node initialize the ways array for the first node to be one because there is exactly one way to arrive at node number 0 because we are just standing over that node now also initialize the distance array for node number 0 or the source node that would be zero and declare a priority queue this is just the usual diastra algorithm Vector of pair or it's not Vector it's po and then vector of Po finally will have a comparator pair PQ initialize this priority queue with the Source node so 0 and its distance is 0. okay the first element is the distance and the second is the node now also I am declaring another variable let's call it mod and it will be initialized to 1e9 plus 7 because we have to Output the answer modulo this mod because our output may be very large also we know that the edge weight may be large so just use long data type for the weights also you and use long data type for storing the distance and the number of ways so here I will be using for the very first number I will be using long so a priority of long end here also will use long fine now run the usual duster algorithm that is run this priority queue pop the top element from this priority queue that would be PQ dot top pop it from the priority queue and check if there is no scope for updating the distance so we know the node is P DOT first and P dot second and the distance is B DOT first so long distance it is p DOT first now if the distance for this node that we already have in the distance array is better than this distance that is tisd then continue to the next pair otherwise a trade over the neighbor nodes and for the neighbor nodes check if the distance for the neighbor node so we have the node to which we are going and the weight that would be long now we have the neighbor node as well as the weight to arrive at the neighbor node now check if there is a scope for improvement if the distance is greater than the distance that we arrive with this through this node dist Plus The Edge weight if it is the case then that means update this distance array for the neighbor node push it into the priority queue new distance and this node also here you have to update the ways array so ways for the new node 2 would be so here let's let me just let me enlist two conditions that we encounter while performing this algorithm that is if the distance to the neighbor node to which we are moving while performing the desktop algorithm if it is greater than the distance that we have if we arrive at this node through that parent node so and the weight so this DISD represents the distance to arrive at the parent node now if it is the case then what we what do we do in the dashed algorithm so this in this case where we are performing the relaxation the distance at the ways array will be updated like this ways to reach at this neighbor node 2 will be same as the ways to reach at the parent node that would be ways to reach at the parent node why it is the case because we are visiting this node 2 for the very first time like here when we were visiting node number four for very first time the number of ways to arrive at node number four were same as the number of ways to arrive at row number zero because we are visiting node number four as the adjacent node of node number 0 for the first time that's the condition otherwise if it is not the case if we have something like if the distance so let's call it else if the distance W 2 that means this is another path or another shortest path to arrive at this neighbor node in that case we simply count the number of ways to arrive at the this neighbor node 2 and we increment the count by the number of ways to arrive at the parent node so in this case the ways array will be updated like this ways to would be like ways to reach at the labor node plus the ways to arrive at the parent node since we have to calculate the answer over this mod so we mod it with this variable model so this contains 1e9 plus seven so in this fashion this ways array is updated in these two conditions finally at the end the answer would be simply ways to reach the last node and the last node is n minus oneth node and that's my answer fine so let's just code this code these conditions so here we just have to calculate ways to arrive at the parent node otherwise if this is yet another path to arrive at the neighbor node in that case just update the ways to waste to Plus face to move at the neighbor node mod fine and at the end return base and minus 1 mod fine so we return the answer right at the end of this function so let's just try to run this code okay it gave me positive answer so let's submit it okay it worked so that's all we have to do the time and space complexity says stays the same as for the test algorithm so that's all for this video if you like the video then hit the like button and make sure to subscribe to the channel and stay update stay tuned with me for more such videos and content on data structures and algorithm so I hope to see you all in my next videos
|
Number of Ways to Arrive at Destination
|
splitting-a-string-into-descending-consecutive-values
|
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer `n` and a 2D integer array `roads` where `roads[i] = [ui, vi, timei]` means that there is a road between intersections `ui` and `vi` that takes `timei` minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the **shortest amount of time**.
Return _the **number of ways** you can arrive at your destination in the **shortest amount of time**_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 7, roads = \[\[0,6,7\],\[0,1,2\],\[1,2,3\],\[1,3,3\],\[6,3,3\],\[3,5,1\],\[6,5,1\],\[2,5,1\],\[0,4,5\],\[4,6,2\]\]
**Output:** 4
**Explanation:** The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
**Example 2:**
**Input:** n = 2, roads = \[\[1,0,10\]\]
**Output:** 1
**Explanation:** There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
**Constraints:**
* `1 <= n <= 200`
* `n - 1 <= roads.length <= n * (n - 1) / 2`
* `roads[i].length == 3`
* `0 <= ui, vi <= n - 1`
* `1 <= timei <= 109`
* `ui != vi`
* There is at most one road connecting any two intersections.
* You can reach any intersection from any other intersection.
|
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
|
String,Backtracking
|
Medium
| null |
284 |
Jhal Hello Friends Welcome To Your Flight Should Be Vaikuntha Lok Shaitan 2 Medium Lal Problem From Digit Court Till Problem No. 218 More Problems Design United South East Self Financed Operational List In Addition To His Next And Next Operation OK Increment Till Previous Zombies Inside Him We Constraints two years will begin to return gift 10 inches below digest object which is given in this year exams in next week after no experiment in the year and month point to many cement stores next water system development and vitamin superintendent anil k tanik bullion hai next two years Till Elements In The Topic In Vitamin Scientific In Vitamin Actor Mere Next Element In The Without Moving Toe Point And 34 Peeth The Accused In This Case Constable In Which Sim Straight Element Which State Element But It's Not Moved From Hot Item Dab Class To Make Multiple Times Between 10am Element And Chittoor Next Filter Element And Will Not Going To Loot Element Electronic Tak Larson Understand What Are The Giving A Greater Class Which Implements The Editor And Blessings Subscribe Typing In Bright Sun Subscribe Button Half To Enter In The River Text Message Sonu Samay Tak Gir Elements Like Topic But Only Difference Is Going To Remove The Elements Next Time European So Let's You Have Elements Like To Three And Four Years Paper Multiple Times You Want You To So Let's Check Per Times That You Will Get You Will Remove The Sign *And Want to You Will Remove The Sign *And Want to You Will Remove The Sign *And Want to remove the battery Returns The Video then subscribe to the Page if you liked The Video then subscribe to Give It Rai Bachchan Drive C Replacement in More One Action Hai Snacks and Comment Functions on Addition to Profit What They Are Doing Is Page Function Bhed about and solution looking at the meeting also be going to take a look and conserve water slide show everything starts from corrupt and what is the biggest a parameter in most member important questions more return elements from the class one needs to interact with fast Translation of Typing in Inter College 22nd SEBI Director Suresh Ones with Write a Letter to Editors Will Have Multiple Values Rights Over to Use a Multiple Values Rights Over to Use a Multiple Values Rights Over to Use a Koi to Create a Variable in Its Members Real You Typing Teacher and They Are Going to Do This for Twelve Years After It's so let's you through input like 582 thirteen fourteen like this what they are going to versus we are going to the editor subscribe to the Page if you liked The Video then subscribe to The Amazing Vighn This Quote April 22 Siddharth Ungli Sindhu Subscribe to YouTube Channel Battery Snow White Item in the Nitrate Goddess Arguments to Unlock This Right and Knowledge Objective and See What the Match Player of the Day Speech Subscribe Gives You The First Elements Present on the Spot Remove Simple Method Not doing anything at all times every time you but witch acid and vitamin e channel na subscribe doosya hai black method flight subah employment network to use we are going to prepare attempt available next day special chahutan subscribe inside the temple inside the water treatment element ko Away The Came Into Force Making In The Real Debt And Avoid Traveling In The What Is The Return Of The End v5 First Form And Vitamin E Was Doing This Form Torch Light Switches Internet Banking The First Women Sleeping In Winters And When They Went To Request they are going to manipulate and back your addition a siddat policy where snacks and vitamins bullion 16 to time kind next this is such simple definitely statement of the one person on Thursday share subscribe now to family se return not equal to sweep unity 3371 Distic will be welcome active and this condition is not meant for now light condition for you must be curios to know what will be doing and year 2nd attend actual code but will be doing this will call this life will be good enough Liquid to software in to-do good enough Liquid to software in to-do good enough Liquid to software in to-do list check and draft letter of vibrator will use hai snake staff and iterator accepted yr din what they are going to vijayan ko into equal feet hai next android 2.3 front otherwise 12227 just signed android 2.3 front otherwise 12227 just signed android 2.3 front otherwise 12227 just signed by the way nice यायून टो return by the way nice यायून टो return by the way nice यायून टो return of all right the name of the first president of chipper nal tu whistle and van k sector-12 के सेक्टर 12 के सेक्टर chipper nal tu whistle and van k sector-12 के सेक्टर 12 के सेक्टर chipper nal tu whistle and van k sector-12 के सेक्टर 12 के सेक्टर बंक 10000 sample start which letter बंक 10000 sample start which letter बंक 10000 sample start which letter to the code and let's see how to get it as discussed that needs after winning stories of Readers will need it return of typing teacher and they are going to call details of the earth and this is nothing but the same after 10 minutes write and where going to have that interior call light show what you are going to initial is this is the first Indian to win in her eyes where subscribe to the Page if you liked The Video then subscribe to subscribe This dish increases the statement how your initial is developed ok so this point is the reason why I drop itr website twitter wikinews it where left his Next Fit is Joe Curfew Output Tax Well Into Inside Time And What Were Going To 2017 Lee Do Something Drop Down List At Alarm Wellington Test Sorry Exam Leaving You To The Same Thing But When More The Same Thing Has Well And Water Into Being Written Down More Than Not Equal Channel To subscribe The Channel subscribe School In Tears Variable No Matter How Hard Water After Point To End Decided To Support You Not Creating A Literate End With This Temple Visa Local Variable Message Will Be Town Halfway To Create A Thousand Times Square Without 1634 Quote And See How To Use A Hua Tha Jai Ho Om Maa Gauri Namah Jai Ho Om Maa Gauri Namah Jai Ho Om Maa Gauri Namah That I Should Be That Do Something About My Problem Tomorrow Morning Bachchan Magistrate Copy Paste Semester Comes Back To Meet Me Options My Brothers Will Win Or Lose His Original Loot Attended This Mistake Hai Talk During Voting 10 Okay But The Can Understand By The Small Role Super Man Chemistry Did Something For Intention To Give The Solution Video Of The Middle Age 102 Solution More Everything Step Away And Making Us Of Subscribe More Subscribe Interview Subscribe Very Difficult To Come Up With the way one side difficult and solution and country's tenth solution helpful we sample 14 exams years for you to understand and also this chapter in their thought process and the mind map behind the sentence solution so find this diet comment section and do subscribe to your Health Channel Se Grow And The Width Last Few Days Motor Sport In Love With Water For This Channel Saving Setting Almost Term 425 Subscribe Everyday But I Don't Like To Hear From You Guess What IF Haven't Been Hearing Not Tomato Comment To Do Feel To Airport Hum Comment And The Black Mature Woman Twink Was Doing Better If You Have Any Suggestions From You Let Me Know All These Things They Can Came Directly Below Better In Indore This Precious COD Solve Any Particular Problem From Any Particular Platform Dainik Anshu Yadav Link Android Ki Pet Urgent Royce Interactive S Possible Indore Ka Me Question Us Kaam Aaf Pitta And Detail Video To Explain The Mind Map Thought Process Approaching Solution And Water But Your Diet Chart For Undhiyo Second Disturb Lucknow Than More Child From This Video Benefits To Have A Great Weekend On Shiv Gas had come
|
Peeking Iterator
|
peeking-iterator
|
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
**Input**
\[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 2, 2, 3, false\]
**Explanation**
PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\]
peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\].
peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\].
peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\]
peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer?
|
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
|
Array,Design,Iterator
|
Medium
|
173,251,281
|
145 |
welcome to july's leeco challenge today's problem is construct binary tree from inorder and post-order traversal from inorder and post-order traversal from inorder and post-order traversal given an in-order and post-order given an in-order and post-order given an in-order and post-order traversal of a tree construct the binary tree we're given two lists one for the in order and one for the post order and we want to return or construct a binary tree from these two lists now we can assume that there are no duplicates in our tree and that's going to be a hint so why would that be why would we not allow duplicates okay so let's go to the whiteboard and try to think about the intuition behind this so let's first construct a binary tree and see what that would look like let's say that this was root one we'll go to two and three or five now what would this look like in order it's just from left to right left node right and it would look like if we were to do this in a list something like two one four three five this is the in order now what about post order well in post order if you recall it's just the left node right node and then the root node itself so that would be something like 2 4 5 3 1. all right so let's think of some things that we have to do the first thing that we know that we must know is that we're going to construct this binary tree from the root right and the only list that tells us what the root is going to be is the post order traversal this one here we know that the very last node is going to be the root so that's key this post order traversal list is going to be what's going to allow us to construct from the root first so why do we need this in order one like what's helpful about it well let's try to think of it at just like one node say that we start with one right and we start with one and say that this is the root now we move on to the next node number three are given at this one root one what could we tell using the in order traversal or the inorder list so if we look at one right here and we look at where one is in our inorder from our in order list we can see that 435 is all on the right side of our tree and two on the left side is our on is on the left side of the tree so that's big because that tells us what the rest of the binary tree is going to look like so why not just do some sort of recursive method where we first set the root and pass in whatever is to the right of the root in the inorder list and call that recursively to pass in this in order list because we know that our next root node that we're going to build is going to be contained inside this right side right past right side of the inorder and pass the left side in the left so pass left now i don't think i'm explaining this very well currently but let's just imagine now we're on three so we build one and we pass to the right side because we're going in the opposite order of post order right we have to go basically node or i'm sorry right left node so here we know that 3 is going to be the root and we can see that 4 is on the left side and 5 is on the right side right so when we go move on to the next one we know we can stop here because at five there's no more things to pass we've already passed in just the five and there's no more list left to pass so we can end our recursion there and move on to the left side at the left side um we just keep popping off of our post order and we know that it's going to be four and that's going to return all the way back here to two okay so this is key we need both lists obviously if we only have one we're not going to know where to stop the recursion we're not going to know when to go to the left or right so passing in using the in order list what's left on the right side what's left on the left side is going to allow us to know when to end our recursion so let's go ahead and code this out see if we could start making sense of it so let's say we're going to write some sort of helper method we'll call it recursion and we're going to pass in the in order and the post order now the very first thing we need to do is well we need there's a base condition but we'll skip that for now because we're not totally sure what that should be and we'll say uh first set the route and the route's going to be whatever's on the most right of our post order list so post order we'll pop off whatever is there and we'll create a tree node now we need to pass in what's on the right side of this root node and what's on the left side of this root node into our recursion and that we're going to pass that as our in order and we'll pass in the current post or whatever is left because we popped off the right one to the right side first and then to the left side so let's say we're going to first we need to know where this root is in the inorder list right so we could do that by using the index method so what we'll do is say get the index point of this list at the root value and since the root value is unique we know that there's only going to be one index value so we'll just call that the mid point now we'll say okay for the root.right now we'll say okay for the root.right now we'll say okay for the root.right pass in the recur recursion and we'll pass in our inorder but only this is going to be the right side so from mid plus one to whatever is left and we'll pass in the pre our post order as well now we do the very same thing but do it on the left side and finally we return the route and here we want to pass in um up to the midpoint i'm not sure if it's mid minus one i think it's just mid i believe and that would be it now we just need a base condition and you can see that each time we call this recursion like this is going to get smaller and smaller same with the post order so it's be something like if we don't have any in order left or there's no post over left then we can just go ahead and return now what do we just return our recursion since we'll be returning the route that's going to return us the binary tree so it's passing the inorder and passing the pulse order all right so let me see if i messed up anything here so far it looks good let's go and submit that and there accepted so this does work but it's not optimized because well not only are we doing this index search we're also using a lot of extra space by passing in like a new list each time so this actually ends up being a n squared time complexity we could improve it a little bit or significantly so the way you can do that is rather than doing the search each time we could make some sort of dictionary so let's make a mapper and what we'll do is say 4 enumerate or i'm sorry index value in enumerates the in order let's create a dictionary and say mapper for the value is gonna equal to the index number and instead of passing in the a broken up list why not just pass in the low point and the high point of the left pointer and the right pointer so we'll just kind of low and high and instead of saying if not in order in post order we could use this left and right pointer to be like all right if the low is greater than high then return and everything else should still basically be the same except we will instead of using this we'll use our mapper passing the route value and instead of passing in these lists we're going to pass in for the right side we want the right so that would be mid plus 1 to the high and to the left it would be low to mid minus 1. it would still be this passing the root now we just passed in zero and the length of either list will do the inorder because they should be the same size and one minus one so let's see if this one works and does and you can already tell it looks a lot faster and there we go and this would be a linear time complexity this would be o of n because uh we're not doing well we are doing passing it once to create this mapper but when we do our search we don't have to search through the whole list we'll be using a dictionary on top of that we're not using any extra space so this is um probably the optimal solution alright so thanks for watching my channel and just remember do not trust me i know nothing
|
Binary Tree Postorder Traversal
|
binary-tree-postorder-traversal
|
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,776
|
63 |
welcome to interview Pro let's solve another lead code problem today unique Parts two this question was asked in a number of companies so let's see what this question is about we will be given M byn integer array we'll be starting from the first cell we need to reach the last cell of this grid and the condition is we can move only to the right or to the cell below the current cell and there will be obstacles as well the obstacle will be represented by an integer one and if it's not an obstacle then it would be simply zero let's see how many unique paths we can calculate for this first example let's try to understand this problem we will be starting from this position and we need to reach this position this problem is similar to the unique path problem which we have solved in our previous video If you haven't watched it yet please go to the lead code the playlist and watch that video now uh the difference between the unique path and this path is there is an obstacle here so let's try to solve this what are the two directions that the robot can move to the right or to the bottom so let's take this cell to reach this cell what are the possibilities to come from either top or from left but there is no left to the cell so the only possibility is to come from the top so the number of ways of reaching this particular cell is equal to the number of ways of reaching the cell above it similarly the number of ways of reaching this particular cell is equal to the number of ways of reaching the cell above it because there is no left so as we are starting from the first cell in the grid let's assume the number of ways is equal to one because that's the only way uh we can start from the cell first cell right there is no other possibility because there are no cells here so this will be one now to reach this it would be same as the cell above it so this is one and to reach this cell it would be same as the cell above it which is one again let's take uh this first row now to reach this cell what are the possibilities to come from the top or to come from the left there is no top here so the only possibility is to come from the left so the number of ways of reaching this cell is equal to the number of ways of reaching to the cell before it so this is equal to one now this is also similar there is no top here so this would be equal to the number of ways of reaching the cell before it so this is one let's consider this cell this is an obstacle so there is no possibility to reach this cell so this would be simply zero now if we come to this cell what are the possibilities from the top or from the left it is anyways obstacle so it's zero the other possibility is to come from the top the number of ways of reaching this cell from the top is equal to the number of ways of reaching this cell which is equal to one so the sum is one same with this cell as well from the top there is no path so zero plus from the left we have one way which is equal to one now coming to the last cell it can be reached by coming from the top or from the left so we already know the number of ways of reaching the uh cell above it which is one so one plus we also computed the number of phase of reaching the cell before it so it is one so the total number of WS is equal to two which is uh coming from this way are coming from this way so if you look at the output the number of ways is two and what are those two ways right down and down so if this is the first cell right down and down then the other ways down right and right so this way this is the other way let's try to code this I'll be coding in C in order to store the number of unique parts for each cell we need a grid but we already have the input grid so I'll be making use of the same grid but in the interview just confirm with the interviewer if he or she is okay with using the existing uh Grid or they want a new Grid in this case I'll be using the existing grid only so uh what was the first uh consideration we are starting from the first cell so we can simply assign this cell with one let me do this obstacle grid of 0 equal to 1 so for the First Column we can simply assign uh the values coming from the cell above it for each of these cells because there is no cell towards their left so let's create a loop in the row equal to 1 because the first row is already assigned we don't need to consider that row so I'll be starting from the second row and uh let me create uh two variables here int m equals obstacle grid do length in n equals obstacle grid. 0 dot length variable M represents the number of rows variable n represents the number of columns so let's Loop through all the rows row ++ so in the obstacle grid for every row ++ so in the obstacle grid for every row ++ so in the obstacle grid for every row we'll calculate values for the first cell if it is since we are starting with Row one this would be our first cell here if the uh for if this current cell is zero in the original grid that means there is a space if this is one that means there is an obstacle so if there is a space we'll simply put the value which was computed for the cell above it obstacle GD row of zero if this is zero then we'll calculate the then we'll simply assign the value calculated for the cell above it otherwise we'll put zero similarly for the first row there is no cell there is no row above it so the only possibility is to come from the cell before it so let's create another loop here but now it is a column let me replace uh row with call now we'll uh assign the first cell of every column with the value which is equal to the cell before it so if this cell oh this should be zero comma call if the current cell is equal to zero that means it is a space it's not an obstacle and what can we do we can simply assign the value computed for the cell before it so Obstacle of grid obstacle grid of 0 call minus one if it is 1 we'll make it zero now for the uh first row and First Column are computed let's see for the remaining cells let's create a loop I'll simply copy this we Loop through every row and then through every column of that row so in this Loop let's say we are at this cell has an obstacle so what do we'll simply assign it with zero so if obstacle grid of row call equal to 0o will uh compute the values if it's not zero that means it's an obstacle so what do we do that uh in that case obstacle row call equal to zero now coming to this uh scenario where there is no obstacle what did we do we computed the value uh to the left and the value above the current cell so Obstacle of row and row comma call is Obstacle of row minus 1 that means the cell above it and also we need to add value coming from the cell before it finally we'll return obstacle grid of call minus one and R minus one this represents the last cell of the grid and one more thing that we did not consider is what if the obstacle is in first cell itself that means we don't have any path to compute right there is no entry to this grid so the number of ways would be zero let's add that condition as well if obstacle grid of 0 is equal to 1 Let's simply return zero let's try to run the solution uh okay there is a spelling mistake here let me update it also this is not the question mark it's a colon uh okay uh this is not row because uh the row is only for this uh loop we can make use of M and N so m and n i there is a semicolon missing here now let's run this the solution is accepted let's submit it uh but before that okay this column is uh should consider n yeah let's run this okay then submit it the solution is accepted coming to time complexity we are uh looping through each and every cell in this grid so it would be big of M byn coming to space complexity we did not create any new array here these are just simple variables and we made use of the existing grid so the space complexity is constant which is bigger of one I hope the solution is clear if you like the content please like share and subscribe to interview pro thank you
|
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
|
188 |
hey guys everything going this is Jay sir who's not good at algorithms in this video I'm going to take a look at 188 best time to spare and sell stock for we've already accomplished the previous three related problems which one two three please search on my channel for details if you want in this problem we're the requirement is basically the same except that we are asked to complete at most K transaction the previous one is 2 or 1 and infinity right now we are said to ask to do it most decay times how we do it well for this kind of problematic dynamic programming will be the best approach let's analyze the example like this so suppose for K okay so for K transactions let's just the direct go to the last element directly so suppose as we always do for dynamic programming if there is an optimal case suppose there are some so some trade picks of the index now if 3 is not in it then it actually just could be removed right it is the problem is same as we handle only the previous integers okay if three years in the optimal pick picks it's a company it's a pairs of index right buy sell so if it is in it then is it is by ID sell so there's must be a pair we index so which one is it might be three maybe two maybe six maybe five is zero right suppose it's in this then it means okay the indicate and most k transactions k minus one transactions at most were happen in the sequence big before it right so it's typically like dynamic programming let's suppose that a RK i means at most k transaction and end at that index high right so it equals should be it equals to if okay it equals to ship should be equal to let's write it down okay max right as we said it might be not might be unused so it so big said K I minus 1 right it is not used or it is used so it is used how we do it is used here are our I am as well possibility as the pairing parent comparing index so it's still another mad max so for supposed index is J with J from so J 0 to I minus 1 right as the beginning so what it will be of course it would be a K minus 1 J minus 1 right there's a edge case as when J equal 0 we handle in our code so basically it's a valid suppose K equals 2 it means we handled K minus 1 batch the transaction until 3 and then what we do with plus we plus a I minus AJ right so this is our formula we say we want to get came as I we now read we reduce it to redacted deducted we do it we just reduced to akk I minus one or I ke minus 1 J minus 1 for 0 to I minus 1 so anyway we were dragged the index K or I down right yeah so let's try to do it of course suppose so the result would be actually matrix we can use that we just use DP ok new array ok array kq0 map back to a rake a wrap to crisis feel 0 this is our result ODP okay now we all live through that T equals 1 TSP than equal to K T incorrupt and now we will for we now we will update DP t right so for let as we said and I ain't add index equals and that index we start one I smaller than transistor name I plus and what and then we will this could be get directly and this will be a form of to get right so he is for J equals zero this movie that I take over this maximum so like okay here max if used with 2-0 we say so max if u equals Mad Max it used with a which is TP k minus one which is a t minus 1 wait a minute we initialize that away from T okay now we get the previous one mmm that will get K there's no K actually there's no DP 0 there is but finally this week said TP t DB T that's got to be a problem to avoid things we better initialize it with +1 uh-huh right it's ok so now we with +1 uh-huh right it's ok so now we with +1 uh-huh right it's ok so now we get T ok this is gonna be alright and then D P max DP that's like this IJ minus 1 J minus 1 plus crisis I subtract process J now we said to DP t I actually man minutes the previous one so which is DP t I minus 1 ok so the T equals 1 because she starts from 1 it's the problem I'm so finally we could return DP ok yeah ok crisis button and that's what right that's right little malfunction what is it man Oh run answer so let's see what happened she goes up for I max if used what not number this is weird let's try to log with DP I have to be honest these problem actually cost me a lot of time see the submission so I'll try to reproduce the process I did at the beginning and to give you a better understanding I think ok I can lock the D key so basic ideas should be ok but now we get an or the first actually the first ok this here it becomes a problem it should be a 2 right what happened we look through 0 2 I minus 1 and then max use if max use DPT - i j- i ah here's problem you see DPT - i j- i ah here's problem you see DPT - i j- i ah here's problem you see we got zero but j minus 1 it's undefined Wow for this case I think we could insert a new false start and this was solve the problem no dpi DJ ah so oh no this doesn't solve the problem because J always start from zero and we need to if J is bigger than zero then this if not should be zero a little tricky get a try no seems like we are doing good let's try one more input like this - oh I one more input like this - oh I one more input like this - oh I think so it's actually working but let's just try to submit they will fail force the input always ask the input what kind of input are we getting for this while we're not guarantee that the array is not empty so if prices then equal 0 return 0 yeah Sammy oh we got a runtime error it says determine the call after an instance of bad allocation while so NEPA is huge and we got a K like 1 it should be this is a mean 1 billion pardoned minion million yeah meaning what is 10 billion I don't know anyway so the K might be super huge well it's can't you super how huge it is close to with infinity right for crisis like K like this if you want to a transaction we need a pair of start and end so actually the maximum will be half of the half of them in if K is over than that which means infinite so if we're infinite we have dead 112 to two best time to spy on the cell stock we have a different non DP solution which is act like a one pass yeah so I'll just a copy that code here this if you are interested please search on my channel and there's a detailed explanation on this problem I copied it like here max profit for infinite okay so it's add us extra if prices if K is bigger than prices but then divide by 2 to return crisis like this hmm okay this should also work submit cool you see works accepted we are accepted and that let's analyze the time and space for time loop k be odd the numbers and then all the numbers again and mm right and space of course music mmm but actually this is slow and a waste of space you see for the formula here we only use the previous one and K minus 1 there's no K minus 2 thing so we can only we can just use one array right to reduce the space complexity let's try to do it without these matrix we use a only one array it's like this right and now for each group in heat in here we will create a new array I will create a new one great which is the next array new TP yeah and the finally we return will you return DP so and the calculation is the same but we was said not the DP but said two new DP we get the previous one DP new TBT is not the bTW is new DP and DP t minus one is TP right so yeah and after it we said to dip into new TP that's right cool so we've successfully reduced the time a space usage from MN to linear which is n now for the time actually it could do better but I didn't come up with that I didn't come up with one actually so I searched from with materials and actually I still didn't understand their code because what I am going to improve so little different from their approach I just don't understand whether their code is but anyway the time complexity doesn't change so if you're interested please continue the stuff just continues just uh lemme let me introduce okay so you see for the loop here we're using new DP uh-huh we loop here we're using new DP uh-huh we loop here we're using new DP uh-huh we loop through the letter the numbers and gets the maximum and then from zero right you see what if I equals two we're still using J from zero you like it like so we're creating calculating over and over again let's look at more details about this equation the new DP I actually is equals to the previous one or the maximum fee I use maximum I'd use is the pre the previous one but previous iteration result Octavius one plus this and this actually does not change right this does not change if I took this prices I out it would mean like you see we update the max actually is the smallest of these work this so rather than we get in the max we can rewrite it to let main price equals infinity now we are getting the mean price would be math mean this is could be rewrite it like this right yeah so we could update the main prize two to one - this actually so prices two to one - this actually so prices two to one - this actually so prices Jack J sub subtracted between the DP Jake - one this Prentice is not Jake - one this Prentice is not Jake - one this Prentice is not needed uh-huh now so after this uh-huh now so after this uh-huh now so after this group we get the mean price and what we do we update to the prices i substract with mean trust right let's try it try run a code yeah still working now you see for i from 1 to the price and j from 0 to i we calculate the mean price this mean price actually depends on what only j and the previous DP j minus 1 right is only dependent this so actually in this iteration this mean price were not change you know what I mean so if I equals to this mean price RJ the so this may pass only depending on the J does not depend on the I is the relation with I yeah so actually this two could be merged together suppose like something like if you're duping through a two-for-one and for each index you're a two-for-one and for each index you're a two-for-one and for each index you're looping from 0 to 4 okay so we can actually catch that right just like what we did at the just like what we did here are not done this one but one maximal one pass one to one I think yeah so actually any price could be move out of this iteration Darmok it is clear so the outer loop looks loops through two four five one and the inner loops look through to two for one so it's actually the same the Minx prep doesn't change okay so now I'll move mean price out of the Infinity I move out from this outer circle cutter look and then to what so here's a little chain the J would be start from o1 it's okay right oh okay we wait a minute should I move the index the mean price we have to disk at any price so I need to move to 0 and then we remove this so mean price now becomes after the mean products so here should be what should be J I and if I figure than zero then it should be this right Christy P and zero yeah this should be right and now new DPI equals maximum max new dpi previous one max right if this if it's nothing or the mean price Prices I mean price and yeah and then we can update the db2 new one so this should work mmm no not number what's the problem aha I see so I see zero here is a problem okay we add the tannery here I don't know why these other peoples solution doesn't have this January maybe they have different understanding but I'm just the thing I just think this might be easier for me to understand this problem and it's just doesn't matter that much and yeah because this code could adhere to our assumption here right okay now you see we're accepted and reduce to 1 for do so we have improved the time to Oh mm right they try some it cool we're accepted and this one thing still we can improve the space you see where are you is linear space for DP here and we actually create a new space here so actually it's - it doesn't here so actually it's - it doesn't here so actually it's - it doesn't matter though but if you matter doesn't matter though but if you are going to - going to improve a little are going to - going to improve a little are going to - going to improve a little more we see that for the array we're actually using the previous only this one right so rather than we are storing the previous DP actually we can cache the previous updated item like this and improve the space though in that big o-notation it doesn't change in that big o-notation it doesn't change in that big o-notation it doesn't change let's try to do that so rather than convenient new DP we will say what I'll say just updated in the DP okay here is the new DP but DP is a problem so if we update it if updated with this updated right so before we update okay we set let pre this one is a let's create updated cool zero let's say equals zero so here because our array will be updated from left to right so when we update it we set it to before we update it we cache the previous result which is DP I and so now here we could get nah this is the previous iteration right so we could use proof updated I think you should work yeah cool but I don't recommend mmm idle will have a hard time I'd say it's hard to name this one what is it what's this it is a k minus 1 j minus 1 so yeah so I'd rather say we stop increment incrementing implementing this one but keep the stick to the new array approach ok so that's all for this problem hope it helps actually it's very I think for me it's very difficult one until now I still don't understand how the other people's to win it without this ternary maybe we have a different formula anyway our basic idea is the same hope it helps see you next time bye
|
Best Time to Buy and Sell Stock IV
|
best-time-to-buy-and-sell-stock-iv
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.
Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** k = 2, prices = \[2,4,1\]
**Output:** 2
**Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
**Example 2:**
**Input:** k = 2, prices = \[3,2,6,5,0,3\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
**Constraints:**
* `1 <= k <= 100`
* `1 <= prices.length <= 1000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,123
|
352 |
hello guys today I'm gonna tell you about these questions in the lead code for the 352 data stream as destroying intervals so as we can see the questions if someone doesn't understand what does it mean I will explain here so as we can see here he gave a data stream input of non-negative integers so it input of non-negative integers so it input of non-negative integers so it means there are positive indicators and from A1 to a summarizer number c and files at least destroyed intervals so as we can see it's intervals but it's disjoint so what does it mean it means like the intervals for example like one two three four five days are the consequence numbers from one to five but it is from one two three and five six it will be like one two three is consequence but five six is consequence because between three and five there has no fall in the middle okay so let's talk about how can we write the code here so at beginning I will make a three side so make a side so because we are not sure how can we make the whole account because we need to return the two to the array so then to the array but we are not sure the size of it so I will make it to the list first and then in the end I will translate to the uh to the array so we are gonna need a side here as an integer side at the beginning is no okay and for the summary ranges will you we will make it like set equals new tree side okay and for the for this method like at now we can just add it directly so we can add directly foreign here but for the convenience I would like to change here to the vibe like here it will be either for us to type okay and now it's a important part so from here we just uh summary ranges it's just make a new site but here we just add the numbers directly because we use the side but here we need to um from this part we have to make it to the intervals so as I explained before like if it's from one two three and four and five six the intervals will be comes to one three and five six right so at this method get inverse we are going to make this method to become true so uh as I said because we are not sure in how the return power for the um for the array so we have to I just use a list here and in the end I will transfer from list to Larry so at least in to the rice so racism is the result of this right so new array list okay and we use integrator here because integrator is easier for us to Traverse the list so I use integrator iterator uh iterator integer okay and now we have to make the boundaries so boundaries between left and right what does it mean it means like we have to make a boundaries like one three or five six but at the beginning the boundaries with we don't know so we make it awesome uh minus one at the beginning so we make a boundaries uh or we can say limit here limit for each interval here so it's in life equals minus one and in the right equals minus one okay so now we are use while loop to search our list to Traverse our list so iterator there has next so at this time if it has an X so it will just uh oh no we cannot use Auto uh okay whatever we just continue to use it uh because iterator the next so at the beginning we just make the atom is the first value in our iterator an iterator is our result list so resulted by result list is the sub in a so it the iterator is a set is what which we add the number to the side so from here the iterator first is the first number we add here for example here is one and three and seven like this extra okay so uh and yeah so if uh if left equals minus one means like the left is still is a default value and left equals right equals atom it means that so is this part means like for example here the one is at the beginning so as we can see here is only have one so it means like this meaning okay and if it's not else so from this part we can see like it's not at a at it's not empty so we have to check if inside our and inside our list or inside our array if there has already have a part of it so for this time we have to check if the new item we are going to add in is already in the internal which our list internal Authority including this item or not so at first we have to check if it's Consequence the consequence for example one two three four five six uh is one two uh five six so we have to check if it is already consequence by our new atom so in this if write plus one equals icon means that our new atom is the last value is a red top value for this interval it will be right equals to the item all right and if it's not consequence we have to uh add the uh so we have to add the interval inside our rest list so it's less list dot I it left right yeah so if it's not already inside we have to add this to the new rest list and in this time left equals right equals item all right so at this part we're still not finished yet we have to add the last interval of 12 rest leaves add last interval to the rise list so it's rice this start by new hint left right okay and the last step is we have to we need to transfer our list to the uh red okay how can we do that is we create a 2d array name as a new hint rights the star size and we know it's the two so it's the epidemic right so for in we make a follow I press the star size all right and then press I equals rise please don't get app and in the final we return the rest so basically this is our code and you can see just the way the important part is here the get intervals so all we need to do is just to find if it's uh already in the consequence or not so basically this is it so let's run and check uh oh I it's a typical term okay yeah so it's exciting okay thank you for watching bye
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
797 |
um hello so today we are going to do this problem which is part of lead called do some birthday challenge so the problem is all paths from search to Target so we get a directed acyclic graph um so this piece is important with roads that are labeled from zero to n minus one and uh we want to find all the possible paths from node 0 to node n minus one and we want to return those paths in any order and the graph is given as a list of lists right and what this represents is basically that zero is has an edge directed Edge from 0 to 1 and from zero to two and here that there is a directed Edge from one to three and here from two to three these are not bi-direction right because these are not bi-direction right because these are not bi-direction right because the graph is um basically directed acyclic graph it's director right so you can see here we have 0 to 1 to 3 that's from this one we have 0 to 1 and 0 to 2 which is from this one here and then we have uh two to three and then for three it has no Edge from it to anything and so nothing here so what the problem asks us to do is to return all the paths from zero to three uh because n is equal to four and it's the length of the graph by the way um so we want to return all the paths from zero uh to three here uh because three is n minus one so we have we could go like this so from zero to one to three that's this path here the other path is going from zero to two and then from two to three and that's this path here and those are the only two paths we have so we'll return both of them um so that's the idea here now how do we solve it well it should be a pretty simple either DFS or BFS right because we can just keep traversing until we reach and minus one append the path and then keep traversing again until we get all the paths right um so pretty straightforward actually now let's first do it with uh BFS I think it's easier and then from there we can do it with DFS um so what we need first for our BFS is just a DQ right so that we need to start from the start swing position which is for us is zero because we want the path from zero to n minus one and we can just pop from the front right that's what we do with PFS um and then the traversal for the Neighbors uh remember in the index is the node and the value is the neighbors right so for a node to get the neighbors we can just do graph load could we can append um the neighbor but we did the path right we need to return the paths so in our state here we need to keep track of the path and so the path first for starting from zero has just zero in it and so here when we extract pop we get a path and so here we need to add the neighbor because we are just visiting this neighbor so we need to add it to our path so path plus the neighbor right uh okay and now we uh so now that we have that for our queue here we need to check if we reached the one we are looking for our destination which is n minus one so how do we get n is just the length of the graph um because each slot is the is a node and so to get the number of nodes it's just the length right um so if it's equal to our destination then we want to add it to our list of paths we want to add this path here right this path here because this path is from 0 to n minus 1 right and we need to Define of course a list of our paths that we return at the end um and so that's should be pretty much it um we get the paths and then we uh when we find it works out you may ask why do we maintain a visited set um and just check that we haven't visited it before well because the problem says that this is a directed acyclic graph so there is no concern of there being a cycle and getting um in a loop in a cycle so it's not possible because we are it said here that it's acyclic um so let's try this one on it and let's submit and it passes out of test cases okay um okay so that was the BFS version now let's quickly do it with DFS so we still need the paths here um but we just need to start our DFS from a node right and we need of course the path as well so we need to start our DFS from the starting node and path has first is just the starting node right now here since we are modifying a set of function we just need it to be a self variable here or the class and here we just need to go through the Neighbors in the same way that we did with the BFS and what we need to do here is just recurse so instead of adding to the queue with a curse and so to the neighbor and then the path we add neighbor because we just visited it right but here we also need to check that if we arrive it so if the node is equal to n minus 1. or rabbit at our destination then we want to add this path right so this would be self.path right so this would be self.path right so this would be self.path right and this path would have n minus 1 because we would have added it here before calling the DFS again right um and again here also we don't need visited set because of the same reason as for BFS it's a directed escalate graph um and that should be it right um so let's on this I'll submit and that passes as well right um yeah so that's pretty much it for today's problem please like And subscribe and see you on the next one bye
|
All Paths From Source to Target
|
rabbits-in-forest
|
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**.
| null |
Array,Hash Table,Math,Greedy
|
Medium
| null |
673 |
hello and welcome back to another video today we're going to be doing number of longest increasing subsequence and so this is pretty much a follow-up to the this is pretty much a follow-up to the this is pretty much a follow-up to the problem that's uh called longest increasing subsequence only code and it's a very popular problem and I would definitely suggest you do that first and I do have a video for that and I will link that in the description below but in this problem we have a variant of that where instead of returning the longest increasing subsequence we need to be returning the number of longest increasing sum sequence so if there are multiple subsequences then we need to be returning that number that are the longest so let's go through our stuff so in our first example we have one three five four seven and we're basically trying to figure out like how what's the longest subsequence and how many are there so we have one subsequence of 1357 and then we have another one three four seven those are the two longest and they're both length four so we need to be returning two here okay now for the second we have two and so for that's each one of these is a one length subsequence and so the longest subsequence in this is one and we need to be returning five because all of these are one subsequence of length one need to be returning five all right so let's get an intuition on how we actually do a problem like this and then let's figure it out right and so we're actually going to do is we are going to do another example though so what we're going to do is we're going to take an example like this we are going to take one two three okay and this is going to help us demonstrate like why like what we're actually doing here essentially so like Where Do We Begin essentially so what does make the longest increasing sum sequence well it's going to be a subsequence that's increasing but how do we actually figure that out and so from my previous problem let's actually start off with this right here and then we're going to be deleting that and move on to this top one so let's just start off with this one three five four seven and now let's just change our question to let's just get the longest increasing sum sequence here not like the number of them but just like what is the longest subsequence how do we do this well it's gonna be pretty straightforward so what we're actually going to do is we're going to take an array here and we're going to initialize every single number to one and then we are simply going to go through all of these and the thing we're going to do is we're going to Loop through all of the numbers before the number we're currently at and just say is that number smaller and is that subsequence longer than the one I currently have so let me show you what that's going to look like so for like this number one we're going to say okay are there any numbers before one no so we're gonna skip that because there's nothing there okay for this three are there any numbers before three and what's their longest increasing subsequence and is this number bigger than the other number so let's take a look so for three we're going to check one and we're going to say okay well it's 3 bigger than 1 yes so then what's the length of the longest increasing subsequence with the one it's one so if this subsequence is with a one well one three is a subsequence right so that right there is going to be a bigger subsequence so then for three we can actually make this a two because we can use the one with a one now let's go to the five so let's delete all this and let's go to the five and we once again we're going to check everything before and we're going to say like what's the biggest subsequence we can get so we're gonna check the three and that is length two is the five bigger than the three yes so whatever subsequence end with three right whatever is over here we can just add a five to the end and that'll be the length of that one plus one so that's going to be three and then when we check we can also check this one but this is only a one length subsequence so then this one would be bigger so we're going to want to select this one okay and this is pretty much how to do the longest increasing subsequence not the number and then we're going to see what changes in the number okay so now we're at this four and we're going to check other numbers we can check the five so the four is not bigger than the five so we can't use that but we're gonna check the three and clearly we are going to use a three so the three is length two subsequence so we're going to use that and we are going to add one to that so it's going to be length three then we're going to check the one and the one is only length one so this is only going to be two and we're going to want to maximize this number okay now for the seven we're going to check the four and we're gonna say oh there's a three there so let's just use that and add one so for the seven we're gonna have four here right because if this is length three then we could just add a seven to the end and now this is length four now we're gonna check over here it's like three so it's the same so we don't need to do anything and we're going to charge over here it's two so that's smaller than what we have because now we'll have three so we don't want that and finally here we're gonna have one so we're gonna have two so we don't want that so finally we have this array of one two three four and now our longest increasing subsequence we can just take the max so how does this problem change when you want all of them and so let's actually look how that changes we remove all of them so we're actually going to write this one three five four seven uh down over here and then we're gonna do this big thing later on so for this one three five four seven once again we're actually going to keep it here and but now we're gonna redo this so we're gonna make another we're actually gonna let's just delete this now that we went through how to do all that so let's draw another one down here same thing with the ones and like what's the difference well the difference is we might have multiple subsequents that are the same length and we need to have we need to keep track of that so we need to slightly change our algorithm to where if we have a subsequence that's the same length we need to figure out like how many were there right so instead what we're going to do is we're actually going to change this instead of this we're going to actually going to have arrays of two so let's actually take this delete it and let's actually show you what we're going to do here so we're going to have arrays of two numbers because we need to keep track of what's the longest subsequence and then how many Subs how many of those do we actually have right so we're going to have five arrays of just one sub 1 . and it's going to be just a slight . and it's going to be just a slight . and it's going to be just a slight modification to the other problem except now we're just going to maintain a count of like how many of these do we have and then once we find the longest one we can just add up all the counts of however many there are okay so we're gonna do kind of the same thing and let's follow along here so for the one we're going to go over here and there's nothing there so we can't do anything there now for the three we're gonna check is the three bigger than the one yes it is okay well how many subsequences end with one right and if the 3 is bigger than the one that means we need to update that biggest subsequence for the three so for this three the biggest subsequence so far so we're gonna write this down so index 0 is going to be length of subsequence index one is going to be count right so like this is saying that the longest subsequence is one and there's one of them okay anytime we find a greater one then we're going to reset our count to one because let's say our subsequence is length or not we're not going to reset our count to one we're going to reset our account to whatever the count of the one that we found was right so let me show you how that's going to work so for this problem we're going to go over here we're going to say okay well 3 is bigger than one so this is a subsequence of length two right so we're gonna update this two and then we're actually gonna say okay now that we updated our subsequence well how many of subsequences were there that ended with one like let's say our thing was just like one three well if there's like four subsequences that ended with one we're gonna have to you know update that and so what we're actually going to do is we're going to take if we update our soap sequence we're going to take the number that the other one had and we're going to put it over here and so because this one only had one subsequence we're going to have a 1 here for this 5 we're going to go to the 3 and we're going to say okay so is 5 bigger than 3 yes it is so that's a bigger subsequence because our subject is only length one so far so we can make a subsequence of like three so let's change that but how many of them are there well how many of how many subsequences of length of that ended with three were there where there was only one so now we're gonna have one okay now we go to the four or sorry and then for the five we're going to go to the one and we're also going to check that as well right how many are there but also the biggest subsequence here would only be two so we don't want that okay now we're going to go to the four and we're going to compare to the five and we're going to say okay well how many subsequences or sorry can we even use this no because force smaller so we're going to go to the three and we're gonna say we definitely want to use this so how many subsequences end with three well it's only one and so then we're going to update the subsequence for four to be length two and then there's only one of them because there's only one over here and then we're not going to want to use oh sorry uh this needs to be a three right because the subsequence that ends with three is like two and now when we add a four it's going to be length one or three okay so we're going to delete this now and we're gonna go to the seven so for the seven we're going to check the four and we're gonna say okay do we want to use the four well yeah because it's the 4 is a subsequence of length three so now we can get a subsequence of length four and how many are there well there's one so we're gonna have one now what we're going to do is we're going to check the five and we're going to say okay well is that going to be important well yeah it is because for the five that is also link three so if I use you know dot five seven this is length four and we also want to use that right so we want to use this subsequence and so here what we're going to do is we're going to say okay well we're going to want to use the five because that is going to be the same length as the current one we have so if the one we found is bigger we're going to want to use that and we're going to want to update our count we're going to want to essentially reset it to the one we found but if the one we found is the same we're gonna have to keep adding to our count right like if we can keep using multiple numbers to make the same length subsequence we need to keep adding all those and so we're going to ask ourselves okay well how many subsequences n over the five well it was one and we already have one so we have one plus one so we have two okay and now finally then we check okay what's our longest subsequence well remember the length of the subsequence is the first element in all of these arrays and so what's the biggest one well it's a four and so now we need to just go through all these arrays check every subsequence with length four and see how many counts there are we adding to add them all up so in this case it would be two and that would be the answer and so let's write down our steps one more time over here and then we're going to go do this tougher problem so we have two we have uh two like things that can happen so one if our subsequence needs to be updated to a bigger one we update it and we take the count of the one we updated from okay step two if our subsequence is the same length as another one we need to add the count from the other one to this one right so these are two if we need to update our subsequences then we're going to reset our account initially or essentially and if we're going to keep if we have multiple things with the same subsequence length then we need to keep adding to it right so let's say all of these were subsequence length three right all of these then we would say okay for the seven we could use the four we could use the five we could use a three use the one and so we need to add all these counts up so we'd add like three and now we'd have 12 in here and so this is kind of what we need to do for this problem so let's just try to go through this problem now knowing what we have okay so we're actually going to copy this and we are going to give us more space up here and let's try to go through it so we're going to do the same kind of thing essentially might be a little long so maybe I won't do every single step but let's see how it goes so we're gonna do the same thing where we make these arrays of one and one initially so how many do we need three five eight okay so one two I think I can actually copy these and just do this a little faster um there here like this a little uh let's make this a little bigger so we have space let's delete this and let's copy it and put it over here and let's finally have a closing delete this okay so let's go through our steps again so for this one there's nothing so we don't need to do anything now for this one remember it has to be strictly bigger so we can't use that either and we can't use that either now let's start with the two that's where we kind of start doing things okay so for the two we can use this one right and so that would be a subsequence of length two and it would be count one so we can use this one so that would make a subsequence of length two but we can also use this one and so that's another one so we need to add to our two snare subsequences is going to be like two and we can also use this one so it's actually gonna be sorry subsequence length two but we can use three different ones right so we can use this one too this one two and this one two we can use all of those so because we use each one of the ones we need to take all of their accounts in that amount right so there's a one and that's why we made it a three now for this too it's going to be the same thing right we can't use a 2 but we can use the ones and so that's going to be the same thing it's going to be 2 and then a 3 here now let's use the threes okay so we're gonna go over here and we're gonna say okay well we can use this one for sure right so what's going to be the answer there well it's going to be 2 plus 1 so that's going to be a subsequent length three right so I'm SQL flank three and how many were there well there were three right so there were three here but look we have three here but we have three here as well right so we need to be able to use both of us we need to use these and we need to use these so that's going to be six total now and here there's going to be six as well with the subsequence length three and here there's going to be some sequence like 36 as well right because this three you can use both of the twos because they're the same like and this three can use both of the twos okay so now this is going to be our output and now what's our longest subsequence well it's length three how many are there's six here and there's six here so there's 18 total and so now you see how you need to keep adding these counts and if you anytime you reset you're going to reset the count but if you have a subsequence that's the same length you need to keep adding these counts and then finally you just go through your nested arrays you find the biggest subsequence and you add up all these accounts so now we have enough to be coding so let's do that so we're actually going to keep track of the biggest subsequence as we're doing this so we're just going to say like longest equals one and we're going to keep track of it as we're doing this okay so we're going to make our DPS so we're going to say let's make it one for I and Rain length right we're just going to make a bunch of one ones and how many is it going to be it's going to be uh you know the same length as this nums here okay so now we're going to Loop through our DP and remember we need to Loop this way and then for every number we need to check every number before it right so we're gonna say for I in range link DP then we could say 4J in range I because we only need to compare this to every single number before it right like in our picture like if we're out of three we're gonna need to compare to this all of those this is essentially an N squared algorithm so now we have two cases remember so for our first case is so first we need to actually check can we use that number right so if num's I is strictly greater than num's J that means we can use that number now we have two cases do we have to do we have a bigger subsequence or is it the same so let's go for the bigger one first so DPI zero this is going to be the length of the subsequence is less than dpj 0 plus 1 meaning like in this example like let's say we go over here the subsequence length is two so then we would add two plus one we'd have three and we are asking is the length of the subsequence that ends with this three that we currently have you know smaller than three and if it is then we need to update it and we need to update the count and we're going to reset the count here so we're going to say DPI zero is going to be we're going to make it equal to GP J zero plus one that's the length of the subsequence now we need to take care of the count so dpi1 is going to be DP J1 right whatever we took it from let's just use that count now we have the other condition where they're the same and so this is going to be very similar code so just copy some of this so now if these are the same so if these are the same what do we need to do we actually need to update our count to add the count of whatever we found essentially right so if they're the same then we need to update the count to have the to find the to add the count of whatever we're not going to reset it because we're not changing our subsequence length but we are going to update our account okay and so finally we are also going to check for this longest subsequence and so the only place we need to check is if one of these happens then we actually need to check like what's our subsequence like now so we're going to say a longest equals Max of longest mdpi zero which is going to be the subsequent the subsequence length okay so we can actually do that here we can actually put that in here I believe we don't need to do it when we add because this is not going to change the length okay so we can just do it here only when we increase the length all right now what we need to do finally is we have our longest count now we need to add up all of the counts essentially right like we have our longest subsequence so let's say it's like three in this case now we need to add up every single count where the first variable is three and so we could actually do that with a sum so we can say like just a one line thing so we could say like okay let's just take i1 right so let's just take i1 for uh let's see here this doesn't need to be like this okay let's just take i1 so this whole thing needs to be a list because we're going to sum up a list okay let's take out one for I in DP if I zero equals longest uh too much JavaScript okay so we're essentially what we're saying is we're saying let's add this i1 to the list let's add this count to the list if the first element equals the longest right so in case or longest is three so we're going to say like okay is this three no we don't need this element is this three no then finally here we're gonna have yes and so our list is gonna look like this and we can just sum that up right so we're essentially just doing that in one aligner you can have a if statement where you do some other stuff and that'll work as well so but it doesn't cost us anything to make this list because you know we already have like and then we already have it list as well so it's still going to be n time and sorry no it's gonna be in space okay so we have a solution it works now let's think about the time and space here and yeah I kind of wanted to do more um bottom up because I feel like most of my problems have been top down memorization so I think it's good to learn bottom up and in not in this case but in some cases bottom up is actually a more efficient algorithm and it's good to know both so I think if you are good at memorization I do think it's a little bit more straightforward than practice some bottom up as well for this problem bottom up it's just a little bit more intuitive but in general I'm probably going to start doing more bottom up just to you know practice both okay so for our time we are going to have a this is going to be n and this is going to be n again so it's N squared essentially and then this is all just like o of one so our time is going to be N squared where n is the length of nums and then for the space we are just storing uh two numbers for every single number in length nums right so that'll be like two times n which rounds down to of n all right so that's gonna be for this problem actually and if you liked it then please like the video and subscribe to the channel and I will see you in the next one thanks for watching
|
Number of Longest Increasing Subsequence
|
number-of-longest-increasing-subsequence
|
Given an integer array `nums`, return _the number of longest increasing subsequences._
**Notice** that the sequence has to be **strictly** increasing.
**Example 1:**
**Input:** nums = \[1,3,5,4,7\]
**Output:** 2
**Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\].
**Example 2:**
**Input:** nums = \[2,2,2,2,2\]
**Output:** 5
**Explanation:** The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
**Constraints:**
* `1 <= nums.length <= 2000`
* `-106 <= nums[i] <= 106`
| null |
Array,Dynamic Programming,Binary Indexed Tree,Segment Tree
|
Medium
|
300,674
|
55 |
in this video we'll be going over jump games so given rate of non-negative games so given rate of non-negative games so given rate of non-negative integers nums you're initially positioned at the first index of the array each element in the array represents your maximum jump length at that position determine if you are able to reach the last index so our first example we have two three one four we initially start at index zero and we can make one jump to index one here and we are allowed to take three jumps one two three to reach the end of the array so we can return true let's go over the thought process let's first find a brute force approach we can implement a recursive that first search approach this means for each of the index i we can check we can reach the end of the array with up to nums i steps this means we will recursively check all of the options from i to i plus nums i in order to determine we can reach the last index now this approach will cost us of k to the n time complexity where k is the number of is the average number of steps in each of the index and n is the length of the input ray this is because in each of recursive call we allow us we are allowed to take up to k steps and each recursive call has a depth of n now let's find a more optimized approach in order to opt more find a more optimized approach we have to scan from right to left instead we will be scanning from left to right while keeping track of the latest index that can reach the last index now let's go over a simple example so in our first example our latest index that can reach the last index is currently at zero one two three four so latest index is go to four that can reach the last index now let's move on to the next elements it's currently at one here so we're currently at one and then we want to check if in this position we can reach the latest index so one if we take one step you can take you can reach the latest index this means this position this index can also reach the last index so we want to update our latest index to 3 because 3 is index of the current one now we want to move on to the next element it's currently at 1 here now we want to check if this position can reach the latest index one can take one step to reach this index this means this element can reach the latest index which also means can reach the last index so we want to update our last index to index 2 which is the current index now we want to go to the next iteration recurring at this position and three we can take one step we are allowed to take one to three steps but if we take one step we can reach this index already and which means we can reach the latest index which will also allow us to reach the last index so we update last index to one and now for the last one we have our uh we're at this position and then we're index zero and index zero if we take one step we can reach this index which is our latest index and we have found uh and then we can't we are allowed to reach the last index so we update our latest index to zero now if our latest index is zero which is our initial starting position here and is the last latest index and being the latest index also means you are able to reach the last index that means we can return true if the latest index is equal to zero now let's go over a pseudocode so we're going to create a variable j to keep track of our latest index so it's going to initially be the at the end of the ring so it's going to be lumps on length like lumps down length minus 1. so i'm going to iterate through the indices from numbers down length minus 2 to 0 denoted as i we're scanning from right to left so if the current elements can reach the latest index so nums i plus i is greater than or equal to j that just means we can reach the latest index on the current position we can update the latest index to the current position then we can return true if j is equal to zero else return false now let's go over the time and space complexity so the time complexity is go to of n where n is the length of the input ring this is each index ones now our space complexity is go to of one now let's go over the code so i'm going to create a variable j to be our latest index and then we iterate through the loops uh iterate through the indices on this second to last element to the first elements using current elements numbers i plus the current index can reach the last index so greater than equal to j that means we can update j to the current index then we can return true if j is equal to zero this means we allow the latest index is equal to zero this means and also the latest index can reach the end of the array let me know if any questions in the comments section below like and subscribe for more videos that will help you pass the technical interview i upload videos every day and if there are any topics you want me to cover let me know in the comment section below
|
Jump Game
|
jump-game
|
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** true
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[3,2,1,0,4\]
**Output:** false
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 105`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
45,1428,2001
|
111 |
hello everyone uh welcome back to pseudocoders uh today we are gonna talk about the lead code uh 111 problem minimum depth of the binary tree uh this problem is uh basically a very basic problem that can be asked in an interview question interview so let's move on let's get on with it uh let's read what the problem is so it says uh given a binary tree by its find its minimum depth uh the minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node a leaf node as a node with no children so yeah so let's understand the problem first so it says find out the minimum depth of the tree let's first understand what is the depth of the tree okay so let's take an example here so it says that is the number of nodes along the shortest path from root node to the nearest leaf node uh so basically depth is a distance from root node to the left node right so in this scenario and what is a leaf node first a leave node is a node where there are no more children okay so if you take into consideration this example one uh it's a it's you can see that there are three leaf nodes right uh 9 15 and 7 because 9 has no children so this is a leaf node 15 has no children yes leaf node is 20 year lafler no because 20 has two children 15 and 7 and what about seven is seven a leaf node yeah so in total we have three leaf nodes here okay so how do we find out what is the depth is the number of nodes from root node to the leaf node so if we so in our scenario our root node is three so let's uh understand what is what are the different three depths in this tree right because we have three leaf nodes so we will have three depths from three to nine it's from three it is one and then from nine so there are two nodes that we need to hop on in order to reach the leaf node so the depth here is 2 whereas in order to reach 15 you have to go from 3 to 20 and then from 20 to 15. so in this scenario our depth is going to be 3 because you move from 3 to 20 and then 20 to 15 there are three nodes in the way so the depth is three for the say uh for seven it's going to be three from three to twenty and then from twenty seven so it's going to be 3 again because there are three nodes okay so now that we understand the problem correctly let's uh think of how we can solve this problem right um this is a classic uh breathful search problem uh because um so if you don't know what breadth first search is uh you can watch a video that i shoot in um it's in the description below you can find the link and there i have discussed you know a basic uh a basic code that we can use in almost every breadth first search algorithm so i usually use that code in all of my breadth first search algorithms and that code kindly fits in uh it's a basic baseline of breadth first search and obviously you can have the customizations that each problem brings in to that particular code right so let's uh hop on to our sketching and drawing and see how this how we can solve this problem using breadth first search okay so we have our example ready we are taking the same example uh as in the problem so firstly uh i want you to understand why are we using breadth first search right um while using breadth first search we do level vice parsing so what happens is first we pass this level and then go to the slope so when we do level by sparsing so suppose we first parse three and then pass all of its children now we encounter nine as you can see we will always find a leaf node of the shortest path from root to the leaf node when using breadth first search because we are going to get we are looking for all the neighbors and when you look for all the neighbors the one that we encounter first would be 9 and this will be at the shortest path from root so this is the reason we are using uh breadth first search to solve this problem we are going to use a q so let's have q in place okay so the algorithm goes in such a way we uh add this root to our queue and then we need to have you know the track of the depth of the tree right so what we are going to store in the queue is the root itself and then its depth so from root we start so root is one node so we add one that is the depth okay so this is a queue what we will do is while the queue is not empty we will pop out this element from the queue now we have a current our current is 3 and our depth here is 1 okay now we check if 3 has any neighbors 3 has neighbors right so we will add them to the queue we add 9 now what will be the depth will be the current depth plus 1 so the current depth is 1 so 1 plus 1 2 right then we add we need to add 20 as well so we add 20 and depth is what current depth plus 1 current depth is 1 so this will be 2. now we move on we pop out the first element again from the queue we pop out nine so now our current is nine and our depth is now two right now we see that is nine a leaf node yes 9 is a leaf node 9 doesn't have any children so what we do is we simply return the depth which is 2 in this scenario 2 is our answer right so this is how you do depth first search uh to find minimum depth of the tree let's write some code in order to uh to write down what we have actually studied so let's go on to the course okay so let's write some curve um first the basic condition that we need to check is what if the root is none so it's a notice that there is actually no depth right so we can just return 0 so we will check if it's the root is none then we can just return 0 otherwise we need to have a queue in place and we need to have it which is initially one and then what you do is you do q dot append and what are you going to append it is basically the root and then the depth right so i append the root and then the depth okay so now we are going to traverse through the queue and then process all the elements that are there so let's say while the queue is not empty what i'm gonna do is i'm gonna pop up the first element so we're gonna pop out q dot pop of zero so pop-up zero basically pop of zero so pop-up zero basically pop of zero so pop-up zero basically gets us the first element in the queue now what we check is we check if the current element is not is a leaf node or not so we check if current dot left is none and right is none so if the if my current node has no children then it will be a leak node and what do we do in such scenario we just simply return the depth so what we do is we return d which is the depth and what if this condition is not true what if the uh element has more children then we need to add them to the key right so we do a current element dot left then i add it to my queue so i do q dot append and then a tuple current dot left and depth plus one because we are going to the next level so we need to add one to our current depth if the same thing i want to do it for the right node as well so current or try i do q dot append and then current dot right and then p plus one in the end what we are going to do is we are going to simply return that so avoid if the queue is empty then it will just return it here but we are going to return it here okay so let's go in and submit this code if i click on the submit button okay let's see how we did yeah it got accepted it is uh faster than 33 of the users so actually this is not correct okay so uh yeah uh so i hope you like this video if you like this video give it a thumbs up and click on the subscribe button uh you know if you want to see any more videos from me and also if you want me to do some problems please let me know in the comments below and i will work on them and get those videos up uh yeah happy coding have a good day
|
Minimum Depth of Binary Tree
|
minimum-depth-of-binary-tree
|
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102,104
|
5 |
hello guys welcome to study algorithms and today's problem is finding the longest palindromic substring first I'm gonna describe the problem statement and show you some sample test cases next we will understand how to go about solving the problem and what issues you may find while working through it then I will compare the code side by side and do a dry run to show you how it exactly works so let's dive into the problem as you know a palindrome is a string which reads the same backwards or forwards so let us make up three strings if we gonna read each of these drinks first forward and then backward now reading in backward going on to the next string no reading in backward and for the last and the final string taking it backwards so what one may observe is that the first string racecar is the same if you read it forwards or if you read it backwards so we would call this string a palindrome but with the second string study if you read it forwards it reads ready but backward it reads something gibberish like ydu TS so this string is not a palindrome and for the third string madam if you read it from the front or from the back it still remains the same so what we would say is that these two strings racecar and madam are a palindrome so given a string you are required to find out the longest palindromic substring the important thing to know here is that there could be multiple palindromic substring available we need to just return a single substring which has the longest length so let us take up an example let us say we have this drink if you just glance at it we can see that this ring has multiple palindromes one of the palindrome being da-ad or you of the palindrome being da-ad or you of the palindrome being da-ad or you could see one more palindrome as BRB or you could even see another bigger palindrome that is a B RBA but indeed if you look closely still a very big palindrome that is B ad a adab so these palindromes all have different lengths so the biggest final room has a length of eight this palindrome has a length of five this palindrome have a length of 3 and this palindrome has a length of four so for this problem of statement you need to output the string and this would be a correct answer as soon as you look at the problem one solution seems very obvious just find all the palindromes that exist in the string I trade through all of them and find the length of the longest one this method for sure works but we end up spending too much time on shorter palindromes and validating them for example let us go back to a previous case as you can see this example has a lot of smaller palindromes we have BRB we have a we have da-ad and then we have a we have da-ad and then we have a we have da-ad and then we have even the single letters are palindrome in itself so we have a over here then a again over here so one can imagine that the problem might get of might get out of hand pretty quickly so let us try to think of an efficient way to solve this problem so the basic idea of following this problem is you pick up any character from the string and go in the both left and right direction so let us say you pick up the letter R now this letter R is a palindrome in itself so what you do is you navigate to the right of it and you navigate to the left of it so the new string that you get is B R B and this has a length of 3 now this string is a palindrome in itself since it is still a palindrome what you do is you again navigate to the left and right of the strings the new string that you get is a B R b/a now this string has a get is a B R b/a now this string has a get is a B R b/a now this string has a length of 5 so you're getting an even begin palindrome you stop as soon as you hit the end of the string or the string is no longer a palindrome if let us say we have a case like D so what do you do is D is in itself a palindrome ok so you go left and right then I get a new string that is a be a now this is still a palindrome so you again go left and right next you get be a D a and a now this string is not a palindrome so the longest length of the panelled room that you got was 3 but in this case here the longest length that you got was 5 hence the basic idea of this problem is VI trait to the entire string go character by character and find the longest palindromes that we can find keep just keep a record of this longest length and in the end you can return this length so let us see how this code works in action so let us understand the problem with an example we are given the string so what will you be doing is we would be hydrating through this string from one till the length and keeping a track of the longest palindrome we can find the variable LPS would be storing a result and it would give the longest palindromic substring once this for loop ends the way the start is we keep two pointers low and high now these pointers are used to keep a track of the left and the right most positions so we start at position 1 now this word is a palindrome in itself that condition so we go to the left and we go to the right now this condition fails so the value of low and high still remains one we can use these values to determine the palindrome that we find and then we would be updating the value of the variable LPS to be equal to B but we are not done here they could also be a palindrome of even length so in that case what we do is we keep the value of low as zero and we keep the value of high as one and hence we are considering this palindromic substring but this is not valid so we would do nothing and we would go on to the next iteration of I and that would be I equal to two so when I equals to two we again refit the values of low and high and then low becomes equal to two and high again becomes equal to two the parent Romek substring we again get is B we don't find a valid palindrome in the left and right and hence not there's nothing we can do about it now let us look at an even length palindrome when we are looking and the email and palindrome the value of flow is 1 and the value of high equals to 2 string we are looking at is B now this is a valid palindrome and hence we would be updating our longest palindromic substring that we found to be B we stopped here because when we tried to lower the value of low and we try to expand the value of high we get low as zero and high as 3 which is EB ba and this is not a valid substring so we didn't do anything about it moving on to the next iteration the value of I changes to 3 this is where things get interesting a is a valid substring we lower the value of slow and expand the value of high so we look in the left and right direction we get a new string that is B a B now this substring have a length of 3 hence we would be updating our longest palindromic substring to be a B and then if you try to navigate further left and if you try to navigate further right you will be looking at a substring BB ABA now this substring is not a valid palindrome and hence you stop similarly if you try to consider the even length now lo equals to 3 minus 1 that would be 2 + hi equals to 3 so the substring 2 + hi equals to 3 so the substring 2 + hi equals to 3 so the substring you're looking at is BA now this is not solid so we won't be doing anything about it once this loop completes you can see that we would have the longest palindromic substring in this variable in this case the longest palindromic substring is Bab or if you go ahead it would be eventually ABA but that does not matter since we are just concerned with finding one longest palindromic substring and as we saw in our problem statement ABA is also a valid answer I hope this was helpful thank you can find the link to this problem in the video description below and please feel free to reach out to me in case of any doubts
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
284 |
hi guys welcome to algorithms made easy in this video we will see the question peaking iterator given an iterator interface with methods next and has next design and implement a peaking iterator that supports the peak operation it peaks at the element that will be returned by the next call to next that is this next method now let's assume that there is a iterator which is initialized to the beginning of the list so iterator would be initialized to 1 and the list contains three elements the call next will get you one the first element in the list with this next call what it does is internally it will also move to the next element so it will give you one the current element and it would move to 2. now that you call peak it would return you 2 because the next method was pointing the iterator to this 2. now again when you call next it would still return you 2 because it is at current position and with that it will increment the iterator to 0.23 increment the iterator to 0.23 increment the iterator to 0.23 again now when you call next the final time this will return you 3 because the current element is 3 and now the has next would be false because there is no element after this next so we need to implement such a functionality using this code so let's just quickly see all the three operations next we'll return the value at current iterator and then increment the iterator that is it would cache the next value the has next method will tell if there is any element present in the list after this current element and peak will only return the current element and will not increment the iterator so what are we going to do basically in this question here we will be taking the use of the iterator class which is already there and we'll implement this particular iterator so now let's take iterator of type integer and let's set it to null first and with this will also need a next element that would give us the next so this would actually give you the element that is present at the next iterator that is currently present at that iterator in here we will do iterator equal to iterator so if there is next element present we will do next val equal to iterator dot next so now peak would just return the value that is present in your next val so we'll just return next val so in the next method we first take the value at current iterator in a temporary variable because we are going to return that in the next call with this will also shift our iterator one point ahead so we check if our iterator has a next element my next val would become iterator dot next otherwise my next val would become null in the has next method i simply have to return whether my next val is not equal to null or otherwise my iterator has a next val so let's run this for our sample test cases and it runs fine let's submit this code and it got submitted so that's how we can implement an iterator by using the iterator class but we are overriding the next and has next methods so that's it for today guys i hope you liked the video i'll see you in the next one thank you bye happy coding
|
Peeking Iterator
|
peeking-iterator
|
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
**Input**
\[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 2, 2, 3, false\]
**Explanation**
PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\]
peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\].
peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\].
peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\]
peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer?
|
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
|
Array,Design,Iterator
|
Medium
|
173,251,281
|
897 |
hello everyone welcome to day 17th of april eco challenge my name is sanchez i am working a software developer at adobe and today i present day 661 of leetco daily question the question that we have in today is increasing order surgery and to your surprise for all those who have been following along as i told yesterday that we have already solved this question in the past that too on december 3rd 2020 i'm thinking that lead could have started picking up questions from this playlist itself so here is a video do check this out and i genuinely hope you have a great time watching it up this brings me to the end of today's session i'll see you tomorrow with another fresh question but till then goodbye i'm attaching its link in the description below
|
Increasing Order Search Tree
|
prime-palindrome
|
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\]
**Example 2:**
**Input:** root = \[5,1,7\]
**Output:** \[1,null,5,null,7\]
**Constraints:**
* The number of nodes in the given tree will be in the range `[1, 100]`.
* `0 <= Node.val <= 1000`
| null |
Math
|
Medium
|
2202
|
1,680 |
Hello Guys Welcome Back To Take Divorce And This Video Will See The Continuation Of Consecutive Binary Numbers Problem That Soft Code Number 181 Middle Age Problem No Problem Thursday Ko Daba Representation In Law And Order No Veer Versus The Latest Example Subscription is here inch and value Sanjay question is one to end solve 123 not want to decimal value of greatest yadav are the greatest religion in the form of representation of all the amazing to the amazing 20351 represented in increasing order of Dec 10 2009 Subscribe Button Voice Mail Value Day It Will Come On 27th They Also Need To Take Delight And A Plus 7000 subscribe The Channel and subscribe the Channel Problem example2 The Loot The Video then subscribe to the Page if you liked The Video then subscribe to the volume obtain a point plus 7 daily tasks 220 ok similarly if you take an example and value loot problems in simple way to solve this problem subscribe to create fear when will create all possible and will keep aside from left to right the The solution subscribe kumar singh will consume a lot of thanks ok supreme court on saturday celebration you tried to avoid this operation of its possible subscribe ranges from this subscribe for live video 2019 date of birth is industry and converted into a representation to know Which will have to the a non-hindu quantity nation operation late se where required to find non-hindu quantity nation operation late se where required to find non-hindu quantity nation operation late se where required to find for any value question ok want to decimal value welcome to the problem Thursday subscribe 12323 first president of the world will bring to front 11000 they have no representation in the world great De Shruti And Objectives 20110 For The Interview Will Come To You Can See What They Are Doing A Year And A Value Only 1000 Years For The Effective This Subscribe No Veer 2018 40 Verses No Abhi Hi Weightage Rate And Withdraw 1922 000 Distic And Subscribe Number Now Subscribe Screen 100 The Video then subscribe to The Amazing Only Value Which Was Already 6 Will Now Be Replaced By Two Wickets And So Its Effectiveness You Will Now Know 62.2 98100 Effectiveness You Will Now Know 62.2 98100 Effectiveness You Will Now Know 62.2 98100 Interview subscribe The Channel Please subscribe and Give One Range 124 Will Start from this is the value a cog existing string is lineage value tourism in the representation of law of number to solve oneplus number to the number system The Video then subscribe to the Video then subscribe to The Amazing to Two Wedding Sagittarius String Value The Value For This 2108 Effective and Decimal Value Representation This Note's Value Are You Can See The 1069 Number Three liked The Video then subscribe to The One more0 Video subscribe Mumbai to Udaipur to so Will be multiplying 6 total points to which is equal to leaping 6 to bits know this thank you will get it is the value of the total sounds person subscribe 323 324 subscribe channel who is the current number is inside number of units which belongs to The Number Call Log Best Wishes Picture and subscribe to the Page if you liked The Video then subscribe to the world will be into the system Subscribe to Airplane Mode of Time Third Point Plus 7 S Word in the Problem Statement Because and Answer Main Over Flow Rate Suvidha Center Optimal Solution For This Problem Know The Time Complexity Of What They Are Doing Work Number From One To The Middoing Left Operation Time Simple Problem Thursday Running From 2nd Id Subscribe To Hello Viewers Loop Shifting It Is The Number Of Units What is the number of units will be equal to one plus log best two of the chronicles were and half subscribe this Video plz subscribe in intermediate subscribe number subscribe The Channel Please subscribe and subscribe the mode off do intermediate episode no intermediate Step Will Overflow 999 Returning Divya Hai Virvar Center Problem Mode Off Simple But They Still Have Any Problems And Comment It's Possible Like Share And Subscribe Do n't Forget To Subscribe Our Channel Thank You
|
Concatenation of Consecutive Binary Numbers
|
count-all-possible-routes
|
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: ** "1 " in binary corresponds to the decimal value 1.
**Example 2:**
**Input:** n = 3
**Output:** 27
**Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ".
After concatenating them, we have "11011 ", which corresponds to the decimal value 27.
**Example 3:**
**Input:** n = 12
**Output:** 505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100 ".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
**Constraints:**
* `1 <= n <= 105`
|
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
|
Array,Dynamic Programming,Memoization
|
Hard
| null |
1,441 |
friend so today we can discuss this problem from weekly contest we put 188 problem number 104 gone we didn't array with type operation so the problem statement is very simple so you are given a target array and an integer n in each iteration you will read a number from 1 2 3 2 till N and you have to build the target array under the following condition so for like push means read a new element from the draining of the list pop mean delete the last element of the array if the target array is already built stop reading my elements this is important if the target element like arrays quality-built arrays quality-built arrays quality-built stop eating more elements so you are guaranteed that the target array still increasing okay this is also important in the operations to build a targeted so the thing is you have a list let's say you have a list um for the for example 1 2 3 because it is from the letters from 1 till n and here n is equal to 3 and then the target is one entry the target area is balanced so what will the output so just assume like you have a stack and you want this in our final stack value and you have this strip of numbers coming so if one comes you will push one into the stack suppose the first do push operation now 2 will come but because 2 will come you will first do push but in the target you do not want to so what will you do you will pop this out and you will do a population and then 3 will come you will do a push operation of 3 because and you will not remove it from the stack and that's it so the answer is push ok so the thing is what you can do is you can maintain one for inter at the beginning of this stream and one pointer at the painting of this stream if ing are sealed which means like the number which is coming from the stream is also there in the target area what you do is you just push but if then you'll move to this because 2 is not in the target which means we first push it and then pop it out so first push and pop it out and then you will add this because both are same so just push ok well the case also here will be if the target is only 1 2 and the stream is still food what you need to do is just push and push don't do again push pop whoosh pop because you don't require all the four numbers you can stop after this point so what you can actually do is if we go out impound of this target heading you can just stop reading our input ok so now I see I can write the code and it will be more helpful to you so make a get tougher string to store to answer and then maintain one pointer okay J is the pointer which is at here then we'll do a for loop which is input stream it will be from I equal to 1 I equal to n and what will we do we will first check if IJ is out of bound which is targeted sides we will what will do we will just break out of this stream else what will be do this if the target value is equal to I which means because the stream of input is I and our target value is this target array if this is same what will be do answer door push back push and we'll think revenge a because we have matched inj now because both of the numbers are matched we have to increase herself but if ing are not matched we will only agrees I know J because I will move through a stream and if the number is not there such that if I now move to 2 and J is 3 so they are not same it means to is first and then popped out then I add again moved to 3 it means yeah I should be there in the like the airing okay else what will we do this answer Todd push back we will do first push let me look and then after that we'll just return this answer this foot first as you can see it's accepted
|
Build an Array With Stack Operations
|
minimum-flips-to-make-a-or-b-equal-to-c
|
You are given an integer array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
You also have a stream of the integers in the range `[1, n]`.
Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to `target`. You should follow the following rules:
* If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
* If the stack is not empty, pop the integer at the top of the stack.
* If, at any moment, the elements in the stack (from the bottom to the top) are equal to `target`, do not read new integers from the stream and do not do more operations on the stack.
Return _the stack operations needed to build_ `target` following the mentioned rules. If there are multiple valid answers, return **any of them**.
**Example 1:**
**Input:** target = \[1,3\], n = 3
**Output:** \[ "Push ", "Push ", "Pop ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Pop the integer on the top of the stack. s = \[1\].
Read 3 from the stream and push it to the stack. s = \[1,3\].
**Example 2:**
**Input:** target = \[1,2,3\], n = 3
**Output:** \[ "Push ", "Push ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Read 3 from the stream and push it to the stack. s = \[1,2,3\].
**Example 3:**
**Input:** target = \[1,2\], n = 4
**Output:** \[ "Push ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
The answers that read integer 3 from the stream are not accepted.
**Constraints:**
* `1 <= target.length <= 100`
* `1 <= n <= 100`
* `1 <= target[i] <= n`
* `target` is strictly increasing.
|
Check the bits one by one whether they need to be flipped.
|
Bit Manipulation
|
Medium
|
2323
|
1,689 |
hello everyone welcome to coding decoded my name is santiago deja i am working as technical architect sd4 at adobe and sincere apologies i couldn't post the solution of today's lead good problem in the morning as it was a working day for me i just came back from office and i thought of completing this exercise because i know somewhere someone of the subscriber is waiting for this video solution i don't want to break his or her consistency and here i present partitioning into minimum number of deci binary numbers lead code 1689 it's a medium level question on lead code however i feel it's an easy question why i am saying this let's try to understand it first we are given a string that represents a positive decimal number we need to return the minimum number of positive deci binary numbers needed so that they sum up to n and how do you define a dc binary number it will only contain 0 or 1 without any leading zeroes for example 1 0 1 double 0 are deci binary numbers while 1 2 3 0 1 are not so here they have provided us with an example 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 partitioning into number of tessie binary numbers lead code 1689 in case if any doubt understanding this question or if you want to ask anything from me in general what is the way out we have coding decoded telegram group or discord server both the links are stated below and i'll be more than happy to answer all your queries up so let's get started with understanding the question again uh what we need to return the minimum number of positive deci binary numbers so that they sum up to n and how do we define a decimal number it contains zero or one without any leading zeros so uh here i have written down few more examples of desi binary number one zero one and kindly note that this is not a deci binary number because it has a leading zero in it now if i ask you guys what is a one digit largest deci binary number that can be generated it is simply one what is a two digit largest deci binary number that exists it's double one what is three digit largest deci binary number that exists it's triple one and if you have understood this much then you have understood the entire algorithm why i am saying this let's hop on to an example let's consider the case where the value of n that is given in the question happens to be 149 what is the length of n is 3 so the largest three digit deci binary number that exists is triple 1 so the first number that we will be using so as to sum those together up in order to generate 149 would be triple 1 and what is the remaining value 149 minus triple 1 gives you 38 so now we need to account for only 38 and the first number that we identified is triple 1 let's proceed ahead what is the length of 38 is 2 the largest two digit decibinary number happens to be 11. so the second number that would be we will be considering in order to arrive at the sum of 149 is 11. what is the remaining value it is 27 so let's proceed ahead again the length happens to be 2 we will again be using 11 and the remaining value turns out to be 16. let's proceed ahead next again we will be using 11 and the remaining value that turns out to be is 5. so the length of 5 happens to be 1 and the largest 1 digit deci binary number is 1 what is the remaining value is 4 let's proceed ahead next again we'll be using 1 the remaining value turns out to be three again we will using one the remaining value turns out to be two again we will be using one the remaining value turns out to be one and finally the last number that we will be considering is one again the remainder gets the meaning value gets updated to zero that means we have successfully reached a total sum of 149 and how many numbers were needed in this process 1 2 3 4 5 6 7 8 9 and if you carefully analyze the sub this is equal to the largest digit that exists in your input number therefore the problem reduces to iterating over the input nums and identifying the largest digit that exists in that input here in this case it turns out to be 9 and we can say that 9 times 1 would be needed in order to reach a total of 9 and this is the crux of the problem the coding part is really simple and let's walk through it in order to conclude the question now so what i have done here i have considered an answer variable and i iterate over the num string i extract each character one by one and i compare it with the previously value stored the previous value stored in ans and once the iteration is done i simply return the ins variable so let's try this off accepted is 63 percent faster it's pretty good time complexity of this approach happens to be equal to the length of string s and the space complexity is constant time with this let's wrap up today's session and don't forget to check out coding decoded sd revision sheet what i'm talking about let me just tell you again so i have created coding decoded sd preparation sheet which covers most of the important topics that are asked in interviews which most of the students find difficult for example dynamic programming graph tries binary search backtracking bit manipulation monotonic stacks two pointer sliding window heaps maps and priority queues so if you go and check out these playlists then you will see that the first one happens to be the template which states the algorithm behind all the backtracking questions so i would urge you guys to go through this template first and then apply this over rest of the questions in the increasing order of complexity starting from easy medium to hard and i promise once you will go through it the backtracking concept would be on your tips similarly for the rest of the playlist as well so over to you guys the hard work is all yours if i can create a video for all of you after my office hours then you can also get motivated from it a little effort is needed and i promise once you will start putting that effort you will get the results that you have never thought of in your life with this let's wrap up today's session i hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates on coding devoted i'll see you tomorrow with another fresh question but till then goodbye
|
Partitioning Into Minimum Number Of Deci-Binary Numbers
|
detect-pattern-of-length-m-repeated-k-or-more-times
|
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not.
Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._
**Example 1:**
**Input:** n = "32 "
**Output:** 3
**Explanation:** 10 + 11 + 11 = 32
**Example 2:**
**Input:** n = "82734 "
**Output:** 8
**Example 3:**
**Input:** n = "27346209830709182346 "
**Output:** 9
**Constraints:**
* `1 <= n.length <= 105`
* `n` consists of only digits.
* `n` does not contain any leading zeros and represents a positive integer.
|
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
|
Array,Enumeration
|
Easy
|
1764
|
456 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem one three two pattern we're given an array of n integers and we want to find a one three two pattern such that there are three integers and they appear in the order i j k so j appears after i in the array and k appears after j in the array but the order of the values actually is going to be a bit different even though k appears third in the order the value of k is actually going to be strictly in between i and in between j so that's why it's called the 1 3 2 pattern because the second value that appears is actually going to be larger than both the left value and the right value so taking a look at an example how could we possibly solve this problem well we know that we have to have at least three integers first of all we can look at the first value we can look at the second value and since we've looked at least two values now we can start looking for our target value which is going to be the k because we know k is going to be the third value that appears after i and j and what we want from k is to find a value that is less than a previous value that's our j value we want k to be less than the j value but we also want k to be greater than the i value and we also want the j value to be greater than the i value now that's pretty complicated even doing this in a brute force way would not be simple we would say that okay this is possibly our k so now we want to start looking backwards to find a value that is greater than this value four we would look at one that's not greater we would look at three that's not greater so we didn't find any value we did not find our j candidate so now we continue we will now go to the fourth value we're going to consider that this is our k value let's start looking backwards for our j candidate let's look at the previous value first this is a 4. that is greater than 2. so we found our j candidate now we want to find a value that is now we need to find a value that is less than 4 but is also less than k and if the value is less than k then we know for sure it's going to be less than j so now we need to find a value that's less than 2. we look at the previous value it's 1 and that is less than 2 so that pretty much means that we found our i we found all three values that we needed so in the worst case this kind of pseudo brute force solution that i showed every time we get to a value we'd potentially have to look through every previous value that came before but there's a way to optimize this problem using a stack data structure let me explain it to you because it's definitely counter intuitive at least for me remember how when we get to a k value we want to then look backwards in reverse order to see if there's any values greater than this value for us to do that efficiently it would be nice if our stack was always in decreasing order also called monotonically decreasing order or mono decreasing order for short and this is actually a somewhat common stack technique so it's not like i'm just making this up but if you've never done it before i would not expect you to be able to come up with this by yourself even if you know what this is it's not super easy to apply it to this problem i think this problem is deceptively difficult the best way to show you how this is going to work is with an example so we're going to iterate through the array first we're going to look at three we would want to check normally are there any values greater than three before but we know there's nothing before it because our stack is empty so we're gonna go ahead and add three to the stack we're gonna look at the next value one and in this case we're also going to ask are there greater values before there's a three which is good but there's only one value we need there to be at least two values that came before because this is our k candidate so in this case it's not going to work either but let's just continue to go through this example we're going gonna get one and then we're gonna get to four but did you notice that for this one it was easy for us to know that there were greater values that came before it because our stack is in decreasing order when we get to the one every value on the stack before it was greater than it but now when we get to the 4 all the values before it on the stack are smaller than 4 so they're practically useless for the purpose of 4. so what we're going to do is pop them so we look at 1 at the top of our stack is less than four we pop it three the top of our stack is less than four we pop it but now we are going to go ahead and add four to the stack by the way for four we found that even though now there are at least two elements that came before it none of them were greater than 4 so 4 is definitely not our k value now we get to the last value 2 we want to check the top of our stack is the top of our stack greater than 2 yes it is it's 4. but there's only one value now on our stack what good was it for us to have removed the other values because now how do we know if we have a solution or not well there's one thing that i haven't mentioned yet and it's that on our stack with every single value we're also going to be maintaining what was the minimum value that came before that n value because notice how we're trying to get this inequality right as we go through uh position by position we are searching for a k value right the top of our stack is potentially a j value that's why we want to maximize the top of our stack it could be the j value but what about the i value well we want to minimize the i value the easiest way to do that is for every time we add a max value to our stack we also take what was the minimum value in the entire array that came before that value this is really easy to get for us because we can actually maintain the minimum in a single variable and you know as we added three didn't really have a minimum value or we could say that the minimum value before that was 3 itself for 1 the minimum value before 1 was also 3 for 4 the minimum value before 4 was 1. so even though yes we did remove some values from our stack we didn't lose any important information because what we really want to keep on the stack are the maximum values it's okay if we removed some smaller values because we are still keeping track of the minimum and it's okay that we removed smaller values also because every time we get to a new value in our array to give us the most number of options for the k value we always want the top of our stack to be the maximum that'll give us the most flexibility when it comes to finding a k value and so by the time we reach the end of the array if we find a solution we can return true if we don't we can return false in the worst case we'll end up adding every single value to the stack at most once and then popping it from the stack at most once so that'll be you know two times n operations that's going to reduce to big o of n that's the overall time complexity that's also going to be the overall memory complexity because of our stack so now let's code it up okay so now let's code it up like i said we're going to have a stack data structure this is actually going to contain a pair of values if you don't want to have a pair of values on this you can just have two different stacks which will probably be the exact same size one will contain the number and one will contain whatever the minimum value to the left of that value is and by the way this is going to be monotonically uh decreasing it's a little bit counter-intuitive but it's a little bit counter-intuitive but it's a little bit counter-intuitive but if we have the stack in decreasing order that will make it easier for us to find the maximum isn't necessarily always going to be on the top of the stack actually we might have to pop some values to get to the maximum so let's uh continue coding it up by the way we're also going to be maintaining the current minimum value initially we're just going to say that's going to be the first value in the array but you could also set it to like float of negative infinity or something like that we're going to iterate through every value in the array but we can actually skip the first value and we're skipping the first value because that can't possibly be the k value anyway it can't be the j value either it can only be the i value which uh is going to be on the minimum of our stack anyway because it's already we're already putting that first value in current minimum so if it's going to be relevant it'll be relevant through that but the first thing we want to do when we look at n is check if there are any smaller values than it on our stack then we are going to pop them so while our stack is not empty and n is greater than or equal to any values on the top of our stack we're going to pop them you're going to see why i'm doing greater than or equal in just a second because after we've done this after we've popped every value that's greater than or equal to it then there are two possibilities either our stack is empty or our stack is non-empty and in that or our stack is non-empty and in that or our stack is non-empty and in that case then we can check if n is actually smaller than the top of our stack with this we're basically checking that there is a value that came before n that's greater than it and we also then want to check and is n greater than the minimum value that came before this value what is the minimum value that came before this value well conveniently we stored it here in the second index so i'm just going to copy paste this and instead of putting 0 here i'm going to put 1 here so if this is the case that means we did find our 1 3 2 pair or 1 3 2 pattern and then we can go ahead and return true now one thing you might notice though is since we did this while loop while n is greater than or equal to that continue popping then in our if conditional why do we even have to check if n is smaller than the top of our stack we know by definition either the stack is empty now and if it's not empty then for sure this is going to be smaller than the top of our stack or else our while loop up here would not have even executed so actually you can get rid of this if you want to but if we did not just find our solution well then we're going to go ahead and append to the stack this uh first of all a pair n is going to be the first value and then the current minimum the minimum value before n is also going to go we know that we're maintaining our decreasing order in the stack because we popped all elements that were greater than it or equal to it and we also don't want to forget to actually update the current minimum after so we're going to take the minimum of itself and the current value n that we're looking at right now so after that if we never find the solution we're going to want to return false outside of our loop now let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient sometimes it's inconsistent on leak code but who cares 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 where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
22 |
hey everyone welcome back and let's write some more neat code today so today let's solve generate parentheses so we are given a pair a certain number and pairs of parentheses and we want to write a function to generate combinations of all well-formed well-formed well-formed parentheses and so you can see that these are the examples and by well-formed they basically mean and by well-formed they basically mean and by well-formed they basically mean like when you're writing code you know you're nesting parentheses you want uh them to be nested in a valid way right like we can't have a right parentheses come before a left parenthesis right like this could not be possible we would have to do it like this right so you can see for each matching for each left parenthesis we have a matching right parenthesis that comes at some point after it right so like in the first example the first three are left parentheses then the next three are right parentheses and when they say n equals three that means we have three pairs of parentheses so in total we have six parentheses because a pair is two parentheses and three are going to be open parentheses and 3 are going to be closed parentheses right so this is a open parenthesis this is a closed parenthesis you can see that when n equals 1 there's only one possible way to make them valid because this is one way and the other way would be this and we know that this is invalid so how can we solve this problem let's just try out the backtracking solution kind of right like a sort of brute force approach how would we even do a brute force approach let's say n equals three so then we have three parentheses what does that tell us about valid parentheses right like this is one valid parenthesis that satisfies this condition right we have three open parentheses three closing parentheses well the first thing it tells us is that we need three open parentheses and three closing parentheses right that much is pretty obvious right like you could probably figure that out by yourself if we have three pairs then we definitely need three open and three closing parentheses so in total six parentheses but what about the order of parentheses so let's say i have so far i'm empty right we're empty can i start out with an open parenthesis yes i can right but can i start out with a closing parenthesis no we know that this is invalid no matter what i do now this is always going to mess up our parentheses so we can't start with a closing parenthesis we can only start with an open parenthesis okay but now let's say i have one open parenthesis now what can i do can i have another open parenthesis yup because our limit is three open parenthesis and so far we have two so we're allowed to do that what about a closing parenthesis can i have a closing parenthesis yes because so far our open count is one and the initially the closing count is zero and i can by adding this parentheses i'm just changing the closing count to one now right so now let's look at it now can i add a another open parenthesis yes i can because the limit is three open parenthesis and so far we only have one so i'm allowed to add a open parenthesis what about a closing parenthesis can i add a closing parenthesis right now no because you see that so far we have one pair right this pair of open and closing parentheses and then when you get rid of that pair then we're just left with a single closed parenthesis this closing parenthesis will never have a matching open parenthesis on the left of it so we can't add this parentheses and how would you figure that out from code well just take a look at the count we have so far before we add the parentheses we have a count of one for closed we have a count of one for open basically what this tells us is that we can only add a closing parenthesis if the count of closing parentheses is less than the open count we can only if this is true are we allowed to add a closing parenthesis so if for example if i were to add another opening parenthesis now we update our open count to two so now we have two open parenthesis right so two is open one is closed from over here right so now i'm allowed to add a closing parenthesis right so basically let's say if we're gonna do backtracking these are the two rules that we have to follow this is basically our base case once we have three open and three closing parentheses then we have a valid uh parenthesis formation right and this condition tells us when we're allowed to add closing parentheses we can add as many open parenthesis as we want as long as it's under the limit which is n right we can add up to three open parentheses but we can only add a closing parenthesis if the number of closing so far is less than the number of open parentheses so with that said let's start our backtracking solution so we so far we're empty right so the first thing we're going to do is add a open parenthesis so now this is what we are so far a single open parenthesis since we added a open parenthesis that means the count of open is greater than the count of close so now we have two choices we can add a open parenthesis or we can add a closing parenthesis so we have potentially two open parentheses or a single open and a single close okay let's take a look at this decision here we have open is greater than or equal to close right and the number of open is still less than three so we can do both choices so from here we can add another opening parenthesis so we have potentially three and we can add a closing parenthesis so two open and one close from here we see that the open and closed count is actually equal right we have one of each so here we don't have any choices we have to add a open parenthesis so what we're going to do is have just another open parenthesis come after okay so i'm running out of room but let's continue so over here now we have three opening parentheses right so we've reached our limit which is n so we can only make one choice and that's to add a closing parenthesis so we're now we're going to have three open and a single closing parenthesis here you can see that we have two open parentheses and one closed parenthesis so we can actually add we have two choices we can add an open and we can add a close so if we add an open we'll end up with two open one close and then another open or we'll end up with two open parentheses and two closing parentheses over here we also have two choices because we see we have two open parenthesis and one closing parenthesis so we have so if we add a open parenthesis again we'll end up with open close open if we add a closing parenthesis we will end up with open close okay so we're almost done start starting over here we see we have three open parenthesis so we can only add a closing parenthesis now so open close from here we actually only have one choice even though we have more open we have three open and one close which open is more than closed so we should be able to add one of each but we can't because we know that three is the limit so we can't add any more opening parenthesis we can only add a closing one so the new parentheses we add is closing here we also have one choice even though we only have two open and too close we know that the open count is equal to the closing count so we can't add another closing parenthesis because that would make it invalid right so we can only add a opening parenthesis so we'll just add a single open here we all we also only have one choice because we already have three opening parentheses so we can only add a closing parenthesis at this point here we also have one choice we can only add a open parenthesis because if we add a closing parenthesis that would make this invalid because then the close count which would be greater than the open count right which we cannot do and so at this point for each of these five we only need to add a single more parentheses and since this has three open three and two closed we know that we need three of each so the only thing we can do is add another closing parenthesis to it right so this is going to be one possible solution because now we actually have three of each which is what we wanted for this one we have three open and three and two closed so lastly we are going to add another closing parenthesis and you might notice that's what we're going to do for each of these right because each of these now has three open and too close so all we need to do is add another closing parenthesis and for this one we also are just adding a closing parenthesis and lastly this one we're also adding a single closing parentheses so now you if you look at all five of these you see that they're all valid right and you see they have three of each and they come in a valid ordering so these five are going to be returned as our result these are the five ways we can make valid parentheses so now let's finally write the code this is basically what we're gonna do you can see i summarized it so we're only gonna add an open parenthesis if open count is less than our input n we're only going to add a closing parenthesis if the closed count is less than open and we're only going to stop adding parentheses altogether once our open count equals our closed count which is going to equal n so i'm going to do this recursively because that's basically the best way to do it and i'm going to create a stack which is going to hold our parentheses and i'm going to create a variable result which is going to have our list of valid parentheses combinations and i'm going to do this recursively so i'm going to put a function backtrack inside of another function so if we have this then we don't need to pass in these two variables into our function because this is nested inside of here we also don't need to pass n in into this function either but we are going to have to pass in our open and closed count so i'll call it open n and closed n so we know the base case is if open n is equal to closed n which is equal to n so in that case we have finished and basically our stack will contain the proper parentheses so what i'm going to do is basically some python stuff but you could probably handle this with a string if you wanted you don't actually need to use a stack but i just like doing it so what i'm going to do is take every character in the stack and join them together into a empty string so once they have been joined together they will form a complete string and what i'm going to do is append that to our result list and once i've done that i can just return right because this is our base case remember if we want to add a open parenthesis we have to check that our open count is less than n if that's true what we can do is to our stack we can append a open parenthesis so just an open parenthesis and then we can recursively continue our backtrack and but if we do that we have to increment our open count by one and the closed count remains the same and after that backtracking returns though we do have to update our stack because we only have a single stack variable remember we're not passing this stack into every single call this stack is basically a global variable so every time we're done with backtracking we're going to pop the character that we just added to the stack and if we want to add a closing parenthesis we have to make sure that the closed count is less than the open count so then we can take our stack and append a closing parenthesis and then we can call our backtrack function our recursive backtrack except we'll leave open count the same this time and we'll actually increment the closed count and as before we're also gonna need to clean up so we're gonna have to update our stack by popping the character that we just added and this is actually the entire function so you can see we broke it up into three conditions which i commented up here and i explained in the visual explanation so the only thing we have to do now is call our backtrack function pass in zero for the initial open and closed count because our stack is initially empty and then we can return what our result will contain which will be the list of valid parentheses so as you can see this solution works and it is pretty efficient so i hope that this was helpful and if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Generate Parentheses
|
generate-parentheses
|
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_.
**Example 1:**
**Input:** n = 3
**Output:** \["((()))","(()())","(())()","()(())","()()()"\]
**Example 2:**
**Input:** n = 1
**Output:** \["()"\]
**Constraints:**
* `1 <= n <= 8`
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
17,20,2221
|
1,057 |
hey guys how's everything going today let's take a look at number 105 seven campus bikes there is a campus represented as 2d grid there's n workers and bikes each work and bike is a 2d coordinates on this grid okay our goal used to sign a bike to each worker a month so the bikes are more than the worker so every worker should be get one back I'm on the other among the available bikes and workers we choose the pair with the shortest and I hadn't distance between each other and assign the bike to that worker okay because spikes are more than the worker there might be different bikes as for each bike the color this worker might be a saying so for that case there are two cases right okay so for the first one bike might be the same distance closest to other workers for that case we chose the smallest working decks and for the four different bikes closest to the same worker which shows it's the smallest biking decks mm-hmm we it's the smallest biking decks mm-hmm we it's the smallest biking decks mm-hmm we repeat this process until there are no available workers mahan distance is the two points which some zoomed up some up the four point two for two points the mahant distance is the sum for their horizontal distance and the vertical distance we need to return the vector and for each index it means the corresponding a bike to that index worker to the work of that index right so example for this of course we need to assign bikes 0 to 1 and 1 to 0 so we need to return a 1 0 which means the first worker get the one's bike and the second the worker get the 0th bike for this case we see that 4-bike zero for this case we see that 4-bike zero for this case we see that 4-bike zero worker zero they are closest so zero and therefore the second worker the closest would be zero a to the zero is already assigned so this one to the rest is one so worker one well the first characters characteristic of these problem is that the how can I interpret this the combination is fine the fin it finite right there are only certain kind of assign assignment there is no infinite combinations so for each worker there is infinite possibilities for assigning each back to it like for worker 0 we could assign back 0 assigned by two assigned bike one for one the same so actually there are end to the square scrub and this amount of possibilities assignment right and for each silent there is a distance lawn or short right so this reminds us of a naive solution which is for each combination we there is I J which means the index of worker and bike and distance all right so our goal is to assign the shortest one the closest one right so we can sort this combinations this would be O and we can sort it first by distance all right for case of this the distance will be of course one for one the combinations will be this like five possibilities and then the distance will be so this or yeah this one or this one and this instead of three this one and for this one right after we saw that if we just take just of course we need to we sorted I sorted it later after distance we sorted by the work index if pike is same right if J is the same yeah because we want to you see for each foot for the same bike we need to choose the smallest smaller worker right and for worker when you choose the smaller bike and then in spiked index okay as a worker so after so dienes we can just click the result Wow for the case here it would be for the distance of half of 1 so 1 right 1 0 1 and or 0 1 we sort the worker first I know we saw you the first worker first so work worker 0 1 and then there will be 0 1 and then we chose the 1 choose one and then for distance one they're on their left only worker to right is a 2 0 1 & 2 1 and then it right is a 2 0 1 & 2 1 and then it right is a 2 0 1 & 2 1 and then it becomes the then follows the distance of two possibilities I ignore it so now you see now we can see that we can just pick the result from top to bottom so 4 0 there is only one pike and one worker at each point so we can pick them this is a final result and because 0 is used this is gonna be skipped so the next one would be 1 2 right so 1 2 and then 2 1 2 is used and after we is 2 0 is used so and 2 is already used so left with the 2 3 or 2 1 cool so our solution becomes clear now the first week we get all these combinations why this could be done and so the step one get all combinations push I J and distance I will get create another function for this yeah this is the distance and then we sort them first is distance okay I'll say the distance and then worker and then bike so combinations sort a B if a2 equals it'd be too if not we will turn a 2 minus B 2 and then if a 0 equals B 0 return a 1 minus B 1 in the other case when we turn a 0 minus B 0 okay now we need to like the result okay the final result will be array and then for let's combinations for each combination cost working decks and pike index and distance this addition is used to stood the sword so it's no longer needed s would be combination and for the K selected like this we need to track they keep track of that each worker is used or not right we could say comes to use the worker caste used bike new set okay so if each worker and bike is not used if use worker has work curl index used spike has bike index if they're not used we say we set the result index equal spike and of course we need to update it update the hashmap the set the word cure index so what will be ending condition we will look through all the combinations but there are more bikes right but okay this first to traverse through all the combinations and then finally we return the result let's run the code submit cool works accepted but only 40% after cool works accepted but only 40% after cool works accepted but only 40% after rank the top what is it top 70 60 it's not that fast maybe because for four there are more bikes and of workers this four loop could be improved let's try to break it and how well of course we need to break when if use the worker size is equal to workers the size then brake would this be better I don't think that's yeah it's actually not that doesn't improve that much ok let's try to analyze the time and the space complexity also here it should be o and M right time and a space those four time space for the sort wow we're using a sort method so it's generally o m and times log m and M right space none and for the last one is the use of two sets this will be o n+ o m and what this is for loop oh I am so in total this method actually have time in Lock em and AM space o and O and M qui do better the most time-consuming do better the most time-consuming do better the most time-consuming process is a sorting thing right yeah use a sorting we see that we use this we cost this much to stew the sorting while we use an extra for loop to construct the array or what and the plus all the nymph of the combination the size of combinations are finite so you see we are given an input bigger than 0 but smoother than 1000 this reminds us that for each distance actually there might be we cube there might be another solution which is not basically on sorting we actually can do some how to say to some use some hash map is to do the direct access like we did here for the results we use an empty array but we just asked set the index and finally we return it right and it is it we set the index it's already sorted and it's finite so we actually could creates a or the array for each distance and finally we can reduce this kind of sort right okay I'll try to do that so actually these kind of this is kind of duplicated within this sort we could do better yeah sure so the combinations is now the array it is good and but here rather than what rather than push the adamant with both index and the Inc distance we use the distance as the index just to use the competition as a hashmap okay so the distance would be get the index and if the combinations distance is undefined we initialize it with empty array and then we push the IJ unit right we the RJ in it yeah cool now we if you push IJ in it we know he said there's a there is a thing that I J are all in ascending order already right so we don't need to do the sword anymore the IG is already sort it this sword actually is caused by the distance not sort ascending and we use this hashmap to avoid sword in the distance and everything is done cool we can remove the sword and now we can eat we could collect the result remember notice now combination it might be sparse array which means some of them some of the index have the data value but some of them are empty might be so yeah now we collect the result removed this and analyze that later and this use working spike let's see if it is needed yeah it's still needed and okay net each combination and for let's of combinations this combination might be empty so we need to do the check if not combination well we'll just continue so now the combination is okay actually the its array of the combinations right it's a it's the array of I and J so we travel through the combination for let's I J of combination free for okay if is I okay I'll just use a working decks and bikes in this here so for each index it's already sorted ascending if it's used yeah if it is not used yet we click the result and add it to the user set oh this is the same and finally we use we check if you sighs the way this is could be put here to improve to helped us make you faster to be shorter sorry sir short sir circulated show circulate show to circulate it and maybe and then we retrain results so these might this should work oh it seems not oh cool let's try yeah we are a little faster but it city's improved let's try to analyze the time and space complexity for here time well this is the same so it's M o m and M a space is o M but this combination might be the this depending on this depends on the implementation of sparse array I think for JavaScript the sparse actually doesn't take any that the detailed implementation is complicated for this kind of sparse array I think we could suppose the space is a big om or if not it's worse would be the maximum right so the maximum would be like 10,000 okay the maximum would be like 10,000 okay the maximum would be like 10,000 okay and now for the result is a here this is sure b-plus sure b-plus sure b-plus oh and for space and for this combination here time will be still Oh M oh no for the total for here the total cost call account for this check is the total or time totally would be oh I am but for the for loop here uh-huh loop here uh-huh loop here uh-huh I don't think so because the combination will be out in time I'm defined for the sparse array so the time here actually depends on the input for worst case if there is a worker here and that there is a bike at the top right and that would be it worse for worst would be a tenth like this right I mean Max and Max M OH so if that's the case any workers it's actually the same oh yeah hmm no there are n an M right a coordinate so it should be max coordinates how can I say the coordinates max work curse i0 work by i0 and this times pi max workers i1 bikes i won it means the largest rectangle generated by left to most left most node and the top right yeah that'll how can I interpret this it means the largest area which will be which consists of these workers and bikes coordinates so this will be om right so the time generally would be well if this is Wow this well this is tricky the time complexity here if it is empty but we don't do nothing we do nothing but it's not empty we need to traverse all the this right so actually every corner is actually will be actually be Travis yeah so it will be like the time would be like this and the space would be oal am om oh yeah cool so that's all for this problem we first use a like kind of brute force solution and then we found that for the intermediate data we are generating has some relationships relationship with the sorting and we try to improve that by analyzing that the generating process is already sorted because you see I and J he's already sorted so this kind of sorted could have actually be emitted by using direct hash map so this will be faster but the d'haran hash map has its own have say limitations is that you will generate more generate two more steps than we need it especially for this combination undefined check well either way it's okay I think in a real interview we should break it down like approach it in us in a easiest way and then try to improve another idea I'd say another suggesting is that we should and I will start using I'll start solving the problems in AD fashion from now on and try to do that the idea is we should split the function space the algorithm into smaller functions as much as we can like the get distance here in a real white board test we don't we might there might be not enough time for us so we could just first write the skeleton code like this and say hey I work this method is very easy to implement but I don't want to waste my time into writing the original letters so I'll leave it immediately live it up as empty and then if I have time I will come back to that later and I think the interviewers who are now but we're not complaining about that because it's really simple and everyone could do that so for this function for this algorithm problem getting an instance is one that we could do you later and what we can for anyone and something else we could actually we could apps right move this cash thing away I'll say there is a cash like cost okay I quit here cast cash and I would say if cash hmm as I used if used worker index and the park index every if it is not used well I will add it to this and it used add use the set worker index like index so the used would be I say has I J used I use the worker you set so I can of omit dryness code at the beginning but come back to this later used bikes new set used to has this so it has beings return this used worker has I or this used worker has J set it's the same nice to worker and I use to bike hmm I think this should also work ah no unidentified oops , cool so that's what I learned from , cool so that's what I learned from , cool so that's what I learned from this problem how it helps yeah thanks for watching see you next time bye
|
Campus Bikes
|
numbers-with-repeated-digits
|
On a campus represented on the X-Y plane, there are `n` workers and `m` bikes, with `n <= m`.
You are given an array `workers` of length `n` where `workers[i] = [xi, yi]` is the position of the `ith` worker. You are also given an array `bikes` of length `m` where `bikes[j] = [xj, yj]` is the position of the `jth` bike. All the given positions are **unique**.
Assign a bike to each worker. Among the available bikes and workers, we choose the `(workeri, bikej)` pair with the shortest **Manhattan distance** between each other and assign the bike to that worker.
If there are multiple `(workeri, bikej)` pairs with the same shortest **Manhattan distance**, we choose the pair with **the smallest worker index**. If there are multiple ways to do that, we choose the pair with **the smallest bike index**. Repeat this process until there are no available workers.
Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the index (**0-indexed**) of the bike that the_ `ith` _worker is assigned to_.
The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`.
**Example 1:**
**Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\]
**Output:** \[1,0\]
**Explanation:** Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is \[1, 0\].
**Example 2:**
**Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\]
**Output:** \[0,2,1\]
**Explanation:** Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is \[0,2,1\].
**Constraints:**
* `n == workers.length`
* `m == bikes.length`
* `1 <= n <= m <= 1000`
* `workers[i].length == bikes[j].length == 2`
* `0 <= xi, yi < 1000`
* `0 <= xj, yj < 1000`
* All worker and bike locations are **unique**.
|
How many numbers with no duplicate digits? How many numbers with K digits and no duplicates? How many numbers with same length as N? How many numbers with same prefix as N?
|
Math,Dynamic Programming
|
Hard
| null |
160 |
hi everyone it's Orkin welcome to my channel uh today we are gonna solve lead code 160 intersection of two linked list problem so the problem statement is that we have to linked lists and uh with the head of the link at least being a and the B and we need to return the node at which the to list intersect so um if there is no intersection between these two lists we need to return null as an example we have here to link it list um a and the B so they are intersect at this point so it means that the A2 and the B3 they are pointing to the same node um another important requirement is that we need to retain original structure when we return the in our return value which means that we cannot modify our linked list uh so yeah that's the that's it let's see how we are going to solve this problem okay uh let's take our example that we have seen earlier and let's work on that let's say that we have a link at least and we have B here so at some point they start to point to the same node so they intersect and we need to find that so this is B has one more uh one more note and then we need to actually that's the problem that we exactly gonna solve if let's say that they have exactly the same size let's say that we have only uh these two Link at least they have the exactly the same size we start from the beginning and we move uh them simultaneously until we will get to the point where they are pointing to the same way a note at a equals to know that b so we are returning that the problem is that the B is longer than uh B is longer than a so we need to move the a uh that difference times so what I mean exactly by that so let's say that the S1 linked list a has the size of S1 and the second one B is the size of S2 and the difference between them is 2 minus S1 is in our case is one right in our case it's equals to one let's just call it variable D so it means that we can move the we should move the b d times then after that we are going to start to move them simultaneously until they uh these two linked list meets which means that we find the intersection which means that they are equal at that point so we are returning this node and since we are doing not doing any modification as it is um as to as it was one of the requirements then so we can return it as a result so that's it let's put our this explanation to code okay um so first thing that we are gonna do first thing first let's check uh Corner cases if uh L1 is equals to null or L2 equals to null so in that case which means it means that there is no intersection so we are gonna return in that case we are going to return uh just now right so um then after that what we need to do we need to uh calculate the size of L1 and we need to calculate the size of the L2 and compare them so let's do that first let's say let's list node um so another thing that we need to do we need to create a new node in order to not to lose the pointer to the Head we need to create a new node that points to the head of L1 and to the head of L2 otherwise or we'll lose the head of the L1 and head of the L2 so what we are doing let's call it L1 temp um equals to L1 and another one is um so for the for this one we need what we need to do we need to uh calculate as S1 as we have seen in our explanation part so S1 so while uh while um L1 uh temp so L1 temp is uh is not equal to null then we are just move it and L1 temp equals to L uh sorry L1 temp uh next so which means that we are just moving the to the next node and we are incrementing our S1 so we are incrementing that uh so exactly the same thing we are gonna do with the uh second note so I'm just going to copy paste this code so L2 temp that's also should point to the L2 so otherwise we will lose the uh um pointer to the head of the linked list for a L1 and L2 so for the S2 we need to do exactly the same so while L2 temp is not equal to null lto temp is equals 12 to temp to next so we're just moving our pointer and at the same time we are incrementing S2 in order to calculate the size once we exit this Loop what we need to do we need to see that okay if S1 more than S2 so what it means that the L1 is longer than L2 so in that case what we need to move them exactly the difference whatever is difference between a d and S1 and the S2 so this difference let's initialize that D is equals to S1 minus S2 right so while um while D is not equal to null D is not equal to now so then we are going to move that to that difference part so it means that the L1 we are moving now the actual node so L1 is L1 uh equals to next so let's say that the size of l 1 is 5 and the size of L2 is 3 so the difference is 2 so we need to move the L1 two nodes uh so at that point they will have the same size and we can move them together until we find the intersection okay so and we are decrementing here over the difference okay so exactly the same thing else if not then it means that the L2 is uh sorry S2 is um uh L2 is longer than S1 then we are doing exactly the same but in opposite direction so we say S2 minus S1 so yeah and we say okay while uh D is not equal to zero do the following the same like for about 42 so L2 sorry for L2 next so we are moving the um to the next node for L2 and we are decrementing the D Okay so uh that's it once we exit this Loop they are um so we move the difference uh whichever uh link it list is longer now we have to move them simultaneously until we get to the intersection so what we say while um L1 is not equal to L2 so which means that there is no intersection yet so we say Okay L1 is uh L1 is equals to L2 sorry l1.next sorry l1.next sorry l1.next and the same we can we should do for the L2 equals to L2 dot next okay and that's it so after that at the end so we haven't modified our linked list so we are just returning L1 and that is the in or we can return L2 doesn't matter in our case we're returning L1 so it means that this is the node uh the sorry this is the intersection for these two linked list that's it let's check our code uh yeah actually let's initialize them here because they might not have been initialized it's still same for us to okay great it works as expected let's go over algorithm one more time so first thing that we do is we are calculating the size of uh for each linked list so for the L1 it's the S1 for the L2 is the S2 after calculating the size we compare if the L1 is longer then we find the difference and move the L1 exactly whatever that difference is exactly the same if the S1 if the L1 L2 is longer than exactly we do exactly the same for the L2 and since at this point they are the same size we are moving them simultaneously until L1 is equals to L2 then at that point we just return one of the link at least because it doesn't matter L1 or L2 because they are pointing to the same node uh and yeah that's it that's the solution for this problem I hope you like my content if you like it please hit the like button and subscribe my channel that's it for today see you next time bye
|
Intersection of Two Linked Lists
|
intersection-of-two-linked-lists
|
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
599
|
1,391 |
thousand 391 crimes that are called chekib diverse for him and for you madrid this problem by the contest 181 of lyrical and good and gel and with many times and good is his problem in reality simple laborious state but it is quite simple what it is about is that They are going to give us the flu. It is the typical problem that you start from the 2 crisis on the left side, which is the coordinate 0, and you have to get to the other end of the two-dimensional matrix to take into account certain rules. In this case, the rules are that each matrix each space in the matrix will have a number that will be from 1 to 6 and each of these numbers represents a road towards some direction. Let's see if there is a valid path, for example in this poem but in this one it starts from here and these two are no longer compatible so there is no valid path and you have to return bag keep in mind it is the typical first search I don't know why there is someone who has solved it by brett Fraser I don't understand how the truth is I solved it by the first search and this and well you can activate the first thing we have to do is and said I forgot something this here this is key I didn't copy it directly from my solution because I'm too lazy to do it again but this is an arrangement that It shows us all the directions in which we can continue if you notice from 1 to 6 1 2 3 4 5 6 and this represents the possible movements if we are in a box of this type if you notice here is we can go towards the left or to the right just in the 2 as if we go up or down not that it is about the rose and go down which is more x + rose and go down which is more x + rose and go down which is more x + 1 or up which is minus 1 etcetera like this one don't lose it 3 and don't be the left or go down and not like that then since we have this the truth is that the problem is not complex at all we simply do our job of proceeding ex we are going to start from zero and we pass it the flu is all we have to do and then we do our function we have to return what this returns then we go to the bullying function and what we are going to do is well first we are going to do the function we are going to pass int raw and nxt code in our function and of course the grid that we already have then the error causes is to see if we have already reached where we want to go no then if you are equal grid point link and - one says it is equal to writing the legend point minus one of the other if not so then we have to look towards where can we go for what and to see where we can go we are going to make a new function we are going to put next core or something like that and we are going to the next word well before making this function we are going to get the value that is in the grid For example, if we are at the beginning we are going to return a 212, it means that we start with this one on this road, no, so here we only have, well, we have two possible movements up or down, in this case that place cannot be done because we are in the upper left corner. so nothing we can go down we help down it only makes sense that we find one of these or one of these no so we are going to make that a separate function and we have to mark of course the ones that we already visited if we are not going to be We are returning and that doesn't make sense so we are going to put a -1 on the ones we so we are going to put a -1 on the ones we so we are going to put a -1 on the ones we already visited and the next one we are going to have to do things with not too and the gray one of course so this is going to return us the next coordinate because inside of this we are going to see if it is valid if it is not valid yes etcetera if it is not valid or if there is some error there then we are going to return a null and if it is null we are going to return false projects that since there is no possible path then we have to return fault if we return if it means that if there is an impossible path then we have to see where that path is and to do so we simply return next court 0 next export 1 and the grid that is found the one we put here and nothing more than now we have a new coordinate ok so I have to say that the magic of the problem is going to be in this function in static export we are going to make it to return obviously an array of integers export and pass we are going to receive the two-dimensional 11 and pass we are going to receive the two-dimensional 11 and pass we are going to receive the two-dimensional 11 grip and then here What are we going to do? We are going to take the next two possible ones and all the next two possible movements that we can make will only be one. We have to choose which ones we have to choose the one that makes sense or the one that does not take us towards out of the matrix and towards a box that does not make sense, for example, we are in two and we go to the one that was not 4, so it makes sense because we can go up specified in two and we go to 1, for example that It doesn't make sense so for that this we are going to pull here we are going to take out our matrix it has to be a two-dimensional array that is be a two-dimensional array that is be a two-dimensional array that is called and in fact so it will have to be towards a two-dimensional array two-dimensional array two-dimensional array we do go and not because You are using no because it is not the value of where we come from, what is this, rather, where are we, what is this, so let's see what position we are in, for example, we are in both, if we are at the origin, well, what does it say that we are in this and we have to get the coordinates in fact it would be like this because we are integrating the two-dimensional arrangement that integrating the two-dimensional arrangement that integrating the two-dimensional arrangement that comes here it would be so that's okay so then we are going to get a new roadster that is going to be more made here is equal to zero and then with a time is equal then we already have one of the following possible values no so following possible values no so following possible values no so to see if that value is correct we are going to see that the pp is not less than zero or that it is not equal to what point lentz that's how it is and nothing more or if it is not equal to grid cereté point and eye that it includes if it is greater than one rather it is less than zero notice that we are putting minus one of those that we already visited we need because we do not want with a continuous And let's say that the basic things do not now have to be seen if they are compatible and in reality the only ones that are not compatible are between these two, all the others can be compatible in some way, that is, from two to six, it can come to yes or from a2 to a3 can reach below that is, all the others are compatible in a certain way except sometimes then if num is to do it like this otherwise one is equal to 1 by eye we pass these realizations that we can ensure that if it is a box where there are something, that is, I mean that she is not out of the flu or that we have already visited her before, something like that, everything is going to bring out a multi-mind that, everything is going to bring out a multi-mind that, everything is going to bring out a multi-mind that is going to be the same as this and if it is not expressive for you, sorry, and if not, where from? where we are is equal to 1 and where we are going is equal to 2 or vice versa is that these two are compatible and we have to give it contini if it passes all these validations if it passes all these validations if it passes all these validations then turn you ins we can say return the degree that we are looking for and it will be 77 because this to say that this is the value where we want to go and if we don't find it outright we are going to enter a null and it seems to me that the whole problem is I hope I 'm not missing something is 'm not missing something is 'm not missing something is happening I have a dream the key to this is that do this well if you do this well the rest is trivial it is very easy to implement it here I am wrong about this because it is wrong about this 126 interest I do not understand why I am wrong of course it is wrong it is much more ere and much more because We are adding to it, that is, we are moving from these and what else is wrong 25 an I am not saying that in a clearing it is a -1 because we are in one and it must be one -1 because we are in one and it must be one -1 because we are in one and it must be one it is zero because this rule has zeros then and it works for these birds and it works for everyone and it works for everyone and this is the solution to the problem is taken into account it is very simple the key to everything is that this is right if they make a mistake in this something matters that they will do this well obviously it is not going to work and this seems to me to be the most risky where in fact I copied it from my solution because it is very easy to make mistakes in this part by composing the columns with the rows of the entire problem
|
Check if There is a Valid Path in a Grid
|
counting-elements
|
You are given an `m x n` `grid`. Each cell of `grid` represents a street. The street of `grid[i][j]` can be:
* `1` which means a street connecting the left cell and the right cell.
* `2` which means a street connecting the upper cell and the lower cell.
* `3` which means a street connecting the left cell and the lower cell.
* `4` which means a street connecting the right cell and the lower cell.
* `5` which means a street connecting the left cell and the upper cell.
* `6` which means a street connecting the right cell and the upper cell.
You will initially start at the street of the upper-left cell `(0, 0)`. A valid path in the grid is a path that starts from the upper left cell `(0, 0)` and ends at the bottom-right cell `(m - 1, n - 1)`. **The path should only follow the streets**.
**Notice** that you are **not allowed** to change any street.
Return `true` _if there is a valid path in the grid or_ `false` _otherwise_.
**Example 1:**
**Input:** grid = \[\[2,4,3\],\[6,5,2\]\]
**Output:** true
**Explanation:** As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
**Example 2:**
**Input:** grid = \[\[1,2,1\],\[1,2,1\]\]
**Output:** false
**Explanation:** As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
**Example 3:**
**Input:** grid = \[\[1,1,2\]\]
**Output:** false
**Explanation:** You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 300`
* `1 <= grid[i][j] <= 6`
|
Use hashset to store all elements. Loop again to count all valid elements.
|
Array,Hash Table
|
Easy
| null |
86 |
foreign hi this is Topher from the lonely Dash and today we're going over lead code question number 86 partition list which states given the head of a linked list and a value X partition it such that all nodes less than x come before nodes greater than or equal to X you should preserve the original relative order of the nodes in each of the two partitions so they gave us an example down here where X obviously equals three I put it up there in a nice big letters and you can see that in this order 3 is coming after 4 and what we really want to do is make sure um I'm sorry two it comes after four which is obviously before three so we are going to take all of our numbers that are less than three and put them on the left side of this linked list node or a linked list in their own nodes and all of the numbers that are greater than or equal to 3 on the right side of the linked list now this is important to note we are not putting them in numerical order they are not going to be in ascending order C4 is greater than 3 but it's on the left side and when we're finished 4 is still on the left side of three it's not three then four um and that's the tricky part of this question because otherwise you could just take all of these nodes you could stick them into a nice array you could order that array and then be done with it and put it back into its own linked list so we can't do that when we're trying to preserve the original relative order of the nodes in each of the two partitions so how are we going to solve this question it's a lot easier than you might think so down here is the exact same linked list that we had up there except just written in a more Cody like manner okay one to four to three to two to five to two and of course X is still equal to three so what we're going to do is create two of our own linked lists down here one linked list is going to be holding all of the numbers that are before X or in this case before 3 and the other linked list is going to hold all of the numbers that are it which are X or above or after uh X okay and what we're going to do is create this linked list and then we're going to stick them together so in this case we're going to evaluate 1 is 1 less than x it is so we're going to stick it into our before uh linked list then we're going to go to no we're going to use a pointer for this so we've already figured that one out great now we're going to move our pointer to the next position this is a four okay what are we doing with our four is it equal to or greater than x it sure is so we're going to stick it into that lovely uh linked list now we're moving our pointer to the next position it's a three it is inclusive so we're going to take R3 and we're going to stick it into our after array and we're going to continue this 2 goes into the less than 5 goes into the greater than or equal to and then this 2 goes in our less than okay so now you'll see that we have two linked lists that need to be connected so this one is obviously pointing at this 2 is obviously pointing at this two and this 2 is pointing out into nothingness this 4 is pointing at this 3 is pointing at 5 and this 5 is pointing at well right now it's actually pointing at this 2 because we didn't assign it a position of pointing so it's important that we ensure that this 5 actually points off into nothingness and when I said this 2 is pointing at nothing this that was incorrect well this was correct because this final two points at nothingness here right there's nothing there's null it's the end so now all we'd have to do is take this 2 down here and we need to make it point at this four as this 5 which was pointing at that 2 then needs to point out into nothingness and what that will do is create a together linked list that is one two then that 2 points to the four three and then five and then we're done okay so all we're doing is creating two linked lists the first linked list is all of the numbers or nodes I should say we're going to repoint them at the numbers that are less than three and then we're going to have another linked list that will point to the numbers and nodes that are equal to or greater than three then we're going to connect the two by pointing the final node in our before x to the first node in our after X and then taking the last node and our after X and pointing it out into nothingness so that's how we're going to approach this question let's take a look at the constraints and see if there are any edge cases okay our constraints the number of nodes in the list is in the range of 0 to 200 so you know it is possible that we have absolutely no nodes to deal with which means there would be no order for the purposes of our coding I don't think that's going to end up being an issue you could say hey if the node is null or if the head of the linked list is null then return and that would be a pretty quick answer but we can kind of skip that for now the values in the nodes are going to be numbers between negative 100 and 100 or inclusive and that's okay and then X is going to be okay X's could be greater than or less than all of the values in our nodes I don't think that's going to be of particular matter to us the way we're solving this question but it's something to consider uh but let's move on to some pseudo code so for our pseudocode I just type into the python area the lead code website and the first thing that we need to do for this question for partition list is to create a new linked list that will hold the values of nodes less than x right so that's going to hold all of those values and we're going to have to identify the head of the list for later use right because we're going to end up having to connect them all together similarly we're going to have to create a new linked list that will hold the values of nodes right equal to or greater than right well say greater than or equal to then X at that point okay and then we're going to have to identify the head of the list for later use now these two sentences identifying the head for later use isn't really necessary to put in there but just for our purposes so we understand where we're going with this that's why I'm writing those okay so once we've created those two linked lists that we're going to stick those nodes into what are we going to do well we need to Traverse the linked list we are provided now for our traversal I'm going to say that we should identify a pointer you could just use the head of the linked list that is provided to us but I like using pointers because it just clarifies things for me so identify a pointer used to Traverse the provided linked list starting at the head right so you could just use head as the pointer again but I like being very clear by actually creating a pointer now we're going to have to take that pointer and Traverse the list so that's going to be a while loop right so while this pointer is on a node with value so while it exists essentially what are we going to do well if the value in that node in the node is less than x right so if the value on the note is less than x what do we're going to add this node to the end of the first linked list okay otherwise or else if the value in the node is greater than or equal to X we need to add this node to the end of the second linked list all right so that's all we got for our while loop because that will force this pointer to go through every single one of our nodes and it is going to be reassigned to one of our little linked lists so when the uh the whole link has been or List has been traversed when the original linked list has been traversed uh meaning right meaning the while loop has completed what do we well we are basically left with two smaller linked lists okay so what do we do with those linked lists well we're going to point the final node in the second linked list to nothing right so that second linked list the final node there should be the last node of everything so it needs to be pointing at nothing or null or no or none however you really want to look at it depending upon what language you're going to it just needs to point out into nothingness um as it is the end of our list got it then we also need to point the final node in the first linked list to the first node of the second linked list right and that creates creating one big linked list okay and that big linked list is our answer that is the final thing so finally we just return the head of the first linked list because that first linked list is now connected to the second linked list and we are done with an exclamation mark there we go so this should be all of the pseudo code that we need to kind of slowly make our way through the actual code and it should work with pretty much all languages now looking at it so uh let's get on to coding foreign area of the lead code website and there is our pseudocode so first thing we need to do is create a new linked list that will hold the values of nodes less than x so we're going to call it before because it's going to hold all of the values that come before our x value and it's going to hold some list nodes and it's going to start with zero value now we're going to use this before reference throughout our code it will be moving forward so we can use it to add to the end of each one of our uh or sorry add the new nodes to this list we're going to use it as reference so we're also going to need a reference to its head for later so we're just going to say before head is equal to B4 okay so that takes care of this and we're going to do the exact same thing for the linked list that will hold the values of X and all those that come after so it's also going to be a list node it's going to start oh my goodness look at all that it's going to start with zero value and after head is equal to after okay so somebody might be questioning why are we doing this it will become much more clear when we get to the end of our code so we've completed uh the creation of our two new linked lists now we need to identify a pointer used to Traverse the provided linked list starting at the head now you don't need a pointer here you could just use the word head and Traverse it I like pointers just because it clarifies things for me okay so the pointer is going to equal head and that is where it's going to start now while this pointer is on a node with value it's going to do something right so it's going to Traverse our linked list so I'm just going to say while pointer exists so in Python we can just say while pointer so while it exists well what are we going to do well if the value at the pointer right so if the value in the node is less than x right so if the value at this pointer is less than x what do we need to add this node to the end of the first linked list okay and this is our first linked list it is the before list so how are we going to do that well before right this variable this pointer this head right now is pointing to nothing so we need to make sure that whatever is next is going to equal the value at the pointer okay so that's just saying we've added the Val whatever the pointer is that's going to be added to the end and so now we need to move that before up B4 dot next so it is ready and again at the end of this list so it can accept the next new node okay so kind of similarly if the value at the pointer is equal to or greater than x and in this case we're just going to say else because that's the opposite of that we're going to do exactly the same thing to the after list right so after dot next is going to take whatever at the pointer whatever value is at the pointer the node that is there and we're going to move it up one position in order to be prepared to take on the value at the next pointer now after each one of these we need to move the pointer forward so that it can evaluate the next node okay so that's everything that we need in this while loop for the pointer to Traverse every single node and for each one of those nodes to either be added to the before or to the after linked list we've identified above okay so that is all of this code here now when the original linked list has been traversed meaning we've gotten out of our while loop so the while loop has been completed meaning it's been completed we are left with these two smaller linked lists up here we're going to have to point we now have to point the final node in the same second linked list to nothing right because that's it's the end so in order to do that after dot next is going to equal none at least none in Python okay so we're done there we also need to point the final node in the first linked list to the first note of the second linked list that way we are linking the two linked lists together so before dot next right so whatever is going to come after our before linked list is going to end up being right the after head dot next aha so that is the importance of having of head value identified up here so that we can use it as reference to connect the two linked lists together at the end okay so we're not connecting the zero right because when we started this the kind of dummy heads right we started the after and before linked lists with a value of zero so if we don't use the next value here we're going to have an added zero randomly in between our two linked lists which we don't want which is why we're doing the next value similarly when we're finally returning the head of the first linked list right we are returning uh before head dot next similarly if we just returned the before head it would start with a zero which was not part of our initial linked list so that's why we have to do the next node and that's everything so all we have done is we've created our two linked lists right one which holds the value of all the Val all the nodes less than x the other one holding all the nodes with values equal to a greater than x then we are sticking them together and pointing the end the new end of our linked list often to nothingness and returning the totally new and completed linked list and we're done that's all of the code let's hit run see how we did and it runs fairly quickly at 46 milliseconds we'll hit submit see how we did against all test cases and okay beats only 5.4 of uh things in Python beats only 5.4 of uh things in Python beats only 5.4 of uh things in Python that's not too terribly great but it also is much faster but we're doing better here uh in memory I'm just going to hit submit again see if we can get any better okay there we go 91.85 sometimes it just doesn't run 91.85 sometimes it just doesn't run 91.85 sometimes it just doesn't run really well on the lead code website uh and still doing quite well in memory so this is the best way I can come up with it's kind of only runs through the linked list once so it's incredibly fast um I guess really that's oh Big O N um but it's simple it's straightforward way of solving partition list using python foreign
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
100 |
So the name of the question is Se Tree, you will get this question number 100, I will put this question in the description in the link, go and solve it there, then look carefully, in the problem statement you have two trees given, okay, the name of is Ke. What is this P? This is the root note of the first tree. What is this K? This is the reference of the root note of the second tree. Okay, the root notes of both are given and you have to tell whether they are from both the trees or not. I just want to tell you this much, so who do you speak from? First of all, you will have to ask from your interviewer. By the way, it is written in lit-cot, I will tell you that in the way, it is written in lit-cot, I will tell you that in the way, it is written in lit-cot, I will tell you that in the first condition, both the structures are fine, they should be identical in structure, this means that look at both. The tree looks similar, its root is note, there is a note on the left and there is a root node on the right, there is a note on the left, there is a note on the right, both are from the structure, it is ok, the structure should match, now look, I am changing the structure. I attach it to another note in the second tree. Now it is not identical with the structure. Okay, so it should be identical with the structure, then ours will be called a tree. But there is another condition that let it be identical with the structure but the value of each note. There should be a match, okay, so the root note of the first tree has van on it, then the value of the root note of the second tree should be the same, the root note of the first one is okay, what is the value of the one on the left, the value of the right one should match, this is both the conditions. Then we will say that the tree is from us. Okay, so I told you the definition of tree from us. Now let's go to the algorithm and first let's focus on what is the condition in which the tree will not be from us. If we two We are matching the notes. We are comparing two notes. Okay, so under what condition can we say that it is not related to both of them? The main one of the first condition is a null and why is it not a null, so I am like this here and Let me put it, don't take one of these two, it's okay, don't take one of these two, it does n't mean both of them because both are taps, so we can say that, but don't take one of the two and note on one of them. Is there any value on P? Okay, so I am telling you the condition in which you are rejecting. I am telling you the condition in which you will say that it is not from us. Okay, I am telling you that condition here now. The second condition is that the value of P is something else and this Not equal is the value of tu ke, value of both should match, if I am comparing this root note, there should be van on both sides, neither one is van on one, if I have one on one, then it is not se, then these two conditions. In this we will say that it is not from both the trees. If we are comparing any of the notes and if both these conditions are met then clearly reject it. Okay, now the accept condition in which you will say that yes it is from both, then see. I am telling you in court terms, if the value of both the notes is same, okay, you know, both of them are obviously not null, but there are notes on both, the value of both is same, okay, you compare both and let's go. If the value of both is same then in this case we will not return anything. We will check further also because till the time the entire tree is not checked you can say whether it is there or not. If you can't say then we will compare it in the case and we will not return it. But we will compare and both of these conditions are ours with reject, there should not be a trigger for reject, look here the values have been compared, look here the values have been compared, look here the values have been compared, this has been compared in reject, we will not return, we will move ahead now the left sub tree of this P one. That is, it will match the left subtree of KK, which is the right subtree of P. Okay, it will match the right subtree of KK. Okay, so this is what we will do. If both the roots are matched, then now pick the tree from the left of P. Compare the left sub-tree and compare the Compare the left sub-tree and compare the Compare the left sub-tree and compare the right sub-trees of both. Okay, right sub-trees of both. Okay, right sub-trees of both. Okay, and finally where can you go and say, ' and finally where can you go and say, ' and finally where can you go and say, ' Hey, I have checked everything and if there is a panel at the end and why it is null, do you know?' That is, you check, you have come, you know?' That is, you check, you have come, you know?' That is, you check, you have come, listen carefully, you have checked and this reject condition has not been triggered, meaning there is no value mismatch anywhere, but there is no value mismatch anywhere, one of these two has not been tapped, if it is not triggered and At last you came here that where both the taps are there, you return here, I have explained it in code terms, okay, so let's see its code once and after that we will also understand the time complexity. Before starting the solution, I would like to tell you if you If you buy any course then you will get 10% you If you buy any course then you will get 10% you If you buy any course then you will get 10% discount, buy this Prakash 10 coupon code, these are very good courses, you will get Java course, you will get development courses, you will get DSA courses and they are very pocket friendly. There are courses, there is no need to spend much, they will come in your budget and you will get 10% discount on it, you will get 10% discount on it, you will get 10% discount on it, Prakash 10 code, if you do it then let's see the solution and the best thing in the questions with trees is that the code is not of many lines. This is a four line code but your concept should be correct in this, logic should be correct and look carefully if you change the order of these lines then all your tests will not be passed. First of all it may happen that both the taps What does the else condition do? If there is any tap then it gets triggered but I do n't want to trigger this fall in both the taps, that's why I thought about it, I have already written the condition for both the taps, if both the taps then first. Just get triggered and return, as I used to do, when I go last and both the notes are null, then I will return because if any negative condition which was not ours has not been triggered, then I am last. If both are null then we will start the return and write this line first because and the condition which is the second line, what will it say if P is null, why is it null, if any of these is null then make false if both are null. Even then make it false because what is the logic of the other condition that P is also null and K is also null, still it has to be triggered, it is only going to check that here is panel, why is it null or both are also null. Even then if it gets triggered then it is a very sensitive condition and due to this reason I made sure that both the taps are not there and have already handled it. Now I am checking that if any one of the two is taped then I will get the solution. You know it is not from a tree, make a mistake, how can it be from a tree, it is not from us, now look at this line, now its order also matters, can anyone tell why this is so? Look, if you have checked the tap condition first. Where will you call from and where will you find its value? So this is the null condition. We have handled both of them earlier. Now we are checking that if the value of P and the value of K are not equal then it means that it is not from the tree. By doing false here. In how many ways is it written? If the order gets messed up then neither code will get messed up. Okay, after that if it is not getting triggered, okay it is not getting triggered, what does it mean, look carefully, both are null, both are not null, first line is not triggered. Neither of the two is null, there is no mismatch in the value of both, it means P dot well equal, only this condition is left, it means in this case I had said that it is not returning, in this case we have to traverse, so now the last one. Look at the line of code that you do not do laptop of P. Reverse has to be continued. Reversal means you check further. It seemed ok but I think now you must have understood the concept. Now let's quickly see the time and space complexity of all the notes. Have to check the time complex and why I, you take two notes. Okay, so in the year case, what will happen is that you will check only two notes because here there will be a mismatch and you will exit. Okay, till two notes, I will check it. Lo man lo is from two notes and after that there are more notes here so you will check both at most then you will reject here and exit then n we are main that in which less number of notes what can happen in case Van tu three ok so it can say those balance tree this is P why is it so in this case when your record is just call stack right where all the function calls are stored in it you have these three functions all three records call If it is from then its size will be N. This type of recursive call tractor size will be N then we will say that the time complexity of this year can be big of N. Okay, so this is the stock in the recurjan that will be there tomorrow. Right, we also consider this in space complexity. If you look at it that way, we have not given any extra space to it, but in this rikarshan, the space it is getting is the size of the call stack in it, which will go till the end in this case. Let's end this video and see you in the solution of the next lead code.
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
46 |
in this video we'll be going over permutations given an array numbers of distinct integers return all the possible permutations you can return the answer in any order so our input array is one two three and these are all the possible permutations each of the elements is used once in each of the combinations let's go over the thought process so we will be implementing a recursive backtracking approach for each of the elements x inside the input ring we will need to check if we have already added x to our current permutation this means we need to create a boolean array to keep track of the previous elements that we have already added to our permutation then after accounting for x in our current permutation we will need to backtrack our steps this will allow us to give space for the next element and also allow us to find the next permutation now let's go over to pseudocode so we're going to create a list results to keep track of all permutations then we will be implementing the recursive backtracking approach now what parameters do we need for the recursive calls we will first need our nums is the input array and they are used is the boolean array to keep track of previously used elements and then we have our permutation so our current permutation and then we can have our result list to keep track of all permutations then what was the base case is when if the permutation the size of permutation is equal to the length of nums this means we have accounted for all elements we can add a copy of permutation to result this means we have found a valid permutation and then we can return from the recursive call now in each of the recursive call we're going to iterate through the indices of the input rate all right or the indices of nums to be exact denoted as i if used i is true this means we have already accounted for the current elements then we do not want to use the current elements in our permutation again so i'm going to continue to next index we're going to set use i to true we are we're going to be using the current elements and we add nums i to our current permutation then we're going to recursively find the rest of the permutation now after this after accounting for nums i we want to backtrack our steps so we're going to set use i to false again then we're going to remove the last elements from permutation then after all this we can return our resulting list now let's go over the code we're going to create our list results to keep track of all permutations and then we're going to backtrack our steps the input array the new boolean array to keep track of used elements and our arraylist to keep track of our current permutation and our resulting list and then we can return results now we gotta go to our base case is when permutation.size permutation.size permutation.size is equal to the length of the input array that means we have already found all of the elements then we can add a copy of permutation to our resulting list we want to add new lists because we do not want to pass a reference of permutation into our result return from the recursive call then we'll iterate through the indices of the input array if the current element is already used we want to skip it so we just want to continue else we just we can add the current elements to our permutation we're going to set use i to true to avoid adding the current element again in future you know add the current element to permutations dot add numerous i now we're going to backtrack or no we're going to continue to recursively find the rest of the permutation results and then now we're going to backtrack our steps to allow space for the next elements and also finding the next permutation so remove the last elements let me know if you have any questions in the comment section below like and subscribe for more videos that will help you pass the technical interview i upload videos every day and if there are any topics you want to cover let me know in the comment section below
|
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
|
174 |
Hua Tha Hello Everybody Welcome To My Channel Today's Date 2F June Recording Challenge And Problem Play Eastern Jung Game Straight Problem Statement And Tried To Understand Half Minute Captures Pain And Imprisoned In Harinder Gautam Right Corner Of Danger Consists Of A Gross And Room's Light Off to Degree Tower Valiant Knight's Was Initially Position in the Top Left Room and Must Fight His Way Through the Danger to Rescue Princess The White Heads and Inhale Point Represented by a Positive Integer If at Any Point Health Points Drops 204 Blue He is Definitely So Probably Room And Garhwali Demons For The Night Russia Help Me Z1 And Upon Entering This Room Another Room Zara Here M20 And Content Magic Of Diet Increase The Night Fruit Positive Integers Given In Odis Preeti Princess Class Possible The Night Dumoli Right Word And The Download In Each Step Is Award Function Determine Not Mean That He Also Died Is World Tour Screen System For This Example Notice Needed Minimal Help Needed Is 7 The Part Of Michael Mishra Download 209 This Problem Night Can Move First Direction One Is Right Words Mannerism Word From The Current Say Like Amazon 200 Hair But It Is Standing Hai Arvind Ise Zaal Where Is The Number Of - 1m Recipe Ise Zaal Where Is The Number Of - 1m Recipe Ise Zaal Where Is The Number Of - 1m Recipe Number Of Columns So What We Can Do Subscribe My Location To Possible S One Plus One Previous Song Dj Ki Sale Aur Night Can Go I To M Z Plus One cell morning will take minimum mode to so testing minimum on district synonyms of every cell of band sid subscribe are forced to have these greater than 108 slide minimum help after 69 price updates and fields in jio phone in slice of bread strengthen negative directions Health Plus 2 And Withdrawal With The Help Doing What We Can Do Will Simply Subscribe Share Like And Subscribe - 121 Subscribe - 121 Subscribe - 121 Ki And James Number Of Columns - 151 - One Ki And James Number Of Columns - 151 - One Ki And James Number Of Columns - 151 - One In That Case Be Happy Return Aaj Bhi Value Of Birth Salman Checking The Value Of Images Will Change Person Enjoy So This Festival Just Need Your Help Subscribe Now To Receive New Updates Subscribe To 220 Dhawan Base Cases That Subscribe This Light Is Entered In The Last Problem Slide Channel In The Download Mister Jatt Hain Alive Corpse From Another Point Every morning youth heart right words where is not download the services implementation record implementation by handing over midnight will start from are will start from the private school on thursday subscribe i saudi base cash is that i is equal to a don't like - one and i is equal to a don't like - one and i is equal to a don't like - one and j is equal To basically reach nighty subscribe 280 - 1the subscribe to subscribe 280 - 1the subscribe to subscribe 280 - 1the subscribe to 205 ko masjid is it is great also in these cases advice return negative value of equal me plus one minimum Video then subscribe to the Page if you liked The Video then subscribe to The Last Row Hai To Here The Night Have Only One Option Tu Thekma Icon Z Plus 2D Option In The Distic Chief - Sai Pa Distic Chief - Sai Pa Distic Chief - Sai Pa Hu Is The Current Channel Health West Macrame Subscribe Now To Receive The the last column to share effigy call to 90 a minus one is in that case will return math dot max pro m1 to calculate of commerce in it is not only to download call of j&k 220 is to take max and minimum vindhya You calls brahmin collapse in the most obscure dengue building road them half inch plus minus sexual that coma it is calculated of one m high to mother nights moving in right word decide website - decide website - decide website - that this coma i coma j member recursive implementation of this solution for This Will Definitely Be Time To The Spelling Mistake mid-1960s Awadhesh Singh Written Mistake mid-1960s Awadhesh Singh Written Mistake mid-1960s Awadhesh Singh Written Statement Return That Hydride's Show WhatsApp Is Invisible Developed Implementation And Its 500 Vid Oo Alarm Set This Website Is Time And Development Complexity Of Dissolution And Expansion Select Means Yudhishthir Developed That Tree Recovering From This So Let's Get Started From 0 To Calculate 0 Swelling Co One Is This College Download And Describe The Calling Similarly From Share and subscribe the Channel Please subscribe and subscribe the Channel Programming for Solving Subscribe Now to Receive New Updates Penis Lee Hai Don't be in the field with minus one and sea of numbers In The Amazing Channel and subscribe the Channel dot nick pic ki and com Ranjan Shyama like oo ki sabhi bill pass duty are quite beautiful function call and he will also take this intense pain in every function call -will pass intense pain in every function call -will pass intense pain in every function call -will pass tp dipping 's comedy dpco and hair comedy p 's comedy dpco and hair comedy p 's comedy dpco and hair comedy p loudest recursive function calling calculate method nominated in the condition will check effigy of chronic cases null's spirited away from were that other wise bf2 fielder value in to the year and return gift commerce and Industry Mein Likh S Yes This Share One's Second K Se And Distress And Third Tips Hair Oil Fennel Button Hair Oil Civil Services Difficult Servi Noise Pollution subscribe and subscribe this Video 133 Accept Sadhi Date Of Birth Dalni Approach Solution For This Problem Solver Time Complexity Of this yes time complexity and space complexity is very much of lemon ware is MS Word number of rose and kolam is so this is the top Dhanteras fennel number plate me explain you have canceled the bottom as explain you beat start from this up from the last Salute Minimum Health Midnight Tours And Distance Id 2nd Test Minimum Nine To 10 - - 5000 Minimum Test Minimum Nine To 10 - - 5000 Minimum Test Minimum Nine To 10 - - 5000 Minimum 600 Out Of 600 800 How Will Celebrate Independence From This Is The Minimum Which Here Individual Has Been Dead Due To This 209 Share It Is One Subtle Game The One Shot How Much Needed To Reach In Distance Between Ther Stories In This Last Week 5 Minutes Simreli Arghya 3000 Minimum Set Health Tips Subscribe A Beta Testing More Fun From The Minimum Of I Plus One Ki Ko Majhe Ki Value And Di I Comedy Z Plus One Shot 271 Is Right Words Mannerism Download Tamil One Message One And Support To Na Ho How Much Needed To Reach Here's Absolutely Minimum Of This 270 Already Know Your Fair End One Has To Be Done With Minimum - Time Will Has To Be Done With Minimum - Time Will Has To Be Done With Minimum - Time Will Consolidate Leaves - 9 - 20 Plus One Which Is Consolidate Leaves - 9 - 20 Plus One Which Is Consolidate Leaves - 9 - 20 Plus One Which Is Electrolyte Minimum Help Your Wings To Big Dipper Similarly They Will Go Hair He Swadesh Will Be From Doing Only 50 To Hair Thursday Subscribe Now He Will Do Any Role In Hair Vitamin B6 B12 Minutes Ago Things To Major will get enough water important dry approach not implementing co dangerous development to note this video dot co dot in 200 time that we solar system aap solution software wali one and a half size ko 1MB test subscribe 10 medium to reset subscribe my channel will Last A Column SMS Sexual Top Growth Rate This Condition For Similarly Will Last Problem Will Not Come From The Guide - 151 - Not Come From The Guide - 151 - Not Come From The Guide - 151 - Karma Flight Mode Of The Value Of Flying Just Subscribe - 21 This Just Subscribe - 21 This Just Subscribe - 21 This Quest For Calculating The Way What Will oo can destroy animal depend one is right side effect sunidhi implementation for water play list co battery saver is jar dp dot lens symbol ok dpco chief language a tip-off 089 david engine are 100 special a tip-off 089 david engine are 100 special a tip-off 089 david engine are 100 special or acid compile now in this complex matter what amma What is pollution it is active and time complexity of dissolution also semester top down for the time complexity is for payment in the number of rows and columns similarly subscribe ka hisab 100 of amazing peer thank you feel like a solution class 8 the like button and subscribe my channel thank you
|
Dungeon Game
|
dungeon-game
|
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.
Return _the knight's minimum initial health so that he can rescue the princess_.
**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
**Example 1:**
**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
**Example 2:**
**Input:** dungeon = \[\[0\]\]
**Output:** 1
**Constraints:**
* `m == dungeon.length`
* `n == dungeon[i].length`
* `1 <= m, n <= 200`
* `-1000 <= dungeon[i][j] <= 1000`
| null |
Array,Dynamic Programming,Matrix
|
Hard
|
62,64,741,2354
|
1,926 |
away for a while some of you know the reason for it was my sister's wedding and I took the liberty to enjoy that event thoroughly by God's grace all the event went really well and I'll be sharing the glimpse of my D dance performances very soon so that you guys can enjoy those too however now it's time to get back to business the problem that we have in today is 1926 nearest exit from entrance is maze here in this question you are given Matrix of size M cross n and you're also told that this is a starting point of that Matrix what do you need to search for an exit in that Matrix this Matrix has some obstacles in it and those obstacles are represented by these bricks you are standing over here you need to identify the closest exit from the entrance position for example if this is the enter position where is the closest exist exit there are three exit in total the first one is this one the second one is this one the third one is this one so this is not achievable from this position only two valid exits are first one is this one second one is this one which one is the nearest one this one is the nearest one so the distance between the current location the entrance location and the exit happens to be of one unit therefore the answer will come as one the question is very similar to rotten oranges and we will be using the same technique over here as well now let's get back to the same problem so here you are standing at this entrance location these are the blocked walls you can't Traverse over here and what do you need to identify the nearest exit from the current entrance location so this one is the nearest exit which I'm highlighting just now and the distance between this location and this location happens to be 1 unit in total there were three exits 1 2 and three how are we going to solve or approach this problem up the answer lies in simple BFS reversal why not d FS let's understand that problem up here I've taken a slightly longer example so that you guys get a good hold of the underlying concept the entrance position that is given to us is this one the for in the first SC what I'm going to do let me identify the exit locations that are reachable from this position so this position is one possibility of answer uh this position is not reachable because this is blocked by these two walls so this is not reachable let me just write cross over here these locations are possible so you can reach this cell by this root so all these cells or exit points are reachable uh the next one would be these two so these are also reachable these three are also reachable remember these are not reachable the ones that I'm highlighting just now so you can't reach this because these three have been blocked these three exits have been blocked by these three walls so this makes it these this it makes these exits non-reachable in nature now comes exits non-reachable in nature now comes exits non-reachable in nature now comes the question how are we going to solve this problem up so we will use the simple BFS reversal and starting this position what we are going to do we'll iterate in BFS fashion and we will Mark the least distance from this current location to each cell given in the question that is reachable in nature so this cell is reachable let's write one over here and this is nothing but the level of your BFS traval so this is at these three cells are at level one now what we are going to do these three would be inserted back into the que and we will Mark those cells that are at level two so what are those cells this one is at level two this one would be at level two and this one again would be at level two so we have marked all those cells that are at level two and uh moving ahead using these level two cells we will Mark those that are at level three so let's start the iteration so this one would be at level three uh then this one would be at level three so if you carefully analyze then you will see that we have reached one of the boundary locations and this one represents the boundary location that is reachable for from this entrance location as a result of which we have found out one possibility of answer and this will be the least one the answer becomes three and the exit is by this route so let's just represent the exits and this person's standing over here can make a move by this particular route to conclude it further let's walk through the coding section and I'll exactly follow the same steps as I have just talked over here we will be using the visited array as usual that we keep in the BFS reversal uh so you'll get the crystal clear idea of the algorithm by the coding section the time complexity of this approach would be of order of n cross M the thumb rule of BFS reversal is to create a new queue so here we have created a queue and the generic type of this queue would be an array of integers and this basically represent the coordinate system X comma y moving ahead I have added the entrance coordinates into this q and I have taken a variable named level that basically represents the distance between each and every cell uh from the entrance location moving ahead I have created the visited array I have marked the entrance location as visited and at line number 15 I have created a 2d array that will help me identify the new coordinates from the existing one that I'm currently add and we already know about these four coordinates so it basically helps you generate the new coordinates in all the four directions up right bottom and left so let's start the iteration while my Q is not empty I increment the level value and I extract the size of my Q I go ahead while size minus is greater than zero what do I pull out the coordinates the current coordinates from the Q and then I move ahead in all four directions uh using the directions array and once I have the new row coordinate and new row column coordinate using the formula that we have used plenty of times in the past what do I check whether the new the next row or the next column is within the limits or not if it happens to be within the limits and it is not a wall I check whether it has been visited in the past or not if none of if all the conditions make makes it a happy case I further check whether it makes up till the boundary conditions whether the next row or next column happens to be any of the four boundaries uh then I simply return the level value that I have so far in My Level variable otherwise I go ahead and Mark my next row and next column as true and push it back into the queue if my return condition at line number 32 is never met I simply return the final answer as minus one in case uh we are unable to reach any of the four boundaries so let's try and submit this up accepted uh 70 67% faster which is accepted uh 70 67% faster which is accepted uh 70 67% faster which is pretty good and with this let's wrap up today's session the time complexity of this approach is order of n cross M because he will be visiting each and every cell only once and space complexity again would be of order M cross n because you are using visited array over here also if you're looking for Solutions in Java C++ or python then for Solutions in Java C++ or python then for Solutions in Java C++ or python then Jes has submitted the python solution s of has already submitted in Java and someone or the other one s sang would be submitting uh the Solutions in c+s very soon so if you Solutions in c+s very soon so if you Solutions in c+s very soon so if you also want to build a similar level of consistency then coding decoded GitHub repo is for you I'll be more than happy to review a solution and dump it into the master Branch with this let's wrap up today's session I hope you guys thoroughly enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded I'll see you tomorrow with another fresh question but till then goodbye
|
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
|
807 |
hey everybody this is Larry this is me go uh doing an extra question because I'm trying to take advantage of my premium uh lead code it's February 5th uh of 2023 man these years they go fight by don't they all right let's get started let's do a random one um okay to do and let's go any difficulty give me one well okay but not an SQL problem uh can I yeah I don't want to do an SQL Palm today so let's try again I need to go food I'm Delbert and another one maybe I do just need to go food I'm at some point uh but today oh wow they really are maybe do I only have SQL problem steps three times in a row all right let's take a look at this one 807 Max increased to keep City skyline um I would also say if you're interested in SQL problems in general let me know in the comments I don't I'm curious whether I should record those uh I actually have a lot of years of experience on SQL I started on SQL actually for those people who actually watch this video even that many people watch the bonus questions these days but um yeah I started on a web app in the 90s which is a ridiculous sentence if you think I look very young which a lot of people do um yeah um started a web app in the 90s they didn't even call it web or app or whatever back then which is a website and it was powered by SQL MySQL if you will uh in uh what's it called isem or whatever but uh I forget about the but they had a dollar based model that was like very used to come up and I got back up all the time uh versus like movie which is apparently I think the thing that is people but what people use these days I believe on MySQL there's of course a lot more uh SQL in general in both um you know postgres SQL and there's also like on the other side of Big Data stuff like Hive and uh and some more like real-time stuff but uh but also like real-time stuff but uh but also like real-time stuff but uh but also like with pre-processing on data I forget with pre-processing on data I forget with pre-processing on data I forget what an example that is off my head it's been a while but anyway let's take a look at this problem and let's get started and see what this is about and again even though I said that I have this premium thing this is not a premium problem so I don't know okay yeah I wonder if I should focus on premium just in case that just gets to be a regular problem in the future maybe I'll do it tomorrow or something anyway let's actually get started with uh three minutes of me renting okay 807 Max increased to keep City skyline okay so there's n by n block where each block contains a single building shifter like a vertical square prism um so it looks something like this okay and then you're given zero index with grid of RC in the height of it okay so you're giving the height a city skyline okay we're allowed to increase the height of any number of buildings by any amount the height of Zubin however increasing the height should not affect the city skyline from any car no direction we turn the Max total sum of high deck we increase without changing the skyline by any condos Direction huh that's an interesting one so okay so I think the first thing that I would think about when I look at a prime like this is try to look for invariants I've I don't know how to solve this one off my head it's not a I mean I have some ideas just from experience but it's not you know I'm not one of those people who try to well even if I used to be probably I used to be at some point but I don't have that collection of um problems in my head anymore nowadays it's more about just resolving everything again uh but in any case yeah so the first thing that I would try to do um and I'm saying it as someone um trying to articulate you know how I would attack this Farm is try to find about an invariant or an observation that I can make right um okay so the so one thing that I think we can do is we can look at each number or like what is n i mean n should be that big or n Square shouldn't be that big oh no 50 even smaller right so it's 50 and there's a hundred so we can probably force it if we're very uh slick but even beyond that we can probably like we can we look at each cell once and just see how much we can increase it right all right let's take a look at how we think about this right north south hmm that's okay that's fine I think one thing that I was curious about um and they drew it a little bit different I think as a way to kind of I would say at Red airing per se but something similar just to kind of throw you up a little bit but if but it should be and this is what makes sense to me but I was just checking it because I didn't want to say something inaccurate which is that looking from the north and looking from the south um they should be symmetric right meaning that if the highest building on row uh column Julius a then it's going to be a from the North or the south on the third column maybe you know you flip in column one uh maybe in one it'll be column three and the other one is column two or something like this right about which type Direction by the way the shape of it will not change right and using the uh same logic uh yeast and West will be the same thing as well right so what does that mean that means that we only have to keep track of two things instead of four things but then the other uh after that the next observation is that um basically for each cell I'm looking at this zero here you can't really see me highlighting it but I'm looking at this the green zero next to the three uh yep okay just checking that you can see it on the screen um looking at that basically it means that on the um horizontal side you can increase it by as much as eight and then on the vertical side you increase it as much as four right so that means that essentially you can only increase it to four which is the Min of the max between the horizontal and vertical and I believe that's pretty much it right um in the sense that I think basically we calculate all these things and then we just take the Min of the max of the two things and then we redo it um and because it doesn't change anything we just have to do it once there's no uh um there's no iteration needed in terms of you know after you finish coating the first time scanning it all the other buildings um you're done like there's no additional changes because um yeah right okay so let's just say uh columns is equal to zero times n and rows is equal to zero times n um and this is just basically um just adding a little comment because I will mix them up otherwise close is the highest of column uh X right so because of I right something like that okay so then now we just do uh and then we have grid of X Y uh what do we do with it well COS of y yeah uh just making sure that I'm consistent so this thing right I don't know why I didn't write books first I usually do this is how okay right and then that will give us the outline of this of the thing from north and west or maybe yeah I think so and then which will give us the entire outline and then now what are we returning we're turning the maximum total sum that could be increased okay so yeah so we have total of zero and then we do it again right so then now on this cell as we said we want the Min of the rho sub X COS of I and then so this gives us what we can build up to so then we want um this number minus a grid of x y and then we want to make sure that it is at least zero and add that to total right and that looks good enough to submit and there we go um yeah so the input is actually n square number of cells um the algorithm that we did is going to be linear uh in terms of time because you have to look at each cell once there's no way around then we do it twice so it's going to be linear time in terms of space it's actually sub linear square root of n or n to the one-half if square root of n or n to the one-half if square root of n or n to the one-half if you will um because we only need all of n we only need square root of the linear of the input size space uh so yeah um yeah that's all I have for this one let me know what you think let me know if you have any questions um yeah that's what I have so stay good stay healthy to come mental health I'll see y'all later and take care bye
|
Max Increase to Keep City Skyline
|
custom-sort-string
|
There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at row `r` and column `c`.
A city's **skyline** is the outer contour formed by all the building when viewing the side of the city from a distance. The **skyline** from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of **any number of buildings by any amount** (the amount can be different per building). The height of a `0`\-height building can also be increased. However, increasing the height of a building should **not** affect the city's **skyline** from any cardinal direction.
Return _the **maximum total sum** that the height of the buildings can be increased by **without** changing the city's **skyline** from any cardinal direction_.
**Example 1:**
**Input:** grid = \[\[3,0,8,4\],\[2,4,5,7\],\[9,2,6,3\],\[0,3,1,0\]\]
**Output:** 35
**Explanation:** The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = \[ \[8, 4, 8, 7\],
\[7, 4, 7, 7\],
\[9, 4, 8, 7\],
\[3, 3, 3, 3\] \]
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\]
**Output:** 0
**Explanation:** Increasing the height of any building will result in the skyline changing.
**Constraints:**
* `n == grid.length`
* `n == grid[r].length`
* `2 <= n <= 50`
* `0 <= grid[r][c] <= 100`
| null |
Hash Table,String,Sorting
|
Medium
| null |
349 |
in any order okay so this is the first example in this first example these two in this area is given to you your output is 2 okay because you have to return the unique okay unit element you have to return and the result can be any order so your output is too high so because a unique element because means if you intersect these two arrays and what you will get 2 and 2 but you have to Regent a unique that's the only two okay I think this is clear this is the second example this is quite easy like um the what is the intersect elements is 4 comma 9 right so you have to return the unique element so that's why and you have to jump nine comma four or four comma nine okay so uh order is not a peak problem for us we can return in any order okay it is clear to you so basically now you have to return an integer array but you can you cannot declare an integer array without size so that's why as part I will just take an arraylist okay and um and I will just add all the element in our array list and at the end we just click clear and array with the same size of arraylist okay so I think this is clear to you okay let's start then you can easily understand what's going on okay has said okay because you have to return the unique elements means you don't have any duplicates so I think for that case has said is the best choice for you okay so in teaser okay new has said okay she has this is for nums one okay and then I'll declare another headset okay and I will just add all the elements nums one Aces one dot add I 4 8 I nums two and I'll just all I will just add all the elements in nums add you know second has said okay so now the asset will store all the unique elements okay will now store any duplicate element it will store all the unique elements okay so now I'll just Traverse this um you can travel um first has said or second headset okay I'll just Traverse the second asset okay you can take also the first hash set if okay now let's take the added list okay array list integer type array list okay n equals to new I released H is um one third at I okay and we'll just add that element in our array list okay then I just stick clear and array the an array okay no diary list new answers size okay then four in I a l in k equals to zero of a r k equals to I and then K plus okay and then at the end all you need to return that particular array okay it's clear now let's run this code so basically um you have to return the unique element Stone like so I take two headsets because for Unique element like you have to remove the duplicate ones you only need to return the unique element these types of question has said is the best choice why is your bigger asset can only store the unique element it will remove all the duplicate elements there it will store only the unique elements okay means hassle will now store any duplicate elements that's why hashtag is the best choice for these types of questions okay so I'll just take two headsets for nouns of one and one nouns of two okay and I'll test take an arraylist okay so basically this array is like for because you have to return an integer array but we don't know what is the size of the integer that's why just declare and add a list okay and at the end I just take an array okay because at the end you have to return the array right so that's why I just take that arraylist and I just um take an array of the size if arraylist the same size of this arraylist size okay so now I just reverse this nums 1 and nums 2 and I'll just add all the element means what you have you know has it you know means you know has it what you have 1 2 and means node one means only one and one what you have in this has only two because I have this told you has set can only store the unique elements okay so it will store one two and it will store only two okay so now I just Traverse our hash set two here you can also Traverse your headset one okay so now if we use here hash it one then you have to write your asset 2 okay so now like now you are traversing what is your first element is 2 okay now you are trying to add this 2 in this hash set right so now this method will give you false like this add method will give you the Boolean value and if that particular element is at in our Hazard success pulling then this add material particular element is not at in our hashes successfully then this method will give you false so now this method gives you false why so because this 2 is always a present in our asset one right so now this method will give you fourth but here I have used no to operator that's why now this overall condition will become true we just add that particular element in our array list okay I think it's clear okay so now I have just declared and added okay and what is the size is same as the arraylist size okay and I just traversed I released and I just add all the element in our arraylist uh sorry you never add in okay I think it's clear to you if I have any question your definition asked me in the comment section okay so now let's submit this code huh time complexity is order of n okay and what is the space complex it is space complexity is order of n okay so uh that's all for this video thanks for watching I hope this video is helpful for you see you in the next video
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
791 |
Hello Everyone So today we will solve another problem of Lead Ko Daily Challenge Custom Short Sting Let us start if you have not subscribed our channel then please subscribe then first of all let us understand the problem statement what is given to us So let's start, you are given to string order and S, so we have been given two strings, order and S, all the characters of order are unique, whatever is our order, all the characters in it are unique and they are sorted into some. Custom orders and they are sorted through any custom order that any custom order will be an order is created matching it param mutate the character of s so that they match the order is the order was sorted so what we have to do is we have to S has to be permuted so that whatever is the order of our order string should match such that given in this e character s comes before the character wa in the order if any character x is coming before the character wa in our order string So this is the same, what should be ours then let Our problem statement was given, so now let us see its example that our order has been given as CBA and our sting has been given as AB CD, so what we will do now is that before the character C which is character A, our two characters have been given the order. In CB, then first our character C will come, then B will come, then A will come. So see what has been done in the order here. First character C has come, then character B has come, then D has come, after that character D has come. Or our permuted sting is done, so let's go. Let's see its logic, how will we make it, now our order has been placed here, so first of all, what we will do is take a map and in the map we will store the sting which is ours, like how much frequency is B, how much frequency is C, what is C. Done, and how much of D will be done? How much of D will be done? One, so the first step we are going to do is that we will store our string A in A, then what will we do after that, we will iterate the order, we will check that the one which is C is If it is in our map or not, then we saw that if C is in the map, then we will take it and its frequency will be added to our resulting string. Like, we have assumed that this is our resulting string, so what we did is, if C is there, then we added C. How many times did it come, once did we add it to B, then saw B that B is ours here, yes, so how many times did we come, once did we add it to B, then saw which character is A, saw that it is available in the map, yes, it is A, so How many times did he come, once, he will cross it out? Now what happened to us, these three characters have been added now, what character is left, one is left, then whatever is left in the last will be removed, and how many times it comes, he will cross it out once. So this will become our result array and we will return it, so how many steps is our solution now? In two steps, what we will do first is we will store S in the map, then what will we do after that we will order We will check whether its character is present with us or not. If it is present then we will store it in our result array. So now let us write its code. So what will we do first of all? We will take a map in which we will store our string s, so we have taken the map, character and integer, so this is our map, what will we do with it now, if we will store the map string s in the map, then what will we do, we will put a for loop and extract the character. So what will we do with the extracted S? First of all, we will convert the string into a character array here and then extract its characters. After that, what do we put in the map? What did we do with 's'? Which one did After that, what do we put in the map? What did we do with 's'? Which one did After that, what do we put in the map? What did we do with 's'? Which one did our character come in? How did we get and default it? There is one method, what we do in this is that if it is already available in the map, then it will extract its value, if not, then its by default value will be put as zero and it will be plus one, we will increase its frequency, then this is our Now what will we do, we will take a string, we will take string builder, what will we do in it, we will store our result, so this is our string builder, then what to do in it, we will iterate the order, what will we do with the beans of the order, we will extract the character from which, order from sting, order dot. Now we have created a character array here and extracted the character from it. That's it. What will we do now? Now we will check whether the first character of the order is present in our map or not. What should we do with the content key? If it is present, then what will we do, we will calculate its value, what is its value, how many times it has been printed, then mp dot get seech, we have extracted its value, as many times as it has been printed, we will add Kism in our result string, so what we have done is as dot and If we have subtracted the stitch and value, then this is our loop. Now when we are finished, what will we do, we will remove that value from our map, whatever our character is, we will remove that character. The work is over and removed, what will we do now, whatever character is there in our order and that character is also in our S, meaning the character which is common in both, we have removed it from S and stored it in our result array. It is in our order, meaning it is in the string S but it was not in the order, so we will store the remaining characters, so what will we do for those characters, we will extract them from the data set, and what we did is we will also compare their value. We will extract the int value map dot gate C and will apply Y loop. As long as our value is greater than zero, we will append it to the result array A C. What is the value minus now, whatever is our remaining character has also become D. What we will do is simply create our result array, convert it into a string and return it by adding T, then this is our code, so let's run it and see, oh sorry, where did get and default fail, so what is our issue, we used get and default. But on which map should we have put it? MPD gate will be default. Here, this was our issue. Let's run it again and see. Now all our test cases have been accepted, so let's submit it. So our code is accepted, guys, see you in the next video, till then thank you.
|
Custom Sort String
|
split-bst
|
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**.
|
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
|
Tree,Binary Search Tree,Recursion,Binary Tree
|
Medium
|
450
|
807 |
Hello Hi Friends Welcome Back To Days Ago Into Solitude Problem 10 Maths Increase That City Skyline After Start Looking Into The Details Of The Problem And Some Example Clear Mention That My Channel Is Dedicated To And People Hu A And Preparing For Code In Interviews And Where Introduced And All My Channel The Royal To Harold Examples Which Were Taken From Previous Vyas Interview Questions For Amazon Apple Google Facebook Microsoft Yahoo And Manya Rate Pick Company And Who's First You Different Varieties Of Problems Which Are Very Important For Coding Interest Interview Perspective True Dynamic Programming Graph of Like Related Problems Binary Search Tree Leaves Binary Search Related Interview Questions and Lag Increase Questions Spring Questions and You Know Benefit Matrix Related Interview Questions Will Also A Few of Preparing for Java Interview Recording Interviews Please Subscribe Channel Like My Channel Send Definitely Help You In Your Job Interview Preparation For Please Subscribe So Let's Go Through The Description Quickly So Delay City Composed Of Pain Into A Blocks Where Is Blog Contents Single Building Area Vertices Person Them You Are You 180 Inducted Into Inter metric Create RC Represents Height Of The Building On Screen Located row art and columns in the city skyline is the shooter control from by all the buildings viewing the side of the city from a distance subscribe line from each cardinal direction north east south and west also have different way alarm to increase the height of any number Of buildings bar planning amount the mind can be different for building the height of zero height building channel should also increase which means that you dare ignore building which can more make building a better place basically a heaven increasing height of building should not left city skyline from Any cardinal directions so what is means is give ur looking skyline from north and poor in preventing lag increase singh samudra building hide and seek puberty and change basically after hui or do yar increase in the height of samudra building and a tax officer return then maximum total Some the height of the buildings can they increase by without changing the city skyline from any cardinal directions Saudi Arabia fold cardinal directions and north south western east saunf increase in yadav building size think should not affect the skyline view from any for these four directions Water problem in so let's take this example to here and avoid discussing about this problem is so is subject one example which you can see here for example of your life gets a fair lion decide from west right so in this direction for watching and gift you Want to Increase Building Its Edison Wright Sui Can Increase Building and From 3282 E Can Increase The Types of Increase 1328 Institutions Can See This Sign in the Same Way Bigg Boss-8 Host That Bigg Boss-8 Host That Bigg Boss-8 Host That Was Previously Highest Building Na Hui Meditate Hair Soft Twist the Sky Line Will Still Be Able To See From There Bit Wick And If You Were Looking From The North Side Will Still Be Able To See Noida Highest-on-High Will Still Be Able To See Noida Highest-on-High Will Still Be Able To See Noida Highest-on-High The building right from the north is similar to the entire descended Gurjar looking for its education from east institute and see the right and what do you want to see or so it is not changing in skyline and if you were looking from south west in this direction and still vacancy In this they like them a little and they can see and still describe remains same basically in this fight and basically a 800 this is the maximum height we can make it a point to make in this line will change view from west developed you certificate is Highest Building Now Give Me The Novel Method Is Building Society Standing Beside You Were Moving From West Basically Side ₹100 Note Style Basically Side ₹100 Note Style Basically Side ₹100 Note Style Thank You That Show Aam Similarly Solid Minute Till 20 Comes Back Again That Similarly IF U Want To Change This Channel Like This Channel Day they can make this allowed for maximum Right for is the maximum height we can make and white in Bigg Boss-5 This make and white in Bigg Boss-5 This make and white in Bigg Boss-5 This point and still you were looking from north will see you used to see this for different na state will see again were looking from North to it is not changing its LMB you were looking from west to tail you know it is and showing 4 minutes will show create and highest building right side change in the sky new senior leaders from this also you will see what is the highest website will not Change Is In Your Toe And From South Also A Few Years Since This Direction Here For Evil Spirit Soul It's Not Changing Dress Of Ireland UP Police Merit 519 Change Style And Varied And Will Starts In Five From South Pacific Not Changed S File Which Itself Maximum Is Liquid Form 10 Years A Politically So And Now They Are Going To Solve This Problem After Hits On What We Can Do It Is We Can Go Through This Today E Agree With Human 2% Will Capture The Maximum Row With Human 2% Will Capture The Maximum Row With Human 2% Will Capture The Maximum Row And Maximum Column Element Slide Show In this road maximum element is for it will capture volume maximum row element dry date 600 800 60 minutes to loot can go for words for this is important tips on all rules will want to find you maximum for example vestige maximum in this rock day in directions From one is maximum ride in directions - maximum and maximum ride in directions - maximum and maximum ride in directions - maximum and indal president when maximum it should have captured in to our form romance share rate and similarly you want to capture the columns volume maximum call option hind is column noida ball maximum birwa in main kal office maximum in This column in this maximum right and in this column seven inches maximum do 9486 have captured at * work volume maximum 9486 have captured at * work volume maximum 9486 have captured at * work volume maximum here and you have listen a maximum volume maximum proof address school can you know you will prepare for watching this poor screened one after the rate in Superintendent Grade One By One Position Will Welcome A Maximum Of Soil And Water Minimum Value In This Is Maximum Subscribe For Example Maximum For Right Clear And For This Column Is Not Volume Maximum Correct Format Surya-Shiv Fancy Dresses Format Surya-Shiv Fancy Dresses Format Surya-Shiv Fancy Dresses Swift Absolutely Minimum Value From This To Basically Rights Will Be 2228 Without Changing Subscribe Now You Will Not Give Winners From All Directions Cardinal Directions Subscribe Is Not Changing In Tijan Z2 Basically From West Indies Pair 12238 Software Looking From Narada And You Will See Job Arvind Chapter Note IS ONE WICH USED TOO SE ZOR Change interview for this also you man lion will back on flight from this side again they are not changing skyline you and your scene from south from this one and against will see 982 u0026 just create should have to go like it say like this and Find out the minimum of the maximum subsidy for example when they got here name right the maximum for Detroit and maximum for the column is for right maximum problems to solve minimum in this is for basically so they can reduce to for physically side similarly can Go from a little thing about life and works and calculate how much rate these possible points and will handle upright and will get the total possible dress that is possible so is just went through this grid and is rooted for here from you so much as you can see The forest trees for it - 350 year is the for trees for it - 350 year is the for trees for it - 350 year is the for stress se countries for redmi note 4 - stress se countries for redmi note 4 - stress se countries for redmi note 4 - 043 dress will be like as you can see servi loot govind ki dikha for this road maximum will be 840 and the minimum leg maximum for this of provisions and Columns Also A Tight Call Me Jaanu Sorry For That Basically Soft I Seth - Minimum Of The Basically Rahil Sharif Yudh I Seth - Minimum Of The Basically Rahil Sharif Yudh I Seth - Minimum Of The Basically Rahil Sharif Yudh Can Not Making Arrangements Or Means In These Cases Will Be The Race Basically Right Clear So That Is How Are You Can See All The Sense Of Forms for this is again to here you here day maximum rise and here right end maximum column and enemy from this they are so they can take minimum of the basically suicide cut in war 787 - course 300 years race iron air tight 787 - course 300 years race iron air tight 787 - course 300 years race iron air tight similarly a protest for all The You Know Desire Total 6 Inch And Here All 1600 Tips And If You Calculate Total Of All The Order Of The British Empire For Example Five Plus 393 Is Prime Plus Five Is Part Plus 50 Plus Two Is Note Plus Two 200 223 Plus 1427 Per Plus 232 plus 335 members have total reigns wave champion trophy 2830 hui cancel maths increase to tips city skyline so they can increase the buildings dead sale absolutely maximum possibility like this and hui tune with now disturb in the existing skyline basically 800 latest place director implementation like share Subscribe we noida calculated in which is the great language is created romance and column back side developed first wanted to calculate this romance and column x healthy school greed and they will capture the romance and documents for each row basically right clear and you can see a So any business throw like share and they will update the romance se zoom and basically use it Madam Totally Responsible Initial 18202 And Again We Are Going Through Subscribe And Share Capturing The Hui Attacking The Rumax Sharif I Am Com X Video Of G-20 Leaders And Converting Video Of G-20 Leaders And Converting Video Of G-20 Leaders And Converting Minimum Value Update And Against Subtracting Current Sale Value For Example Clear Hui Have Kid Right Minimum One Hui for its rate - Stree is favorite Subha One Hui for its rate - Stree is favorite Subha One Hui for its rate - Stree is favorite Subha software doing so will rise after and where Dasharath * Total press possible and so will do it Dasharath * Total press possible and so will do it Dasharath * Total press possible and so will do it for every sphere 100 g Raju can see hidden ladder will return to trace Possible types of hair time complexity of this old Is gold of in this website * In basic values in square that Inspiron time complexity is in square and they have created over two years year to shoulder maximum of possible so basically you can see the space complexity is show in its place complexities one because You have created this to address is otherwise website the readers can we have maximum elements of classes to it is equal to complexities open and still retired for suicide solid sin square of its order of Inspector Ashok this is the implementation of how they can solve this Problem Solved They Can Just One This Example2 Shyam Bluetooth Setting Show Will Just Go Ahead And Take The Giver Share On 200 Abs Can See Them Next And 1000 Correct To Aam Upton Make Another Test Cases Will Hear That Chatur Check You Know One Can Make Its A jis building gas ko and this building is too late to fight and see how are you i pot result hui get clear hai 200 yar cutting for air tight fennel 2008 summit interest rate in this movie related issues and a i which police Peshi a 13005 blackness ki 13005 blackness ki 13005 blackness ki purva hero 10000 tit 034 hai aa a comment for this one software testing isko Navratri Vikas office late se this is the maximum writing in English Shyam ji ko hi in the future will be maximum End years e will be maximum kar do hai to let's right download fennel and road maximum will be 420 end to right for 2012 vriddha maximum for romance and column actor will be 420 250 loss sunavai new year celebrate in half an hour maximum minimum from this 250 Hour Minimum From This 250 Hours After This Oil Is For Maximum Volume Maximize Do People Without Impacting And Spire Line You Will Give Them Hair Day Maximum Of Rule B0 Share And Maximum Keep Long 409 A Maximum Of Pro0 And Maximum Of Column Is Forces Who have taken minimum of that so e can not make strong neeraj clearance 0.2 simple 1600 par dushman 02 software which can make an easy 25000 is the romance and development software a hundred minimum of temperate song again came across 2014 method romance and will be to Medium to Right to the Question Is the Road to Make Sure Minimum Me and Share Romance 2020 with Total Visits How Two Plus Two is Equal to Two How You Can See Footwear Getting the Correct Answer Suvty Suv Will Appoint Meet Says Will Give and Will Compete with Rate Romance Value and the Problem Max Value for the Time Rohit Isro And This is the Calling for Example 14322 Come 108 K Explain in Details with His Two Examples Which Golden Submit Our Solution 20000 98% Poster-Banner Raw Submissions and Seventy Five Per 98% Poster-Banner Raw Submissions and Seventy Five Per 98% Poster-Banner Raw Submissions and Seventy Five Per Cent in the Memory Site Which Has Pretty Good 34 The Way You Can Solve Maximum Krrish 2's City Skyline So It Can Harm You Have Used In ODI Concept Back Cotton Just Calculate The Romance Share End Column Mixture War To Front When It Is Total Dress Possible And How Much Total Trains Will Be Right And With Jaswant Roll Se To Calculate Total Prayer Is Difficult To Here Founder Salary From This Point And They Descended Into Total Are To Find The Total Way Common Death Is 121 Virud Playlist On My Channel Bollywood And Input Solution Please Go Through it Nov 28 2012 Problems that were taken from the rear of big tech companies like actor Apple Amazon Facebook Google Yahoo Microsoft and many rates and problems of very important from food intake new perspective because friends institute important point this true dynamic programming side related problems binary Search Tree in Binary Search Related Interview Questions Link Less Related Interview Questions Difficulty and Matrix Related Interview Questions Well and Also Helps Java Interview Questions Which Were Javatypoint Frequently Asked in Interview Questions in Job Interview Playlist A Software Looking for Life After Preparing for Java Coding Interviews and Just Simply Job Interviews Please subscribe to the Channel Now This Channel Money Will Definitely Help You and Your Subscription Really Important Tourism Develops Illegal Videos Can Reach to More People The Can Also Watch This Sort of Problems and You Know That Can Also Get Here To Understand How To Solve Different Types Of Problems And Causing Problems Using Tower Please subscribe The Channel Share This Video With Your Friends And Thanks For My Video
|
Max Increase to Keep City Skyline
|
custom-sort-string
|
There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at row `r` and column `c`.
A city's **skyline** is the outer contour formed by all the building when viewing the side of the city from a distance. The **skyline** from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of **any number of buildings by any amount** (the amount can be different per building). The height of a `0`\-height building can also be increased. However, increasing the height of a building should **not** affect the city's **skyline** from any cardinal direction.
Return _the **maximum total sum** that the height of the buildings can be increased by **without** changing the city's **skyline** from any cardinal direction_.
**Example 1:**
**Input:** grid = \[\[3,0,8,4\],\[2,4,5,7\],\[9,2,6,3\],\[0,3,1,0\]\]
**Output:** 35
**Explanation:** The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = \[ \[8, 4, 8, 7\],
\[7, 4, 7, 7\],
\[9, 4, 8, 7\],
\[3, 3, 3, 3\] \]
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\]
**Output:** 0
**Explanation:** Increasing the height of any building will result in the skyline changing.
**Constraints:**
* `n == grid.length`
* `n == grid[r].length`
* `2 <= n <= 50`
* `0 <= grid[r][c] <= 100`
| null |
Hash Table,String,Sorting
|
Medium
| null |
583 |
That Hey Guys Welcome And Welcome Back To My Channel Today Bhaiya Ko International Problem Barf Aur 1.5 Lite Video Please Like Share Subscribe Barf Aur 1.5 Lite Video Please Like Share Subscribe Barf Aur 1.5 Lite Video Please Like Share Subscribe My Channel Record Bhi Solve All Problems Dairy And I Don't Want You To Miss Any Problem So Also Hit The Bell Icon For Regular Notified When you for watching my video without any further delay charted and problems i.e. depression for charted and problems i.e. depression for charted and problems i.e. depression for two lions will appear after winning how to approach problem and how to draw so let's see who wins problem give two chances to return minimum number of the required to Make The World And Want To See Him I Want To See The Given Video To Make Them See And What We Can Do You Want A Week And Delete Exactly One Character From A Basic To Any Specific In One Traffic And Literature From Any One Thing Is Difficult To Lead character for testing and Vikram Digital character from Distic in one step Twitter Minimum number of steps so that they can make them equal OK for example scenes 130 posting ne my tablet a scene Dhruv Yadav a CAB it is a so normally to me to make them Equality and want to meet you in minimum phone number of tips on who invented what you can do delete me one character to when you will need one tractor dynamic content one step at the longest effect to make them equal ho neeraj me to make them equal to Make a I can just remove all the characters from distance between them equal I will remove all the characters from distance between them equal will also belcome equal MP board 10th time table par committee proof and MD Sudhir equal hai to jaise jaayenge but in 10th over time Doing this is deleted all the tractor rate is how many types let from jayram kar actors in restrictions and characters in the string to employers and will be the phone number of tips a the five to mark your dealings in character is sullivan step this one jar is worship 100 Owaisi distance between answers but this will not with the correct answer because they need to find the number of minimum volume maximum kar do hai what we can do elective one say is tried to think what food bhi made the way to behave See that and share it ok so what we can do this pick what we need to do we need to absolutely minimum number of world ft minimum number of me to play mini to remove minimum do a need to remove minimum character moral and just Remover character doesn't want to prevent minimal structured vishuddha remove minimal elements to be used only report so judgment idea not same 's note CM in both rings everyone does 's note CM in both rings everyone does 's note CM in both rings everyone does not same in both strings only on the result of this note SIM not frame for NDA is final and Right 102 is what we can do meanwhile can not simply disconnected not in the string and descriptive is not getting removed immediately friends remove s dip on the internet 2012 want a fix and after removal prohibit it and you will welcome a great you will Be Removed from Being a Giver 119 2 Here's an example of All It's a Physicist Liquid This Test's Pet So Insited of Language and Taking a Peached OK Aa Hai Love U I C E Want You Make A List of Tweets That Decided to Think What Servi and A Shop Approach Which Describe What You'll Find Out The Different Tractor But Don't Want Every Time OK Over Seat A Nerv System Hee's Inhibition Tight 3000 Love Tractor Rate Arrow Ideas President Both The Thing Rights What We Can Do From This Booty To Zoo Heel Something Like this ok aa that boat what you will do that border world will understand why can't you whole live video according to loot approach that you will see you give different subscribe need to make a what is that which co remove s what does medium Kiya hai ko increase murthi what will be amazed e aaj raat to then practice till suitable wicket rearrangement it can only remove the character of hai to approach with and tight will find out how many different tractors today every day that my number of tax will Be required to approach banks for correct wine because its status as you can see were and hear how they can 23 to your side second slice cigarette to attach healthy back nda back ok 180 a novel objects and died in want you can delete exactly one If character reminder setting is on then it is plate means let me have an available which aims at the starting index for watching and another level Vijay destination of the country is on then come Tubelight now you have done these rules juice one and consumer research a Love you might Indian boy removing cheese wife equal share not seen a aa jaaye not seen it on here jam palat se infrared AT&T AT&T AT&T servi is something get oo 220 to character both sim ki sim to will listen to remove the evil for every time You know which is placid in 1st edition is not equal to character of tours co tight Janodi world and Pooja's this is where they can remove the young director and they can remove the S2 character ok dad one step which can remove one character I Tujh Se Join Approach Rahi To Here What You Think They Were Believers Who Is Right Your Choice That With Use What Will You Recognize After The Meaning Will Pray Buddha Possibilities It Might Happen But Wicket Minimum Answer From Removing Enemy And Might Happen But Wicket Minimum Answer Minimum Number of Text File Movie Dushman OK Selection List Discuss The Rate Approach Vansh Electronic You Will Understand Approach Along With Sexual Holi Celebrate In Distress Class Ninth Of Bagassi Or Fear Being Updated On To Is Vansh Drinks A Riot Quotes OK A That And S Such Thing is a Positive Attitude's TCO So History Dance Problem and it's Longest A Common Subsequence Ho Renu Easily Label to Reduce Problem That Without Problem OK But Let's Not Know Weather Will Solve Address Using Reckon First To See Women Take Water Will Take Two Variables 2.1 A Subscribe Now To British I Sic Character Add Is Not Equal To Key Right Soviet To After Removal And Nifty Futures Remove That A Hai Tu But I Will Do Taking Removing Aircel Soft S One Will Become A S One Will Be Ashok Initially Rates And Doing In Acting To Initially Eyebrows 123 45678910 Dr. One To Three Lives In Szechuan Finish Hair Products And Fashionable Remove Jis Tractors Avengers Take Us Remove Initiated In The Time Being This Point Favorite Full Hd Movie Characters To What Will Be The Thing To Arrest Offspring Mill Bhi eid ko pcs pe modi ok and where not review nor do they not remove them shifting of burning sexually suggestive the i will be able to induce cases driving gaya hai mein ruke to i will be hi karna hai that and distic have removed his subjects Will meena true at all can only move on character add time right that marriage secondary river DCEO p how to step how many states this free mode on actor saif ban on and Xavier 19th a love english not have removed and him sell right but the Also have a choice to remove the c is none to remove bhi to is remove this key what will happen ab half minute mein aisa kuch hai but this city will regret remote 100 to 150 cd oy give WhatsApp Web wear look features a country on am So I care if you're over your seat now they will take up this is equal to the self I is equal to a positive a so improve or remove this right with the same time on power so that I will move forward at Vindhya Request I plus to z plus fight to remove dharam singh rajveer want to make things seem pure practice of all this and want to remove the to i will go for ayurveda history will b t c o d that in the country soil see you too Key Air Tight Share Bhi Aay Ki I Will Appear Hai Entry Bhi A Main Aapke Show Will Now They Are In I And Let Small Letter Shifted To Also Share Your Views And Not Equal To Remove It PCOD Instant Railway TC Only A 125 Remove This is the target digit code that and you will get the most from CO2 ok so and listen to garlic power a the latest notes12 how to here or two choices and because even the are not same phimosis that I will get PCOD hai to yeh meri movie english Right And Removing Dress That Itself Step Will Increase By One Two Medium Two Three Four One And You Will Remain S H O 110 Fremont CA Soft Will Get Key PCOD Will Remain S H And You Will Get 9 Votes Will Miss You Too Had Been In KNOWLEDGE IS POWER HOW TO HEAR NOT USI OVER A YEAR WHAT WILL HAPPEN TWENTY YEARS SIM WHO IS ZOOMED TO WILL NOT DO ANYTHING WILL JUST BEFORE BUT SHOULD NOT INCREASE VITAMIN A SPECIFIC *ONLY SPECIFIC *ONLY SPECIFIC *ONLY AND COD THAT NCO A LOOK ON WHO IS LOGIN SEE TO Here is an account of SIM right CM Chauhan will simply mood power The person who invested in it again Navdeep Singh will remove power duty and share this to will be removed Subscribe I am telling you and listen directly this will never regret Calamities Singh retired Professor One and S2 Victims MP It Means To Adi Extra Characters Twitter Not Enough To But In The Right Yogis This They Never Did The Country Comment It Means Delhi To Agra Extra More What Ever Is The Name Of The Actors Extra Characters Thoughts Not In The Thing Feedback Cigarette Twitter Account Of Destruction Written Records Vilaspur Images 200 Proper Acid To Certificate To Plus To 4 U Ki Including Surajmal Vihar And Co Minimum Number Of Steps A So This Is Only Sector Of The Year The You Can Just Made Khol Recorder Free The It Better Understand let's make for dushman hai to he ear c id 1st division or sim to free mode this will get that PCOS BB free and this will be BTC ho aisa handsfree mode system will get that PCOD and they will be two I To Gai C N Rao This thing that Iss Aam Edison Main Front ETC On This Meaning Dashrath Repetitive This sub problem is this play relative sub problem tomorrow morning and objectives of problems which can you want dynamic programming and you can use memorization meaning SIM Memorization hello how's music will start the results which will get for this is equal and which toe values and same result for when they are making which toe values and same result for when they are making which toe values and same result for when they are making districts of will not and sacrifice the way she is not taken during worship for such as pimpri 10th value which we Get From Here It's Morning Basically A Drawing Easy Traversing Bodhsingh S1 S2 I Rebuked Actors And Buddhist Rings Reply This Business Ignore Friends' Actors And This Business Ignore Friends' Actors And This Business Ignore Friends' Actors And Wished Them On Father Died Yesterday Plus Hai Otherwise Note Sim E Will Make Two Record Schools In Which Year In Movie Such In Another Which They Are Moving Such Software Removing Is Correct Ans If Implemented Free Movies Yes Character Gel Been Created A And Its Associates Understood Approach Sexual It Will Be More Clear Reviewed A Year In Yourself In Using Registrar To Write The Code And Want You have written som iodine ok sorry here's what they are doing don't see the second for pimples solution post to here's what they are doing we call ras helper function in which we are near english word 102 sharing and wasting r young generation from zero index 34 Yops Polled Sushil A Ki Naav Is Higher Of The Unit Is Rich Poor And Offspring One And Agri Students Pintu Meaning Of The Thing Is This Condition Means Tat One Of The Rings Is Vikram Equanimity Of Victims Will Return The Character Of The Present In This research for tat ok is booth and mp meaning drops samrat repo rate se tds deduction claim to have seen that som will return zero meaning the is not to remove any character sonu zero sex is us otherwise that much practice limitless will Americans give to fall In witch women will come very but engine oil money will be by-2 remove will be but engine oil money will be by-2 remove will be but engine oil money will be by-2 remove will be moving one tractor 841 responsibility wedding oneplus water minimum value will get from the chiffon vitamin e find minimum set so minimum of that i van also remove such file show I Will Implement Its Premise And Today Suggesting To Meet You Play Services And Side Equal Right The Amazing Force Software Day Colors Pe Ddp In Which River To River Side Change Which Vasan Singh Sudesh Us 1200 Taken To Tdp This Vector In Which Were Storing So Value Which We Get From Eyes A Is Cruel Value Is Note Initially Lower Part Wishes Is Note Blurry Awardee Calculated For The Wicket Storing Care Sea Water Being Tried To Inter Dps Vector Values 90 Tried To Inter Dps Vector Values 90 Tried To Inter Dps Vector Values 90 Quality Calculated Value Fry J Civil Judge Ship And Suggestions For Making Electric Battery For Readers To Memorize Them Will Assign Problem And Approach What Will Be The Time Complexity 12121 When Is The Size Of Is Vansh Penis Size Of A Stew That Bigg Boss Hi Dad 2012 * And That Bigg Boss Hi Dad 2012 * And That Bigg Boss Hi Dad 2012 * And Request For Read This Money Times The Record Date For Dividend Has hai ika badshah begum rapid kal nahi aa 2019 end space contact you also went well before getting a factor hai flash light of 234 problem was clearly vinod ko mishri when e don't want to high school please like and subscribe my channel selected thank you to
|
Delete Operation for Two Strings
|
delete-operation-for-two-strings
|
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_.
In one **step**, you can delete exactly one character in either string.
**Example 1:**
**Input:** word1 = "sea ", word2 = "eat "
**Output:** 2
**Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ".
**Example 2:**
**Input:** word1 = "leetcode ", word2 = "etco "
**Output:** 4
**Constraints:**
* `1 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of only lowercase English letters.
| null |
String,Dynamic Programming
|
Medium
|
72,712,1250
|
1,323 |
I am Hasan America. In this video, ricote always comes to me. 323. to their table. Wooden sword. Every participation from the baker Orhan. Sorry, living the condition of the table. Our Fridays, this is not genial before. Look, it's long, come, it's the last goddess, now it's the transition that emerged. Steel should fill it. Because from the channel, it should fill here. They have to have their tables, the condition is tears, our enemy. So, the number is one, the one who is the one who disappoints, but collect it at 6, I am at the bottom, Ortakent speed, this number, Uncle, it's over, holta Then, a teacher who comes to nine will throw a debt to Hasan, we have to sell to that number, our last fish is 9669, this is the number. which is over 69 the answer is a little bit in Ortakent, your last bird is ready, the medicine you need is on the pipe sofa bed, the last Hasan Kılıç Friday. This medicine was on the side, the diameter was on the side, it stands on the side, the doctor should carry it to the bow, because it is believed that every saturated plane is on the side, nine, that is, the elbow is different, let's have a mule with us. Did you prepare me this Dop You know the knife is on the side nine directed 9969 here Uu 9699 Ankara opera theater understanding that lorikami was outside as well as fish these tables rice flour meatballs Kemal pulling towards this document ticron String Elentra shoestring pain this crane gold nine lubricates and this strena If you remember by laying down Ortaca İntizar, sleep her with a canister, winged course, take her abundant name to me and protect it, I went to your table, I end like this discotheque, I hurt that you will give the number 9669. The merchant adjective is also the string of this Intizar, you can tell, let 's see, 's see, 's see, this vastarelin lepidolite has the sound of hazelnuts starting. Always I wish twice Metal one get a lot against this Kayseri electricity to separate 90 100 this rent a talented one without money from this method Culture is over every bit 69 is a lie the epiton we give and who meets One wheel tribore broccoli As a result liquid collects both golds I made us take it but it makes someone cry [ __ ] I made us take it but it makes someone cry [ __ ] I made us take it but it makes someone cry [ __ ] like sugar here for that The pes table has just finished, my money is not our rate, but it is bitter. You Özge throws it like this, it makes sense to me, you see here, both we bought but you are brass on the diameter side, after depositing it, I gave you as much as you can throw and this will be reduced to String, that is, once the last word came out today, there is no copy mold, you will make a cage mold. Korsakov of the map subscribe this technological can't see this meat We think Mete is alone or not The girl on the table no I'm upset she cheated when she left If this Thank you intor yuda burn like this Bursa from you I will leave the stove late stringreplace table comes out Or was I one Elif day Buca Sevgi moonlighting stand Ok, that tale, the song you passed, I forgot it here, it's leaking, is it ready for everyone, do you see? Because after that, what does Paçanga Toraman mean? How are you, they see, genetic johnston, it is not boiled, we need to pass it on to you, take it once you have the strength, it comes, in fact, be acrylic rız, your kidney, they are collecting the gold that eliminates the sprat on the side, it means we need to stone. After the sorority, every moment the number is over, God, you need to use Access. I joked with you that the revenge of this union is from the numbers. Foot Movement These we have from this today the free tip By the way it's like 9669 it's like Oh here you do it then 10g Company God is already very nice since the heart is fasting in a tone Present requiring etc. Pınar's Damla all that kiss Placenta etc. Is it to that? prayer image Ooh, for diagnostic purposes, thanks to this, you will get the collective 160 gold under 10 g blocks, the required speed remained free from the side of pregnancy and became 9669 360, that is, our fever, look at it, there is a method, suicide Division Dilan divided by 10g, our God, I understood the obvious answer that 966 smart, everything is over, this arakanli This is Halis Kenan, our stone, brand, this hobby, stunstreet, Principality, rare, desired region, my friend is coming. Throw these numbers that don't know this list, to make you angry, this is then we move away by adding it to the bodywork. Sedat, that girl, this Eminler, Cahide Turk, So Özge, 9 billion to this buckle, Android, nowadays, be like these, six Hundreds will hear it in the straight direction Troll nowadays If it's his, anyway they remind it coming 60 from Translate nine stop around here again think about the length of this 9669 moment as if we put it here so broadcast flow from here to clamp today Now to me this 600's 620 39 from Tolstoy 9969 direction right answer Give it to me ha I'm also a wrong move on this subject, I'm a whiny Google, I'm a new darling, you go to bed ashure for me until the ninth of this union and spread the stone of the society, look, I'll lay it on the knob of the 19th wave, come and carry it to the dog. The one is 13. I almost find it. Hello, it comes out to roast with 900. On top of it, there is a buckle on it. Brother peace today, think closely about the trends, Kucuroglu, do you think about this? We don't have scoliosis. You have to be a dynamite. You have to be a star boss. You have to collect the boss girl. tipped because we got used to it girl this 14 this tarmilus friend's blood is right to me in this place you 4 million 48300 dollars fast twice for him this gold bard we landed the cinema will approach so six selfishness Site stands think as you can see a taste came to the side the line in front of the school for this we are chopping the menu no I counted it back out, if it breaks, tormin is super These six second place I'll come to you this queue s3's Now you wake up again the crime is outside the rest The Crime of Terminator 3 What happened together as aşure? As if we join the Oscar and see you until the branch Your age We want our high school soup Yes this digitastic e reputation Let's finish every number of people, it's an Aries movement, search for it in all words. Op.Dr. Actually, the method is burned. Even Op.Dr. Actually, the method is burned. Even Op.Dr. Actually, the method is burned. Even if you are Varlıbaş, forgive this messages. Oh, make the number a biscuit cake, do n't do that. Because the girl is on the other side, Hodja, it's empty, we need Africa next to us. This list Oh, I like it there, it's empty to the quick list, don't run. Nur İnci and indik skean liked the answer for peace, I was getting rid of Namlı herbal tea titleless, I need a duck, it was very nice from 9669, like meter, we talk, see you on this internet in your body, what will you do with this series in Ramadan, well 9669 nobody I'm kidding, huh. See you bro, this ends here, when we put a mistake, a task or a road, but I continue 90 You don't have this friend yourself My flight from happiness technique first empty here call next to Egypt see production Bursa burkon we consume see this we are tired Hatice walking like our mother every fig walking Risk your side, foil your life, let's see. Let's see, I also have this code, think about it, we will stay here, its existence is flying for a long time, its own job, Fatma, you meet nice, what will we do now, look at these, this is nice, tinas, this image for me, we need our friend, now come on, let's see, Ender is still scratching the risk. We need to open a trade in this list, but did 69 generally Ergen take it? Prepare a supreme list, so it's flying, bye, see you later, we'll talk. Needed turkey turkey, every one of them, we need it for nothing. Because Batur, I have 10 liras. I don't have any friends to respond to it. We were blind to it. Planet List It's going to be long, I guess Yunus. These are the ones, you will go down each meter, not friends, come and think for a minute, I mean, Andreas secrets, the need for toilet, duty, Özge, download it's a leap year, but we will be on this road together, we need to carry the gold to the 36AS buckle, the dog is on our side table with ramp, the 99999 line. These are I can't walk around and work on the grill at home. I believe in the wedding. The region is this. I think it's good that I collected six. It's a little bit crumbled. Now it's Aries. If the empty air that doesn't turn off is a number. We went to Aura. It was bloody. Nine burned. The air conditioner is important. Become a king. Pınar. Being free, it's standing at the moment. Let me ask you this then. 99. 69 of your answers came out. I put this to be lies, and the tests are dinosaurs, but I told you about it, but we are testing it, I am there. Then it was very elegant that cleaned the air, I opened it. Then you click on the canary. Shame on me, it's a shame to stand in one place. this but it oh let's own it because the police and their numbers then it's this or their end even though it bothers their own teams
|
Maximum 69 Number
|
maximum-69-number
|
You are given a positive integer `num` consisting only of digits `6` and `9`.
Return _the maximum number you can get by changing **at most** one digit (_`6` _becomes_ `9`_, and_ `9` _becomes_ `6`_)_.
**Example 1:**
**Input:** num = 9669
**Output:** 9969
**Explanation:**
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
**Example 2:**
**Input:** num = 9996
**Output:** 9999
**Explanation:** Changing the last digit 6 to 9 results in the maximum number.
**Example 3:**
**Input:** num = 9999
**Output:** 9999
**Explanation:** It is better not to apply any change.
**Constraints:**
* `1 <= num <= 104`
* `num` consists of only `6` and `9` digits.
| null | null |
Easy
| null |
936 |
Same guys welcome to take good bye Nivedita and in this video we are going to solve stamping also sequence in such problems statement what have we got here we have two strings even champion target and in this problem statement the giver is that an initial string We have a camera whose length is equal to the lens of the target and it has all the tractors in it. Question market. What we have to do is to convert this app, we have to make it equal to the target and how can we do this by overwriting this tempering which is specific. We will overwrite the beginning of the index. What about returning it in the comment box? Okay, let's go through this briefly to understand what our problem is, then we will see how we can solve it. We have given two examples here. First we understand the problem, what is our problem exactly, we were given a stamp and given the target and it was said in 3 minutes that you have an initial sting S, its length is equal to the length of the job target. 12345 is five in September and all the tractors in it will have a time question mark. Okay, five question mark, what we have to do is convert it into this, how can we do this by overwriting it, then how will they do it, give it to us. If we keep it tight, then we start here, if we enter ABC, then these two questions are fine, then what do we do, pay special attention to IG and from here again, if we add ABC, then what will this convert back into, then where our First I started from zero and then the starting index comes here at 012, so the answer is yours. Please do 042. This is your answer. I hope you have understood what the problem is and how to solve this problem. In this, we have given a statement to convert the four ghee which is our initiative into this, but we will solve it, what will we do in it, we will do it with the target so that it will become easy for us to solve the problem, so let's see how we can solve the problem. What we can do is let's take the example of a BCA ladder, what we will do is convert it into our initial Singh here how much total is two to 414 667 so you have to convert this into four five six 7 to 2% in this you get this four five six 7 to 2% in this you get this four five six 7 to 2% in this you get this Now how will we do it, if we want this then what will we do? Subscribe to this ABC, then you will search first, now you will see this channel, after that you will see its link, then you will see these four, what is required, if not, then okay, moving ahead. Here, yes, it is this, so what will you do? Convert these four. Come and ask a question. If you convert all four of these, it is okay in the question mark. Now after that, we will see whether all our tanwar is done, is its total done? If it is not done, then I will do it again from the beginning. Okay, I will do it from the beginning. So here you will see the testing. It is not necessary but am I matching the letter. If the letter is equal to our question mark, still we can do it. Okay, so it is doing one match each but BBC is ours, no, there is a question mark here, question mark is a question mark, but we will do it here, question mark will be ours, if it remains like this, it will be ours, you can do yours, it will remain like this also 20 question marks If it comes from C-Ad also then we can do it, sorry, this is comes from C-Ad also then we can do it, sorry, this is comes from C-Ad also then we can do it, sorry, this is too much for us, I thought you can do it will remain like this too, money can be made even without it is possible, right, we can do it in all the ways here, okay, so this is what we We will convert this also, then cut it, this time we have converted it for you, we have made this superhit 415, we have saved our CA. Okay, so now it is that you first get the Nikah done at your place from here on Caravan that you have zero. Started from CO, do not shout loudly, do it on one, you have become a customer on your Jio, then where do you live, if I write here then 202, they have stones here, right, sorry, now here we can see one, here this is that This is our This is getting substring So this is our possible It can be our question mouth 80 instead of baby and this is matching Okay so you can convert this What will you do Here we will convert this also and this Now what will we do, we will convert it, okay, so look, now see this mail in this, today we can solve this in this way, now we have approached this item, I will tell you this from here, you might be thinking that first you have to see that Is it matching you, are you getting it, if it is getting it, then replace it, okay, so here we are going to create two functions for love, one will check its own, is it replaceable or not, do we overwrite it? Can do, can't do, if we can, then what we will do is convert this, add this, turn it into question mark, OK, so what we will do in this, see what we are going to do here, so what we will do here in one inside We will start in a chapter, matter type, our answer, then we will tow the answers in it. Okay, and here we are going to tell you what cigarette we are going to use, and what we are going to do here, index, which contact, starting index. We have already done it, have we replaced it, does it need to be done again, and if not, what will we do to take care of it, if we have a busy day, then keep in mind that from the beginning of this index, we have already replaced it. So what will we do for it? We will make an idli here. Okay, what will we do after that? Look, how will we know whether it has been replaced or not? What will we do for it? We will take a flag, we will meet ma'am in these directions. We will put fennel seeds in it will be fine, see, it will remain close to its own inch, okay, when it has become a little irreplaceable, then it will convert it into its own. We had come here in the room, when even this egg of now would not have been able to be replaced. This means that it will be impossible for you to get four get ups. In that condition, we have to make it 110. Okay - we have to make it 110. Okay - Now on the night of the monitor, we have to allow minus one or into something positive response. So, what will we do in this condition? Edit done here. If we do this then what can we do for this? To check this, we have kept a flag here that if all our resources have gone to replace, we can achieve our target here, if not, we must have come to know that if we cannot, then For that condition, we will keep false, it is okay, if it is after the fall, you can check that this flag is yours, this is not the philosophy, it could not be replaced anywhere or could not be replaced at any place. We will keep it in that condition when we got our platform, its nature is ok, what will we do, we will entertain, MP is coming, ok then we will do it, now look, the one coming from the approach route, we will do what I have told, we are going to do it here. That we can replace, then we will replace, okay, so what will you do here, instead, what will you do to quick this stringer, show it settings, so now where can you check, you can check these four. You can check these four. Okay, if you check after that, you will not get it. Start checking from here, will you get it or will you not get it? So how far do we have to go? Zero want to do till 2F3, right, so this is Apna, who will know what will be in Generalized, what is its size, what is Apna, what is phone, this is Amm Aalu, its size is this fold and what is Apna Target, its size is J7, what is its size, Apna Seven. Okay, so look at the difference between these two, how much is the serial, here we need to separate, I don't think till then we will check, so what will we do about the difference in the long loop, okay that's how far we can go, what will we do now Here we will do this joint, let me take it again, okay, I will use another color and take it from someone else, so here we take it, yes baby son A B C D, from today itself, it is okay that it is here, now what do we have to do here. To star life, to text. Okay, now we have Jhansi as our own. What will we do with it? We will check its results here. Yes, this is our equal, so you will do it till yours. You check these four as much as its length was in the cup. We have to keep checking till then this is a record, right, isn't this a must at all, no collar of this, will we open it, sacrifice, this is not our replaceable product, we ca n't replace it, okay, so now we will start from here, we will return okay If we do it with one, then now he is doing inches, get the match done, the brain is doing a bad match, please forgive me, please get the match done, if he is doing his own match, then what will we do in this condition, I will replace him here, it is good that we are in this condition. The entire match is being played a bit, Sibal is there, so what will we do now, we will replace him. Okay, I have already told you about the replacement. If you do it, then what will happen to you? Question Mark, OK, it is CA, now see. Here we will take an account barrier to check whether our entire replacement has been done or not. What will we do in this? How much letter has been changed so far? If he will do the account then how much is 12345. Is it only your intake? Is it not correct? It is not ours at all, so now how will we know whether we got access from this account or not, now the intake is only there, no, as per the amount in our account, ours has not been replaced, then what will we do, we will start from zero again along with one. What will we do, we will tweet the route, we will have supervision on our phone, we will kill it, okay I know, we have visited here, okay, after that we will chart from here again and in the answer, is our 160 replaceable, isn't it Vanshith starting index one, so the answer What will you do in me, you will do one inside, you will do it, after that what will you do again in half, why will you take four crores from the districts, because whatever is your account, reach it so that the masala is not done yet, okay, then if we start from 0, then we will definitely subscribe, so see. Here this figure is matching, BB is not matching but it is a question mark, that means depression can occur in such a situation, it is not matching with the stomach because of the fear of it, but it is a question mark, okay, bad in one match. But this question market means it can be our replaceable, okay so here we will do it in this condition, we will convert it into nutrition month, we will implement the account, okay, we have converted it into nutrition month, add which one are you with? Have mercy on zero and delete the mask, what will you do then forgive me, you will visit, ok 200, now you will see whether the account has become your servant or not, then you will chart it with Jio SIM, then whatever you market, you need to keep an eye on it. No, this one also does not need to be checked, but from here to two, we can see it, so we can see it here, okay, we can see it, so it has a question mark, one, it is not matching. But question wise we will see further also, the match is not lost but we will also see question market mange C will not match question mark, we will see further also this is Kunwarsi and it is not matching i.e. is Kunwarsi and it is not matching i.e. is Kunwarsi and it is not matching i.e. it is not replaceable, we will leave ours and will click on it now We will read further, okay, we will be free, we will go to the birth anniversary, so here he is matching, is n't he forgiving, okay, but after hitting the question, didn't this figure smile, but is this his question mark, is he talking like okay? Mask is not done, even if this necklace is what we will do, we will replace it, we will replace both of them and our account will be used by both the parties here. Okay, this service is done, now we do not need to check, we are converted. So there is one thing about flag, when we are done with everything, we will give Nala Kumar, okay, if we get our true then there is no need to return the ministry IS, okay, what will we do after that, what you are starting in the answer, right, where is that? But you will do it for the eunuchs, it has become a wrestler, it has been done, 1 was presented, then it was made in a public place, then you lit the light here, but what answer have you given, you have given the third one, whatever you saw, it is kept, we will do Pew research on it will be the default. We will do it, then we will grand it. Okay, now let's look at the code with the code, which we understand. We have to do the check as I told you. There were 100 rooms, so here we did the tide for an answer. In this, we will start, we will also size the tank. Inside this target's continue our and took a business tab plus 108. Now we are here in America, how long will we do this until our account and K are not equal, that is, the legs are not equal. Okay, and below we took black, call you why. I have told you that this is to check whether you can achieve your target, if you can do it, then you will do it after covering whatever has been started in the answer chapter. For after that we will see Visit Britain, we will already run our stance somewhere, why tighten the loop till the end, now I told you this, look at us, even through checking, the technique of obscenity is needed because after this your four size After this, if you do it now, you will get free chicken, there is no hurry, under this, you will take paycheck till the end, this is a visit, what if not, end can replace the seventh class, what if replace, can replace the seventh class, what if can replace, then we will replace it, okay. If you look here then what will we do here? Target brought for stamp. Index positive zone. You can paste the tax copy. If you are checking that then here what is it doing? What is the replaceable one doing? What is this to do? Amlera Pastimes Size and taking target size, okay, we have brought it again and what we will do is first check from Jio till evening, what is your stamp or not, four, see your charge, as late as the press time is, you have to see that, is this? This is okay for whether all the lions are here or not, so here you will check Gyan Crore, I plus position, is this not a question mark and this is not the result of the index of this stamp, so this is the condition. What will happen in this, we will understand that this replaceable is not ours, our better B is matching and also this question mark is not ours, if this is yours from Jio till the end, love, passion till the end, if this is happening anywhere. So I am in this condition, if I have to fill the tent, it is false, that chilli cannot be related, other wise and earned through it will do OK when Dhandhuka either we will give Silai Kumar here OK we will do it here After that the answer is what will we do Gas We will put the index inside here and yes, in the account, this account is not mentioned, if we have to replace it, then what will we do with the index which we can replace, here we will give it to that hand in this function with the target and here what we Will do the account recovery force OK so what we will do here is we took the shoulder of the size time, the size of the target and we will run a loop from Jio to the end and we will join here the target i plus position is there a question mark? Look, we already know about making changes, we have to take care of the accounts also, that is why we are doing this, what to do here, let us let those who have question marks, change those who are not there, in the society, we will keep doing plus account plus, okay. We will front it is taking its own globally, look here, the difference is not only its own and cloves, nor are we getting results, so it has to be like who will be the function, he is going to change it on the address, so we have this font of ours here. But you are stunting so that you can store this account here. Ok, so this account here, we will check whether the account has been opened or not, it will not be accepted by them, if it is done, then it will take us out of it, which is in the previous answer. You must have done Play Store, you will divide it, don't you do it here, you have to check that light also, not your pimples, yet Nitesh can't do pulse admin, will do front interior, ok now Raghu Pappu, you must have understood, why science?
|
Stamping The Sequence
|
rle-iterator
|
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`.
In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`.
* For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can:
* place `stamp` at index `0` of `s` to obtain `"abc?? "`,
* place `stamp` at index `1` of `s` to obtain `"?abc? "`, or
* place `stamp` at index `2` of `s` to obtain `"??abc "`.
Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`).
We want to convert `s` to `target` using **at most** `10 * target.length` turns.
Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array.
**Example 1:**
**Input:** stamp = "abc ", target = "ababc "
**Output:** \[0,2\]
**Explanation:** Initially s = "????? ".
- Place stamp at index 0 to get "abc?? ".
- Place stamp at index 2 to get "ababc ".
\[1,0,2\] would also be accepted as an answer, as well as some other answers.
**Example 2:**
**Input:** stamp = "abca ", target = "aabcaca "
**Output:** \[3,0,1\]
**Explanation:** Initially s = "??????? ".
- Place stamp at index 3 to get "???abca ".
- Place stamp at index 0 to get "abcabca ".
- Place stamp at index 1 to get "aabcaca ".
**Constraints:**
* `1 <= stamp.length <= target.length <= 1000`
* `stamp` and `target` consist of lowercase English letters.
| null |
Array,Design,Counting,Iterator
|
Medium
| null |
543 |
to look at a legal problem called diameter of binary trees so i haven't do any easy legal problems for a while now so i'm gonna do it now but basically depends really depends on your experience this question in my opinion is pretty easy but it might not be easy for um for other people but i think that in this video i really want to talk about what i learned from this question and you know how you can be able to solve any of those legal problems using this similar uh process right so basically the question is that we're given the root of the binder tree we want to return the length of the diameter of the tree right so in this case in the tree problem we want to figure out the diameter of the tree and diameter basically means the length the longest path between any nodes in the tree right and this does not means that we have to go past the root so i can give you a perfect example for example if i have a node right and in this case this is the root and you can see this i also have a bigger sub tree here right so you can see the longest parameter or sorry the diameter in this case is here right so in this case 1 two three four five right uh and then in this case if you don't have to go through the root in this case if i have a note here one two three four right that gives you a total uh the diameter of this path is four the diameter of this path in this case is six right or sorry in this case five right so in this case uh we just return five so we don't have to go past the root um and then you can also see the length of a path between two nodes is represented by the number of edges between them okay so basically you can see this line right here that's the edge okay so you can see we have an example here right so we have this uh binary tree and you can see that we're returning three because in this case you can see the diameter of this binary tree is basically one two and three right so in this case we have a diameter of three right it doesn't matter if you go from four to one three or five to one three we're just interested in returning the diameter of the binary tree okay so in this case uh we want to return that right and you can also see we also have another example like one two so if i have just one and two then in this case the only edge that we have is this right so in this case uh you can see it's pretty straightforward that we're just returning this one edge um and then you can see the constraints is that we are guaranteed to have you know at least one node in our binary search or a binary tree right and then the value in here pretty much doesn't really matter because we don't really use the value at all right we're basically interested in you know like the actual diameter right the diameter of the tree so in this case how can we be able to solve this problem well when you deal with problem like this i think it doesn't matter if it's tree or you know recurrent tree or you know uh dynamic programming or anything i think it's very important to you know think about how we can be able to break the problem down or maybe like just work start to work with the base case right so just like i mentioned before a couple videos ago you know if you want to build a dynamic table diamond dynamic programming table right db table you know you have to start with you know the base case so in this case what's the base case here so if i have just one node right because like i said again the constraints were guaranteed to have at least one node in our tree right so if i only have one node uh what's the diameter well in this case it's gonna be zero because there's no edge right so in this case we return zero uh but what if we have like this right it doesn't really matter what note what the value is so i'm just gonna put like a uh in this case empty right so basically nothing right so if i have this tree right here what's the uh you know what's the diameter of this one okay so we know that the height of this sub this tree is two or in this case uh in this case sorry uh yeah in this case the height of the sub tr or in this case the tree is basically two and then there's a and the edge between here and here is just one right so you can see uh if i want to know diameter i basically i need to know the height of the left subtree plus the diameter of the right subtree right or in this case sorry the height of the right subtree in this case the left subtree has a height of in this case just one and the right subtree has a height of one so one plus one is basically two right so if i go here it's basically two so i know that the diameter for this subtree is basically two okay so now let's work up a bigger example like this so if i want to know the diameter of this or this subtree um i know the height or the diameter of the left uh yeah sorry in this case the height of the left subtree right is basically just two right we have one we have two right and then the height of the right subtree is basically just one okay so if i don't want to know the diameter of this subtree or this tree then it's basically the height of the left subtree plus the height of right subtree right or in this case the max height right because in this case i could have also have like this right i can also have like another node right in this case i can also have another node and in this case for this subtree the height of this subtree where the max height of the subtree in this case sorry just the height of the sub this subtree is basically one two three right so basically three so we basically return back the height of this subtree is basically three right we wanna know the max height right in this case the longest uh the longest branch right so in this case we return the number of the edges right in this case basically it's two and we know that the right subtree has a height or in this case one edge right so to know the diameter basically it's two plus one which is basically three right okay but the thing is like i said earlier before like you know in this case we don't really have to go past the root there could be a situation where we've already found a uh you know the longer longest diameter right or the biggest diameter in the subtree so in this case what we had to do is that we have to go from bottom to up right we start from the bottom we calculated the diameter for the current subtree and then we can be able to use a you know in this case a variable to keep track of the longest or the maximum diameter that we have in our binary tree right so we do a dfs and then in this case you can see uh we're starting from the bottom so the base case is that if the left if this current node is basically a leaf node we're basically just going to return one right if you look at the code i've known the left i know that right is null right this is the leaf node uh we're basically just going to return one as the height right of this current node right and then you can see the left is zero the right is zero so basically there's no edges right there's no the diameter is basically zero so we back we return back to the root now so now we have no two right so no two we know the left is uh in this case is one and we also know the right is has a height or in this case only one edge so left plus right is two so we know that the diameter of the current subtree is basically two okay so in this case what we need to do is that we need to return the height or in this case yeah the height of this current subtree right so we know the left or the right so left and the right they both have one so basically it's just one plus one is two right so we return back to the root we know the left subtree has two edges right one and two right and then in this case the right subtree if you're following so no dot right is not null so we go down to this path so we know that node.right or in this so we know that node.right or in this so we know that node.right or in this case node3 has a leaf node right because node.left and a leaf node right because node.left and a leaf node right because node.left and node.right is not node.right is not node.right is not is basically null so in this case we're returning one back to the root because in this case this note has a one edge right which is this one right here so return back to the root right i'm just going to draw now basically we are having one we have two right so in this case this is two because we have two edges one and two and this is have one edge because this here is one so in this case to calculate a diameter of this subtree right is basically two plus one right so in this case it's basically three right we go we find out the height or the height of the left subtree plus the height of the right subtree will give us the diameter of this current sub tree right and in this case we're basically just returning the height of the current uh current subtree right but what really interested is that the height where the max diameter right which is what we're returning at the end so that's basically how we solve the problem is we're basically just going to return the max right which is basically the maximum diameter that we found throughout the binary tree so we can see if we submit the code you can see we have our success and you can see the time complexity for this one is big o of n and is number of notes that we have in our tree
|
Diameter of Binary Tree
|
diameter-of-binary-tree
|
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.
The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.
The **length** of a path between two nodes is represented by the number of edges between them.
**Example 1:**
**Input:** root = \[1,2,3,4,5\]
**Output:** 3
**Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\].
**Example 2:**
**Input:** root = \[1,2\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
1665
|
328 |
Loot Hello Friends Hindi Session Where Do We Need To Discuss About Another Simple List Co Problem And This Liquid You Will Be Given As In Link List Group Oil And Notes With Affordable Events Please Note The Group Must Be Done Not Index Not Be Not Valid For United State The First Noida Shoulder To Shoulder 1000 Give What Like This Point 1358 Notes To The Year Old Boy Did n't Go To The Phone Please Not The Return Of The Day Question Exam Bizarre Oil Relationship With Big Blow Of One Space Complexity A Big Way And Time Complexity One Is The Number Of Units Clear Solution Simple See The Question And Complex Don't Have To Take Subscribe Will Reach All Notes In To-Do List On Reach All Notes In To-Do List On Reach All Notes In To-Do List On Events Will Attack China List Play List This Point To Point Gautam Increase In 2012 Sapre Tree For Better Visualization a jhal ko a will take another point of all the events that which is point * Even no dear events that which is point * Even no dear events that which is point * Even no dear friends the events that point reminded constable in the traversal and will be used to attach even last not the list playlist and attractions in the first reaction Will Find Urs 9900 8.2 What Is This Thank You Urs 9900 8.2 What Is This Thank You Urs 9900 8.2 What Is This Thank You All Will Point And Not From Year To Year Notes Will Hear All Differences On That Boat And Differences Only Visit For Similar Operations And Even Not In The Same Direction Fuel Daughters Point To Point Start Hotspot On The mentioned links this broken similarly will appoint you will not rest even thought this day will provide a that these points here will perform same tips in a nation against heart disease point intuitive and don't see the rings broken and noticed in points next Friends let's get hair oil two and similar operations and even not to noida entry point hot research this channel in this with this link this video of and even no different appoint hair not hair tips updated one's fast traversing link less novel attached both link playlist Old Next Point 12.27 Start Point Videsh All Notes Group Together Followed 12.27 Start Point Videsh All Notes Group Together Followed 12.27 Start Point Videsh All Notes Group Together Followed But All In One Us Allergic To Avoid Fried Idli Class Family Members Which Not Only Next To Listen All Subscribe Not All Subscribe To Family Basic When Will The Giver And Null Are Null Let's Declare And End Variables Is And Point Is Don't Know Dear Friends That China Point Say Cannot Injuring Let Creative End Start Vegetable Friends The Events Start Point To Even No Dear Friends This Not Value Will Be Reminded Content Will Use This No Difference The Two Attach Both And Events which will give you a c and d were first change and update to next reference discussed and difference value were village and simple step will not as well as that 108 rumor look at both and end events behavior start no different from attachment to then finally return Have developed has been done with writing code later functionality also written a utility function call print place which prince delete under cancel also written in the same time this created link listen and making call to odd-even list link listen and making call to odd-even list link listen and making call to odd-even list wifi which are referenced and finally where Printed Heart English Fonts Jakhan Selection Be Modern And Runtime Error On That This Resort Introduction Respect For This Boat Lift Problem Like Thank You For Watching My Video And Subscribe To
|
Odd Even Linked List
|
odd-even-linked-list
|
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106`
| null |
Linked List
|
Medium
|
725
|
611 |
welcome to july's leeco challenge today's problem is valid triangle number given an integer array nums return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle here with two three four we're gonna output three because we have uh three combinations of two three four again to this two that is and also two three so what's the condition here that we'd have to figure out to see if a triangle is possible so imagine that we had three lines one with a length of two one with a length of three and one with a length of 5. now if we want to form a triangle here you can imagine let's just say we moved this middle line down to here all right and if we did that we can see that we wouldn't be able to form a triangle right so these two are a combination of two lines like there has to be some angle here for us to form a triangle right if we want to bend that in like this and form this triangle these can't be equal because if this third length here is smaller than this i plus j then a triangle isn't possible one of the conditions that we can see is this right here has to be greater in length than our largest line so that's kind of the basic formula um so a couple conditions here what this means is the i has to be less or equal to j and this has to be less than k and i the lengths of i plus j must be greater than k so with this condition here we can kind of start figuring out what is a valid triangle or not of course we can do the brute force method and find all combinations of three check to see if these conditions hold and just add to our output but that's going to be pretty inefficient one of the ways we could make this a little more efficient is to first sort it okay so if we had like this what we're going to do is first sort our array so this would become like that get rid of this for and what we're going to do is do a nested loop we're going to check every single uh k here okay so we start with the third element okay so this would be k and we have to do that because we need an i and j somewhere so at the very minimum i and j has to be right here right and we know that i and j are less than k or less or equal to k anyway um so now all we have to do is uh for every k we'll have a two pointer solution we'll point one you know right at this point at the very first index that's gonna be our i and have our second pointer here with the j right before the k here now if we see that i plus j is greater than k that means a triangle is possible and what that means is basically every i in between here say that we had like a bunch of twos like all those would count because we know those are all less than our three right so what we'd have to do is um add whatever j minus i is to our answer because all those combinations are going to be able to form a triangle after that we figured out what j is possible so then we just decrease our j pointer one to the left if we find that i plus j is not greater than k what we'll have to do is try to increase our i and we'll increase our i to see at um until the two pointers me in the middle like can we get to a point where i plus j is greater than k here so uh i hope i explained that okay let's start coding it and maybe it'll start to make sense first we're gonna sort our nums and that's gonna allow us not to have to check every single combination here then we're going to well let's get the length of nums we're going to check for every k right so k in range of 2 to n now we are going to have a two pointer here um we're going to have i and j so i is going to equal to the very beginning of our index and j is just going to be k minus 1. so while i is less than j what do we want to do we'll set our answer here our output so let's check to see if i plus j is greater than k so if nums i plus nums j is greater than nums k uh then we're going to add to our output the everything the entire length of this array so j minus i believe j minus i like that yes after that we know that this j would count everything inside so let's decrease our j and check to see the other ones as well otherwise we're going to just increase our i all the way up to the point that it's no longer less than j but we're not going to add anything here because we know if it's less than the length of k then this triangle isn't possible right so after that we just return our output so let's see if this works okay and accepted so time complexity is going to be let's see n log n here for the sort and here it's going to be uh n for every k as well as n for this two pointer solution so that's going to be n squared so in total it's going to be an n squared if you want to get real technical you can say n squared plus n log n but i don't think we use any extra space so that's nice all right well that's it thanks for watching my channel remember do not trust me i know nothing
|
Valid Triangle Number
|
valid-triangle-number
|
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_.
**Example 1:**
**Input:** nums = \[2,2,3,4\]
**Output:** 3
**Explanation:** Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
**Example 2:**
**Input:** nums = \[4,2,3,4\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
| null |
Array,Two Pointers,Binary Search,Greedy,Sorting
|
Medium
|
259
|
1,512 |
Work in this area Ajay Ko Ki A [ Ki A [ Ki A Hello Everyone and Welcome to New Video Hindi Video Bihar Going to Discuss Another Problem from Its Code Problem Is Problem 1512 Number of the Problem Statement Boys Subscribe and Good Player Our Pear Hum Apna 12351 This Vansh Now what we have to do is told in this what Sinha said on submit on which good if our oil add enjoyed and this is our index and number tide equal our if this will be our ghagra if we compare And he was appointed here and will not do this, so the average salary of both of them is 1000, this is the difference, whereas our element is possible 04023, which means our second appointed, and lastly, subscribe on Thursday, it is a simple problem to do brute force for you. See the approach, see the messenger color ad, for this we need our brute force every day, always subscribe our channel, first of all, we will run 2020 electronic from village to village, here we will subscribe till village and inside this Inside this, if our elements are at send here, what do we have to do in some cases, we will increase the answer name available, make it a big one, like this is our complete, both the accused and we will cut the if subscribed, what is this our Our time complexity will be soaked in the answer because for all to friend if we see that our speed will be reduced because here we have not created nor appointed commission on ourselves subscribe from where to where this is equal to zero six electronic names which If the length is there then the name will be Switzerland after that we will update you every time Tamarind we will make these which is this plus two plus 151 of our face that Julia Ann shot length that along with that the job characteristics bar will update this plus what do we have inside it What we have to do is if our name is typed as 'Hey Sorry' we have to do is if our name is typed as 'Hey Sorry' then what we have to do here is to increase the answer by one that Vikas and like ours will end and both of them we will return our answer then the return answer is a special submit for us. Let's do it and see click on Terrorism Aditya what comes our result has been corrected for one sexy input. Now let's submit it and see our result. The field is there and this has been our success which is from more than six people. We are using it less, let's turn off the mode and see its options. If we appoint more number of newly appointed nurses in it, what will we do? Will we make it at that time? Let's make it 1000 inches from the side, so we will make it 10 inches long. Now we will take like this subscribe our channel one two three 500 1000 2000 will be completed so now what will we do in this how many of us are there so now what will we do here now we will run a flop and people and whatever here The value will be big subscribe to it and keep doing this and we do this first of all we will take this side which is our glue subscribe result subscribe name set a big us on number type index meaning dip electronic and there also this thing Make it great and subscribe like we are in this, how the results are appointed, 12313, which is our tempered glass and our meaning, set 98100, all these are tampons, if I am pregnant, then what will it do, the result is equal to the result, this result will be the answer, no. There will be a pimple so here this is our ghagra again at one place tempo here 10 and along with that update its so then from the side appointed for us so now let's see for two so set the name To what is number 20123 means what we have to do is three if we do per 1230 then we will do this and before that before consuming we will add here so this is our to do appointed for how to tamper proof smudge of tree not sleeping 20123 Lutyens of Three Previous 181 Now see here we result and after that again this we click to subscribe if we loot means what do we have to do tempo sabsakraib Karen village like we do our Four-five this third then we will have to our Four-five this third then we will have to our Four-five this third then we will have to see the temple of Shri tempted pictures 1231 so in this we oven and so this is ours like we increase this by one to two cups final if we like subscribe our and subscribe our channel subscribe that What will be the time complexity if we look carefully? Time complexity will be our time waste. Omega will be this Vivo of and your Pan because if we look carefully it will be Vivo because this is ours. This is our paste of using ghee means use it while subscribing. So here we put the solution on top of ourselves, what do we have to do here, first of all we have to make this extra, let's make that if we want to make these temperate, then we will make it like this, let's make the tempo, we will make that size, we will make it Forest Act 2005 Subscribe that Now we are here, it is okay to loot, isn't it, eye lens, how long will it last, no, daughter, in, till, name, dot loop, here, we saw it, we will subscribe and inside this, we pimple a plus is equal to two results for digital plus what Have to set M of phone number? Is it like this is where our society will take, after that we will increase it by one, Temple Run President is appointed plus like it ends and what will we do, we need a simple solution for this, subscribe and this is our Subscribe If you subscribe and if you do regular practice then please subscribe to our channel John Hafte whose link is in the description thank you
|
Number of Good Pairs
|
design-underground-system
|
Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nums = \[1,1,1,1\]
**Output:** 6
**Explanation:** Each pair in the array are _good_.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
|
Hash Table,String,Design
|
Medium
|
2285
|
671 |
hello all welcome to netset os today in this video we'll be discussing lead code number 671 second minimum note in a binary tree here let's understand this question in terms of players let's say i have steams who are playing the games 5 4 2 three six one eight and seven now obviously if i need to take out the winner out of them these two will be having a match similarly these two will be having the match and the team winning out of these two will be going to next round and then next round and hence we'll be getting the winner here let's put a condition that a person who has the minimum will win here let's say the team who has the minimum number will win in this game so if we have a game between five and four wins similarly with two and three two wins six and one wins and between seven and eight seven wins as like this now if there is a game between four and two being the smaller one two wins similarly here among one and seven one wins as it is the minimum and between 1 and 2 1 wins now if you can relate this with binary tree here we have used min heap so as to calculate the winner team which is one here we have eight players right or eight teams out of this eight teams how many matches were conducted so as to get the winner one two three four five six seven that is seven matches so we can say if there are n teams n minus one matches will be conducted so as to get the winner now if i want after this winner the second winner if i remove this winner team i need to track where this one is coming in this binary tree that is i need to take out the existence of this winner team so as to get my second winner here i have to calculate second winner team so if i go down the lane this is the position from where it is originating and this was the game out of which one was the winner so what i'll do i'll update over here and we'll remove this one so if i don't have this one which will be the winner obviously six as there is just one player one team over here so i can simply write six now going one step before here we have six and seven which is the minimum six so here one will be updated to six now out of this two and six which is the minimum two so the second winner team will be two let's understand this with another example here i'll be having the numbers in a binary tree and i need to calculate second minimum number among these binary tree so for this lead code question i need not to build this binary tree i have just told you how it was built over there but 2 is the minimum number so what i'll do i'll track from where it was originating that is i need to take out the path so when i go down this is the location from where this 2 originates here the decision was made that 2 is winner among 2 and 9 so what i'll do i'll remove this so here there is just one number over here so instead of this 2 9 will get updated now we have 8 and 9 at this point of time when i need to make decision among 8 and 9 8 is the winner now when i need to make decision among 3 and 8 3 is the smallest so 3 will be the winner that is the thing which we need to perform over here so let's discuss the strategy for it how we need to do this so here first i need to track the path so for tracking the path i'll take this as root and here i'll calculate its left and right so for 2 left is 3 and right is 2 then i need to check whether this 2 is matching with this 2 or not from where it is coming so here this 2 is coming from right so now my root will become at this point where i'll take out both left and right left is 8 and right is 2. again i need to check this 2 is coming from which location from left or right here it is coming from right so the root will become this one now i need to calculate its left which is 2 and right 9 now here again i need to check this 2 is coming from which location either it will be coming from left or right this time from left so root will become basically it is recursing whichever value it is matching with it will recurse in that direction if it is matching with left it will recurse in the left if the value is matching in the right it will recurse in right now at this point root is 2 now if i check it's left i don't have any number in the left neither in left nor in right so i can write none over here perfect now my cursor is on this as it was recursed top to bottom now at this point i need to check if it's left and right are none it will return minus 1 so when it returns my cursor will go at this point so for this point root is 2 for which left is minus 1 this 2 will be updated to minus 1 and right will be as it is so here i got minus 1 and here i already have 9 now i'll make a condition if left is -1 you need to return if left is -1 you need to return if left is -1 you need to return simply the right value so here it will return 9 value to this point so right will be updated to 9 over here whereas left will be same 8 and rest will be the same if both values exist we need to just calculate min of both as we are calculating second minimum number so here out of 8 and 9 we got minimum number as 8 so when it returns from here it will get 8 in the right whereas in the left we already have 3 so minimum of three and eight will be three so we got the second minimum number three after two so this is the strategy now let's build a python program for this so as it is a binary tree question here we'll take node class for which we'll have data and we will take here data as input parameter left by default will take as none and write as none so let's start the program here first of all we'll make a condition if root is none it will return minus 1 and we'll be not having anything it will return minus 1 then and there and if it's left and right unknown it will return minus 1 rest left will have its value right will have its value let's understand this with this particular question we have root over here so first of all it's left will be having its value which is to write its value 5. here i need to calculate second minimum value as its value roots value is matching with left data so it will recurse in the left direction and this 2 will become root as it says recurs in the left direction now again it will check if root is none root we have two over here now it will check if it's root dot left and root dot right is none here we neither have its left not right so it will return from here minus one so left will be updated to minus 1 and the right we already have 5 so here we will get 5 as second minimum value now so as to handle this minus 1 and 5 we have made a condition over here if left not equal to minus 1 it will return left if right not equal to minus 1 it will return right so here right we have 5 whereas in the left we had minus 1 so it will update value to 5 over here and the other condition if we have the values other than minus 1 it will take out min off left and right so it was an easy program i'll give this program in the github link which will be in the description below so hope you understood this concept is related to tournamentary i'll make a separate video on donamentry later so stay tuned for my next video till then don't forget to like share and subscribe my channel bye thank you
|
Second Minimum Node In a Binary Tree
|
second-minimum-node-in-a-binary-tree
|
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly `two` or `zero` sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property `root.val = min(root.left.val, root.right.val)` always holds.
Given such a binary tree, you need to output the **second minimum** value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
**Example 1:**
**Input:** root = \[2,2,5,null,null,5,7\]
**Output:** 5
**Explanation:** The smallest value is 2, the second smallest value is 5.
**Example 2:**
**Input:** root = \[2,2,2\]
**Output:** -1
**Explanation:** The smallest value is 2, but there isn't any second smallest value.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 25]`.
* `1 <= Node.val <= 231 - 1`
* `root.val == min(root.left.val, root.right.val)` for each internal node of the tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
230
|
1,324 |
everyone so today we're going to go over a string based problem asked at Microsoft called print words vertically so the description says given a string s returned all the words vertically in the same order in which they appear in s words are returned as a list of strings complete with spaces when is necessary trailing spaces are not allowed each word would be put on only one column and not in one column there will be only one word so in this first example we're given a string s how are you and if we were to look at each word individually we can see if we look at each words first character would be H a and why that represents the very first string in our output and then if we look at the second character in each word o R and O the second word makes up Oh ro and then finally w e U and that's the last string in our output so we're printing out each column of characters for all of the words in our string s so to explain how to solve this problem I'm gonna go over to the white board and I'll go over some examples so in this first example we have a string s called to be or not to be and if you imagine we split this string by spaces we would be left with all of the individual words and it's pretty much represented in this format we can easily see what we need to return from our function we need to return each column specifically all of the characters in from top to bottom order for every column so we would return T be o n TB that would be column zero and then we have o e r o e that's the first column and then in the last column we would need to return a space and then a tea so space tea the reason why we're not accounting for these extra spaces here is because in the problem description if we go back we can see it says trailing spaces are not allowed so we pretty much do not want to take any spaces after our last index that has a character so the very last character in this column 2 is T so every everything after T will need to be removed so that's just an extra edge case we have to consider so the way we're going to solve this problem is we need to extract the word that has the maximum length so this word has as a length of 2 this word is the length of 3 2 and 2 right so our maximum length would be 3 in this case with the word knot and with this number we're going to iterate over every single word after we split our initial s string so if we were to split this we'd be left with and so we know that the maximum length is three so what we want to do is we're going to iterate from I we're starting at zero so I is going to start at zero and we're going to iterate up to three and this I number will tell us which index we have to extract from every word and we're going to do this specifically zero one and two times right because three is one based we're just doing it zero based because we're gonna be accessing the individual characters so with that in mind let's start I equal to 0 and this value is going to tell us which character we need to extract from all of these words so zero the zero index for each word so we're gonna look at t be o and t and b and so we're gonna be returning a list of strings so let's create a list down here and we are going to build this string TB o and TB right and then once we build that string we're going to increase I so I will now move up to one and we're gonna reset and now we're going to look at index one for all of these strings so we're gonna look at o R T U and E and so that means we return the string oh RT you eat and then once again we increase I so I is now two and then we reset but now we can see that this string 2 does not have an index of two because it only has two characters right so if we ever get in the scenario where I is greater than or equal to our word length what that means is we need to simply add a space instead of a character because if you look back in our example right here we still need to handle these spaces for this second column so if I is greater than or equal to w dot length we need to return just a simple space if this is not true then we return the actual character itself whatever that character is so now we're going to be looking at a space here right here we do have three characters so we're going to be looking at T a space here and then a space here so by the end of this iteration we will be left with the string space t space and so now all we need to do is strip these last spaces right because we don't want these any extra spaces after our last character but these spaces right here are fine it's just the very last two so we would finally just return once we strip the end space T so not too bad to understand how this problem works let's jump over to the code now and I'll show you guys how we can implement this okay so we need to return a list of strings representing the words that are printed vertically so let's just create a list of strings first and we can call it result and now we need to take our string s and we need to extract each individual word so we can say string array words and we're going to split by a space and now once we have all of these words we need to extract the maximum length specifically the word that has the maximum length so we can offload this to another helper function so we can say private int get max length and we're going to pass in our array of words so we can say in max we can just start it at 0 I'm gonna loop over each word and we can say max is equal to math max of Max or word dot length and then we just need to return max and so now we can have the max order length be equal to the function call of this and we're going to pass in our words and so now this is where the main part of the algorithm comes in we need to loop over from I up to max word length and for every iteration of that we're gonna loop over every single word in our ray of words and extract each interval individual index and build our string and put it in our result so we can say for and I 0 is less than max word length and in here we need to initialize some structure to keep track of the string we're building so we can use a string builder for this and after we do that we need to loop over all of our words so we can say for string word in words and this is where the logic will come in where we check if I is greater than or equal to our word length so if I is greater than or equal to our word length we need to add a space to our string builder if that's not the case we add the character itself so we can say if I is greater than or equal to we're not string dot append an individual space if that's not true then all we have to do is append word the character at the index I and then we still need to handle the logic where we trim the trailing space so let's offload this to another helper function we can say private string trim right and we're gonna pass in our word so I know that you could probably do this in newer versions of Java just using you know string dot trim right or something like that but I always like to assume that if I'm in an interview there they're not going to want me to use that so I think we have to implement this trim right on our own so to do that let's initialize what our starting index is the way we're going to do this is we're going to have a pointer starting at the very end of our word and we're going to loop to the left going pretty much going to zero and the first time we encounter a character that's not a space we just need to grab that substring and that will pretty much trim the right trailing space off so we can say int I is equal to word dot length and we're gonna say while I is greater than negative one we'll say if our word char at I if it's not equal to a space that means we need to return the substring up to that point so we'll say return word dot substring starting at index 0 up to I plus 1 because the end of substring is not inclusive so we have to make sure we increase that by one and then one more thing is we actually need to make sure we're decreasing I at every iteration because we're dot length is not zero based right so if we have our length of the word is six right we're gonna say while this will automatically decrement I down to five and so on and so forth and then we can just return null out of here this will always execute in this while loop so we don't have to worry about the function actually returning null and so now we just need to call this trim right on whatever we have generated in our string builder so we can say result dot add we'll call trim right on the string builder and then finally we'll just return our result so now let's just make sure this code works and there we go so next I'll go over the time and space complexity of our solution the time complexity of our solution is going to be M times n where m is the very maximum word length that we calculate in this get max length and then n will be the number of words that we have in our string because we're doing a nested for loop so for every iteration up to max word length we have to loop over every single word so that's why it's M times n and then our space complexity is going to be Big O of n where n is the number of words that we have in our string on line four we have to split our input string s by a space so we're going to be instantiating new memory when we do this s split so space complexity Big O of n so that's it for this video guys thank you so much for watching I'll see you guys in the next video
|
Print Words Vertically
|
where-will-the-ball-fall
|
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.
**Example 1:**
**Input:** s = "HOW ARE YOU "
**Output:** \[ "HAY ", "ORO ", "WEU "\]
**Explanation:** Each word is printed vertically.
"HAY "
"ORO "
"WEU "
**Example 2:**
**Input:** s = "TO BE OR NOT TO BE "
**Output:** \[ "TBONTB ", "OEROOE ", " T "\]
**Explanation:** Trailing spaces is not allowed.
"TBONTB "
"OEROOE "
" T "
**Example 3:**
**Input:** s = "CONTEST IS COMING "
**Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\]
**Constraints:**
* `1 <= s.length <= 200`
* `s` contains only upper case English letters.
* It's guaranteed that there is only one space between 2 words.
|
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
|
Array,Dynamic Programming,Depth-First Search,Matrix,Simulation
|
Medium
| null |
1,970 |
hi everyone in today challenge we are going to solve this problem the problem name is last day where you can still close and the problem number is one nine seven zero all right guys so as usual first of all we are going to clearly understand this problem statement after that we're gonna move to the logic part we are going to see how we can solve this problem what is the logic to solve this problem and after that we are going to move to the implementation part we are going to implement our low as you can see plus Java Python and JavaScript programming language fine guys now let's see what this problem is right so problem says there is one waste binary Matrix where zero represent land and one represent water you are given it is a row and column representing the number of rows and column in The Matrix respectively so guys first of all what we have been given we are given with row integer fine so this row and column tell us the uh how many rows we have in our Matrix I know how many columns we have pneumatics right so for example let's say rho is two and column is also two right so we are going to have a matrix like this I hope it makes sense right so this is going to Matic sphere we are not given with this Matrix we are going to create this mat is by this Row one column right now in this mat is always going to be I can say binary Matrix binary means either a cell can have zero or one right now if a cell have zero that means this is nothing but a land and if cell has one that means this is a water if entire Matrix is land that means entire cell in this Matrix is going to have a value zero simple thing right however each day a new cell become a flood with the water on each day we are gonna convert a one we can sell from zero to one right that means we are going to convert one land into a bottom you are given one base 2D array cell where cells of I is rho of Roi and C of I that means row and column represent that on either day the salon are A rho and C column will be covered with water that means chain to one simple thing guys now they told only here you can see they told in each day news had become flat with water right so this is the simple uh we can say line right how we are going to convert this into water we're given one 2D array here you can see in example one this cells array this is a 2d array right so on each index we're going to have a row and column right here one from one here two comma one comma two right so this is nothing but you can say row and column now this is going to tell on zero day we are going to convert this cell into a one on first day we are going to convert the cell into one on second day we have to convert this into one on third a we are going to convert this into one I hope it makes sense right so this is how we are going to convert right now you want to find the last date that is possible to work from the top to bottom by only working on land cell you can start from any cell in the top row and any cell in the bottom row you can only travel in four dimensional directions left right up and down now guys what is the main goal our main goal uh for us main code is nothing but we have to start from top right from top of any cell and we have to walk till the end right bottom of anything right Simple Thing guys we want to start from any of the uh we can see cell of we can say row 0 so this is row 0 right so we want to start from any of the cell from row 0 and we want to reach any of the cell of the row is equal to and we can say like last row right or vs row is equal to n minus 1 but if n is nothing but number of force right so we want to start from 2 and we want to reach at the bottom right that is the simple thing we want to do right now what we have to do we have to find the last day still we can reach 2 from top to bottom right now we have to find that particular Simple Thing written the last day where it is possible to back from top to bottom by only working online setup so now as you know that on each day we are going to convert one uh land to bottom so that means there will be some day where we could not even possible to start from the door and reach to the bottom right so we have to find the last day where we it is possible Right simple thing and we have to return that I hope it makes sense right now so let's see the example one and see how we can solve this right and I'm gonna take a less time over here just because I have to implement a four programming language that is also going to take some time right we have given this Matrix and now on first day we are going to convert this uh zero comma 0 into 1 right means this is going to be now become a water and see guys they have given one comma 1 that means this is one base index so we have to decrement uh by one for each particular romance right okay now so this is become um we can say whatever but still we can Traverse over this right so we are starting from this store and we can reach to the bottom line then they have converted this into also bottle but still we can Traverse this right we are starting from top and we are reaching at quota now they have converted this into a butter so now you can see we have no cell where we can start from the top right so we are going to return nothing but day two only so this is the day 0 this is day one then this network day two right so till day two we could able to um we can say Traverse from top to bottom right but on day three we could not able to do so we are going to say the result is nothing but date right so we have written two now for the second example you can see we have this Matrix so on day 0 we can Traverse from top to bottom that is definitely right on the day one we have changed this one comma one to zero that means the same so we can easily Traverse from uh top to bottom again so this is day one is also possible and now for day two we have uh change this from this Ln to from we can say land to water so now guys again there is no cell from uh from we can start right we have can only start from the topmost row so they all is water so we cannot starts we are going to return day one is the only one uh latest a day where we can start from the top and reach to the bottom so right so we are going to get another one on the example three if we see so guys here is example three it is three first three matrix it's fine and on the day Zero we can say we have nothing but right we can Traverse from top to bottom on day one they have made these two buttons so we can Traverse over this it's still opposable on day two they have make these two button we can still Traverse from this top to bottom on day three they have made this one because we can only move to four Direction up left and we come to this one we can't do this one density we cannot move animal right so there's no possible weak as a path from starting from top to bottom so we are going to return nothing but we can uh written three because on day three we can still pass from top to foreign understanding path so let's move to the next part that is the third logic part right so in the logic part what we are going to do we are going to understand how we can solve this problem by code right and what is the algorithm logic we are going to use it so what I'm going to do I'm going to write just a logic first of all think about this so if you will think a little bit so we have find out one thing right what is that is nothing but we can say if you could not able to pass here see guys if you could not able to pass on this day right here if you could be able to pass from top to bottom then that is definitely show that on the next of the day we could not able to pass it right let's say there's a let's say one two three four five six seven eight X there are eight days right that means they have given a sense of length of eight right so that means they are eight days and if we could not able to pass on the fifth day so can we pass on the next uh this six seven and eight no we cannot pass it right to land right so that means if a cell uh on a day we could not able to pass it if we could not able transform top to bottom that means that is sure that for the next uh all days you could not able to travel safe right so that means we can close it out now the question comes can we Traverse over this side right and we found that on three USB can Traverse it right so that means now we can say that fine on the left of this side we can easily Traverse it right if we can Traverse on three that means on the left side we can easily Traverse it I hope it makes sense right Simple Thing guys we are just checking a first of all mid thing we are seeing if we can Traverse on this mid part if we can Traverse it then move to the left side because left side uh move to the right side because left side is always going to be at gonna Traverse it so the answer is on the right side but if you could not Traverse it from on this day then move to the left side because right side will never gonna Traverse City okay so two conditions so I know it's gonna be a little confused if we can Traverse possible end if it is Towers then we can move to say move to the right side if node if yes if it is not right if it is node then we are going to move to the left side I hope it makes sense right so simple we are going to use a binary search on the date now that is clear now on each day how are you going to check whether it is Traverse it is we can Traverse on this day or not so for that we are going to use the breadth first BFS right so first of all we are going to create on each day let's say I was checking for this five so I'm going to create a matrix I'm going to create this damn uh this simple Demi Matrix and on this Matrix we are going to initiate find all zeros right after that we are going to say on until this day so let's say cell we have given this right so this cells is going to have a length of a so till 5 convert all this day to all the cell to one right so for one they have converted this one then this one two then this one three then this one four then this one five so we have uh fill all the sense value which are existed five index now because we haven't filled last we can say rest of the values because we are not checking on that is we are checking till five days so that means all the we are going to convert all the land to the water which is possible with this particular cells array and still if you're getting confusing so we can say you can see this example right so we have the cell setting one two and two right so we are checking for second day so let's say I want to check for second day here for second day so I have to go 0 1 2 1 3 till second index I have to fill all the values uh all the values and convert into what I write so for a second I have to convert is 0 To Us button I have to convert this zero cell also to one right I hope it makes sense so same thing I'm doing here for till five day I have to check then I have to convert all the zeros to one which are given in cell setting till 5 Index right so I know it's a little confusing don't worry we haven't seen implementation part but still here I'm just trying to make you familiar right but that is not necessary but the complementation but you can easily understand that right okay now what you can do we are going to use a PFS we are going to check if it is possible or not if it is possible return true right so now guys let's move to the implementation part and let's see how we can implement this one right so guys I'm gonna with first of all with the python so quickly what I'm going to do I'm going to say result which initially 0 that means it is going to increment by Minister but initially we have given 0 there on day 0 we can easily pass it right now we're going to say left side let me write here a length of cells so this is the range of over we can say why let me write a while and we can say left is less than equal to right is this okay now we are going to find a made which is uh that plus slide and divided by 2 right once we found a mid we are going to check it if it's possible if is possible for this particular medium then what you are going to do you are going to say move to the left is equal to mix plus one move to the right side and result is only else we are going to say light is equal to Mid minus one move to the left side right if it is not possible now let's define this function here the Phi is possible and here we are going to say take a milk and here what we are going to do we are going to Define first of all matrix by default Matrix is going to be about zero so velocity 0 into underscore in rain or flow right so we have to find by default Matrix with o lens now we are going to say for each for I in range of we can say this mean right fill all the lens to water which is possible till this particular day right so we can see Matrix of rho note row we can say uh cells of I minus I of 0 minus 1 right see that cells of I of zero in the model is the row on that particular zero day n minus 1 because this is one base indexing same thing cells of I one uh let me write one minus one same thing right now for this is converting we are converting for each we can say t till mid right so it starts from 0 until that way we are going to convert into one once this time we are going to use one more Loop before that we are going to find our Q because we are going to use a BF as so for that but we are going to say okay let's say collections dot DQ foreign left fine so once you took a data you're gonna check it and this is also going to be a row and column let's uh what it is happening fine uh so we are going to convert into a row and column so let's actually convert here now once we have this data we are going to see if this row not row we have already very low so let's say uh if this R is equal to rho minus 1 that means we reach to the end of this right so we are going to return directly uh two let's say we can say here fourth action we can write so we can see zero one zero minus 1 and 0 right so this is the four directions which we can move so we can say four a uh four right and we are going to say our new row is going to be nothing but rho plus this direction of I and new column is going to think about column plus this direction of five plus one now we're going to check if it is not so if no new row is less than zero or new column is less than zero or Nu 2 is greater than equal to rho or new column is greater than equal to column four one more thing if Matrix of that particular neuro and new column is one that means we can't move it right now these four conditions are just to check out of bound and this condition just a check to the uh this condition is just checking that whether that is uh land or water if it is one so we are going to say continue right but if it is not the case then we are gonna say so that means it is zero if it is 0 so we are going to first of all make this one that means we should not come to this again so make to one and then we are going to say a few Dot you don't append this particular new row and new column fine and after this while loop we are going to return first just because if it is true then it's always going to come in this condition always right but if it is not the case so it is going to come out from this Loop and we are going to return fast so let's try to run this code C and whether it's working final node all right so we haven't used a bracket so that is why this is giving a invalid index side okay and let's see now equal to W equal to we have to use that's what I was thinking because in Python we don't need to use a bracket right okay now fine it's giving somewhere else so that is also light is equal to what is this fine now let's say next we don't want to see any more error but still there is an error while left is less than equal to right spending is mistake I don't know the first I was I am trying to do the later I am happening right okay so like none is not very so fine we have done these things now just we are going to return this right so we are at here and now once we found this we are going to return our reason now let's run this code so let's see whether do we have any error so you guys can see that all the rest is passed Finance so let's try to somebody let's go so by this we are going to submit with a python line so let's see whether it's what if I don't know so guys here we go we have successfully submitted with python right wow we got in one badge as well 0 and then we are going to say in column node column left side is going to be always 1 and right side is always going to be uh cell script size right once this is why left is less than equal to right uh what you have to do you have to find a made intermediate is left plus right and divide by 1. is possible before this made and for that we have to pass this row column and cell as well if this is possible then we are going to return node item we are going to say result is going to be equal to Mid and we have to move to the right side left is but if it is not the case so we have to move to the lights uh left uh now we have to move to the left side so we can say right is equal to minus one after that we are going to return the given this result right and here we are going to find this function is possible right fine so here we are going to say first of all just create a matrix vector Vector again and here we're going to say enter and here we are going to say given name Matrix for row size and then in each you are going to create a vector and so in the column size and here by default value 0. once this is done we are going to say 4 into is equal to 0 I less than mid I plus and here you are going to convert all the lens to water till that day which is possible like so we are going to see Matrix of cells of IE of 0 minus 1 because this is one base indexing cells of I 1 minus 1 and is equal to 1 once you are done this thing you are going to define a q so Q is going to be pair of int n a and here you can say given mq and here you're going to say 4 into is equal to 0 what is this of 0 and I is equal to 0 that means this is still a land so in study number q dot push this particular 0 from I right well this queue is not empty that means we are going to Traverse it we are going to take uh before that we have to use the front that means we are taking the first element of Q then we are seeing that q24 to move that element as well numbers this is R2 none we are going to say fine we have done this thing so this is a pair right so we are going to say our move to the fourth action so Port action is going to be nothing but in direction is 0 1 0 minus 1 and 0 right now 4 into I is equal to 4 i 0 I less than four I plus and here we are going to say our new row is going to make data first which was the first row plus uh direction of I and new column is direction of I plus one this is gonna tell us the new rows right neuro and use now we have to check whether it is new row is less than zero Less Than Zero so if it is the case and one more thing guys if new row is greater than equal to rho and also new column is greater than equal to column and also last thing which in a different Matrix of new column is equal to one so we don't want to go into SL if it is Autobahn or it is the what right so we can say continue but if it is not the case so what we are going to do we are going to say first of all make Matrix of new row and new column is equal to one then you can say Q dot push this new row a new column and after that your bi say come out from these two and you are consideration fast but we haven't written two we have to return to here if data Dot if equal to rho minus 1 so you have to return directly to there fine now let's try to run this code and see by this we can find a node right so let's see do we have any error yes we are defining intervene okay now let's see okay do we have any more error here you can see guys all the risk is passed right so let's do submit this code as well so by this we are going to submit to the C plus minus as well so I was thinking to implement with this two programming language only but I think we can implement this JavaScript and Java as well in this video right fine so let's move to the next programming languages so in Java what we are going to do we are going to first of all Define earn we can see result which initially zero and then left which initially we can say one and then right which initially we can say stored uh length right now once this is environment is a while loop while left is less than equal to I we are going to say um left plus right divided by 2 fine and if uh is possible we have to use exposure if it is possible on that day on that mid so you can say find you to move to the right side so you can see left is one mid plus one else you're going to say move to the left side so right is going to left but midi minus one fine once this is okay now here what we are going to do we are going to signify this function so public this is going to be cooler data type and the function name is going to be nothing but we can say it's possible Right and here we're gonna say in uh and we have to pass this all things as well that's into row column and all these things we are going to copy this whole part fine so here what we are going to do first of all we are going to define a matrix rate so for this Matrix what we are going to do we are going to say okay let's define a matrix so here uh we can say into this Matrix side uh new and here not new Matrix is going to be new in this node and this column right fine how much this is done we are going to say port in I is equal to 0 I less than n root n we can say I less than mid I plus so we can see Matrix of this row we can say cell uh of I comma 0 minus 5x and cell of I comma 0 not 0 1 and minus one so what we are doing actually here we are just converting land to water till that is right so we are starting from 0 to the midst of our day we are going to taking all the uh we can say particular cell from the cells array and we are converting into a water right after this we are gonna make our Q so we can secure integer uh array and here we can save a q is going to new uh link this right uh we can see this particulars how many uh we have a particular column so we have a this particular column will tell us that how many uh we have a cell infrasto right so four in that is equal to zero I less than column I plus so now was this is done what we are going to get my check if Matrix of this I and this particular of this zero and this particular I just means open this cell is if it is 0 that means this is a what we can still add so instead in our Q so Q Dot this particular new in and we can say I comma zero fine not I commodity we have to use 0 comma right we don't want to do mistake in Java I really have a fear about this right so once this is file not equal to Q dot is empty right it is empty fine if it is not empty so take out the data so we can say uh take an integer array integer data is going to be nothing equal to Q Dot right once this we have taken technology fine you check if data dot zero is equal to rho minus one if it is equal to 1 then we are going to see return true fine we reached to the last row but if it is not equal to rho minus one though we are going to remove the four directions we can say is equal to direction is equal to new in and here we can see 0 1 0 minus 1 and 0 9. and we are going to move to the 4 into is equal to 0 I less than 4 I plus right and here we are going to check uh if we are going to move to the four directions so here we're going to calculate first one Euro which is going to be next of 0 plus direction of I and new column chart of one no data one data no zero is not it is we can see here like that of 0 right so we can say uh data 1 and plus Direction if our Matrix of neural Matrix of new row and new column is equal to 1 that means this is your water if it is the case then you can simply continue this right but if you denote the case so first of all let's make Matrix of new and new column is equal to one that's so that we cannot move to the this cell again so we are marking them in the other language right so we make this uh biscript now we are going to say Q node push foreign and here we can see new row a new one right once this is possible like if this condition is not we can say run that means we are going to come out this while loop we are going to return nothing but first let's say to let's go to see whether certain final node or do we have one here in Java so we got one error that is nothing but this Q dot removed so that is nothing more we can say what is Q right so Q is not present because we have used we have to use this move right fine now let's see if I just want to find out okay so you can see guys all the desk is passed right finally so we are going to try to submit this code as well so by this variable somebody with a Java as well right so now last is what you can say JavaScript right so give me a second fine and fine so it also got submitted let's move to the JavaScript programming language and here first of all with JavaScript first of all we are going to take some things that is less than equal to right foreign so what I'm going to say uh post is possible right and here it's going to be nothing but a function which is going to take a mid and here we are going to see nothing like this now we are going to Define one Matrix for that I just uh already seen somewhere because I don't have this obviously language but what we were doing we are saying that const Matrix just give me a second array of fill you have to fill uh give me a second array dot row right so we have to say it like this let me just confirm this okay and here we're going to say here array Dot column array of column dot fill 0 right so this network we are making a 2d matrix by default with a magnitude so this is just I don't know where our slime is because I am just learning this JavaScript but yeah I have seen this line from somewhere so I'm just using that here okay so now what we are going to do we are going to say fine uh we can say for let I is equal to 0 and here I less than we can say this middle and I plus right so for each we are going to convert uh land to water so we are going to say for Matrix of cell of this I minus I of 0 minus 1 and cell of I and one minus 1 and is equal to 1 right so we are converting length into water for this till this day after that we are going to say make a queue so for creating a queue so what we can do we can simply say post our let's say Q is still empty so we are going to say while node while we can use the first of all insert in our all the biggest land in our queue for the first row so for let is equal to zero that module l i plus and here what we are going to do we are going to say okay fine if this Matrix of this zero row and this I column is equal to 0 so we have to insert in our Cube so we can say Q dot push and you have to push nothing but this square bracket uh this particular 0 and we can say I suppose this is also done what we are going to do here comma from this group we are going to say while this Q dot length is greater than foreign and here we are going to say fine if this row is equal to rho minus one so you have to Simply return I hope it makes sense later you have done this here or three times right now what we are going to do we are going to say fine you have it is not equal to the last row keep traversing on the four Direction so you can say let's make a constitution is nothing but zero one zero minus one and zero right now here we are going to say 4 I uh I naught for let is equal to 0 I less than foreign new column is greater than equal to column last thing is nothing but if Matrix of neuro a new column is equal to 1 then we don't want to move it right if it is Auto one only it is a button right if it is not the case so first of all let's make Matrix of new and new column is equal to one then you are gonna uh let me use a simple column as well and here then we are going to say nothing but Q dot push this neural n equal right fine so we are going to say nothing written after this while loop fast if it is not the case so let's try to run this potency but just we have done any mistake or no okay so you guys can see that this is one mistake if is possible it's not fine so we have done something is possible we have used this thing fine now let's see what that's worth the final note okay so you guys can see that we are getting answer now zero Heights so that is what you can say it is 0 just because nothing but we are seeing that wizard is and if it is equal to this is fine and find this also working right if Q root length is greater than this so Q dot shift and you are going to say rho is equal to rho minus one you have to get to true and then inserting this all things into our queue find this your school so what we are doing is nothing but we are saying that if it is equal to greater than rho or this and fine right so we are making this a one and we are pushing into one hour to find that is also is fine and let's check it here right so we have going there cell of i 0 and i1 is also going to be one light that is a school life and that is also cool so of course this Q is also empty and if it is that equal to 0 that is also fine so it is fine so white is giving a zero so we can check the first line first of all we are using the same area flow dot field zero let me match this one put map and here we are using a DOT column dot field zero this is fine right so the issue is only here right now in this part so what we can do guys we can just uh do a try the left is going to be less bit plus one result is made so this is fine so what we can say okay we are getting a fast here right so these are suppose okay so now we have to develop this is one really tricky part so for let I is equal to zero less than polar I plus we are moving to first row and we're checking if this is zero so inside there also we are doing the same thing so we can see if this is giving 0 in every case so we have to find it right so let's see in this case 2 what we are getting a zero so on each case it is getting a 0 right so after this write this so we can say fine if this is the case so what we could do we could say here as well okay so we're making it one we are saying that on each direction we have traveled direction of five plus one no plus one hello so let's see whether it's looking fun or not we are coming in this conditions or not so if it is not working that means Q dot length is no okay so we are using a th type dng now let's see should work lies so you guys can see that all the desk is finally all the discus was passed with the JavaScript so let's get to summary for that let me recommend this is console part so guys I want to get submitted with JavaScript as well and we have already taken a lot of time right so you guys can see that finally also got some JavaScript programming language as well so we have successfully implemented with python C plus JavaScript and Java right and we have also seen the logic part we have also seen the problem understanding part if you have any kind of doubt any type of doubt in the these sections you can write in the comment section I'm always there to help you and if you learn something new this video don't forget to hit the like button and subscribe my channel meet in the next video
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
1,197 |
hi everyone with Kelvin here so let's discuss about beauty contest 9 second question we need more mic move so we are given infinite chessboard good coordinate from minus infinity to plus infinity and we have fun like X square 0 and then I have a possible Phegley to move as a standard chess role of naik and then we've been asked to return the minimum number of step needed to move a knife to square X comma Y so let's see here on the first example to move to X 2 y 1 we require 1 move like from here to here so it's one move ok and on the second example to move to coordinate 5 from 0 we move to two one move to for two back 2 3 4 and then move to 5 ok so the shortest path here is for step to do ok and notice the constraint here is the length of X the Delta X plus Delta Y is smaller than 300 so we can say like we can ignore the Infinity if the length is only this but of course we can exceed the back of 300 and then suddenly we go back like the common way we do a night move so yeah so how are we going to solve this question so basically if we're going to handle the range of 300 by performing at the DFS or BFS it will get a time off because the amount of navigation we need to do is too large so we definitely cannot done that by normal BFS instead what I'm going to do is we try to move closer to the goal point and then after that we perform BFS so how are we going to do that basically by doing a greedy so if X is X distance is larger than Y then we move more on X and move less on Y and otherwise if y distance is larger than X we move more on Y side and more flex on X I so in that way we can decide how we're going to move our horse they like itself so yeah the first part there as I explained like as long as we still far away from our goal like let's say X is larger than 6 and y is larger than 6 then we perform everything using a greedy method like to determine whether we're going to move how many X and how many y okay and we count it as a move okay and this part of the code basically you can ignore it because this is not going to happen but after that once we move closer we have the current X&Y and move closer we have the current X&Y and move closer we have the current X&Y and how many move we spend on the greedy method and after that we perform the BFS okay when we perform the BFS after the map of the pile itself and what how many is the cost the minimum cost to fix a current path and once we reach our coordinate then we can our current path cost plus initial move so initial move cost by the greedy method we add it there and then we return it so yeah that's it for this question like so the greedy move plus the move needed by checking the BFS okay because once we get close enough within a BFS the to determine how we going to approach to reach the goal like going back and going forward again something like that so yeah BFS can do that pretty well in close distance so we done spent a lot of memory yeah so thank you for watching see you on the next live on this
|
Minimum Knight Moves
|
parsing-a-boolean-expression
|
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists.
**Example 1:**
**Input:** x = 2, y = 1
**Output:** 1
**Explanation:** \[0, 0\] -> \[2, 1\]
**Example 2:**
**Input:** x = 5, y = 5
**Output:** 4
**Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\]
**Constraints:**
* `-300 <= x, y <= 300`
* `0 <= |x| + |y| <= 300`
"t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
|
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
|
String,Stack,Recursion
|
Hard
| null |
531 |
hey everybody this is Larry this is January 17th of the New Year 2023. I'm going to try to do a problem that I haven't done before so let's uh let's get to it uh oh there you go uh what I want to do I feel like yesterday I got it easy or something but I don't remember all right let's just uh let's just focus on a medium one and then uh you know and then I'll maybe get some early sleep and let's try to get when that is an SQL diet maybe you should do SQL but I don't think I want to focus on that on a video but yeah uh all right we finally got a premium question though so for today's premium uh Lobby problem is 531 lonely pixel one do they already know that they could have like a lot of lonely pixel problems like how do you know like you know it's like uh naming a movie before the trilogy is started like I don't know wait like how would you even know that you could have not only pixels how do you know they're gonna be successful uh maybe they just vote a bunch of these at the same time I don't know anyway that aside let me know your favorite uh movie trilogies uh who I'm talking about is but today's uh well I'm 5 31 uh it's lonely pixel sorry I like writing this out before but yeah so we have all time see picture black in my pictures we've done a number of black lonely Pixar a black lonely pixel is a beat that located is a specific position where the same Rose and column don't have any other doesn't have don't have anyway I don't have any other uh black pixels uh okay um that's not so bad I think you can probably do it in two passes right um yeah I mean I or maybe even well now you probably need to I don't know I'm not doing two passes though um yeah I mean I think it's just going through the for Loops right um and basically here at least for me I will try to um you know just have a rose as you go zero times R um and this is number of black pixels on this row right so then now we have four x in range of R for y and range of c um a picture of X Y is equal to Black then rows up X increment by one right and then now we go over each thing again right um how do I want to do it uh basically oh well if votes sub X is equal to one then what do we do if there's only one back pixel here then we look at the column I foreign and then here we go if COS of Y is equal to one but also a picture of x Y is equal to Black and then you know and we can actually optimize this point if you really want to meaning that um like instead of just having a column you could actually I mean I don't know you could do it a number of ways but instead of this you can have um like a list of at most two items or something I guess that's an option uh if you wanna talk about uh what you would call it a functional programming terms then you have an option right and what I mean by an option is that it could be just a Nuno or some way and then you know instead of looking for it you could just look it up but like uh wow sub X is equal to Y and then you just look it up or something like that maybe I'll do it that way fine okay is equal to Y right um and then the other one you can maybe just do account and then if those if length of this is equal to one then now I mean this is such a minor optimization I don't know why I'm doing it uh if this is equal to one and The Columns of row sub X oh this is actually I wrote this in a weird way because I this is uh it's not none foreign a black lonely pixel or whatever and I think that should be right basically it's just saying you know yeah give us a minute hopefully I didn't oh no hmm but did I mess this up why wouldn't this be true huh foreign oh I messed this up um in that uh okay my Optimist State I tried too much to optimize um because this overwrites the other one that doesn't mean that there's only one item right um I guess we have to that's a little bit I try to be too clever uh and that's what I say you know humbling but now I mean uh that's fine I they apply there are ways I can fix this but like basically add another flag but uh okay fine um something like this uh so otherwise then we have multiple of them then maybe we can just put as negative one or something right it doesn't really matter but that's just a silly mistake I probably could have just done the other thing as linear anyway right uh that's what I get for trying to kids don't prematurely optimize at home and you know maybe do later it doesn't even change the complexity and I made it worse by printing so uh still be 97 percent uh yeah let's try again we move to printing this time and sometimes slower I don't know technology how does it work but um yeah I mean either way it was going to be linear because it's the size of the input it's R times safe due to from here and there's no that is the lower bound right you have to look at every pixel it's just no way around it so it's linear time and uh sub linear space actually but yeah uh all of our pluses space instead of times c space kind of embarrassed I've been no I mean I'm not that embarrassed to be honest like it's okay to make mistakes um you know from time to time just like for me personally I feel like I've been making a lot of these kind of silly mistakes lately so I'm trying to but I'm also not practicing that much so I don't know it is what it is you know uh anyway that's what I have with this one let me know what you think stay good stay healthy to get mental health I'll see you later take care bye
|
Lonely Pixel I
|
lonely-pixel-i
|
Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels, return _the number of **black** lonely pixels_.
A black lonely pixel is a character `'B'` that located at a specific position where the same row and same column don't have **any other** black pixels.
**Example 1:**
**Input:** picture = \[\[ "W ", "W ", "B "\],\[ "W ", "B ", "W "\],\[ "B ", "W ", "W "\]\]
**Output:** 3
**Explanation:** All the three 'B's are black lonely pixels.
**Example 2:**
**Input:** picture = \[\[ "B ", "B ", "B "\],\[ "B ", "B ", "W "\],\[ "B ", "B ", "B "\]\]
**Output:** 0
**Constraints:**
* `m == picture.length`
* `n == picture[i].length`
* `1 <= m, n <= 500`
* `picture[i][j]` is `'W'` or `'B'`.
| null |
Array,Hash Table,Matrix
|
Medium
|
533
|
2 |
so hello everyone i am straight i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product based company so let's start with the problem in this session we'll study about this problem that is add to numbers it belongs to a medium category on lead code and it is the part of the ongoing lead code top interview question series that we are discussing so let's look at the problem statement so the problem statement is straight and simple we have been given two linked lists like this and we need to return the some link list of that so we need to output this linked list in our solution so these link lists are given to us so let's try to visualize it what is happening so the problem statement is very fair and simple it's like 2 4 and 3 is given and let's say 1 2 and 3 is the second linked list this will point to null and this is all this will also point to 9 so what will be the output it will be 3 6 3 9 so this is the fairly simple problem statement so what we can do is there are multiple ways of solving this problem but we look at a very intuitive approach that is using the dummy node concept so with the help of this dummy node concept we get rid of several boundary conditions cool so let's start what will we do so we'll just declare a dummy node let's say of value minus one and we will create the linked list by adding these two numbers these two nodes so in the first iteration what we'll add the value in the first node and the second so two plus one for the second node we'll add the next two values that is four and two for the third we'll add this and finally it's null so we'll return the linked list will become like this and we'll just return sorry this will be six we'll just return the next of dummy so this will be the our output we'll just finally return so we are doing it very fair and simple we are just making the linked list as per via it is required so what we will do if there is a carry so let's say it's one so we'll add the carry here as well and move our pointer towards the next node so let's try to code this and then you'll get a better understanding of what i'm trying to so let's go this one so first as i mentioned i'll declare a dummy node nummy node is equal to this node and also i'll declare a temp variable which points to this dummy temp is equal to dummy cool and we are having this carry we are looping over the statements and this is the carry yeah and we have a variable in sum is equal to zero for calculating the sum we just check for the existence that if this exists the sum is equal to l1 dot val and l1 is equal to l1 dot next similarly it will be for the second case this will be l2 yeah so we are completed with the iterations now uh our sum will be adding the value of carry if there is some carry and carry is equal to sum divided by 10 and then we are creating a list node next node asterisk node is equal to new list node that is some um mod 10 here and the temp of next is equal to will be equal to node because we are making the uh dummy node next point towards the nodes that node that we are made and temp is equal to temp off next yeah and finally as i discussed we'll just return dummy of text let's run this and this will be good to go yeah so it got accepted so we just we are just simply traversing and we are making that so the time complexity of this program so the time used will be uh big o of max of the length let's say mr ml or n and the space will also be the same because uh the link is that we are making will be equal to the size to one of them the maximum of both of them so that's it about this lecture hope you have understood kindly submit this code on lead code or it was also present in many other platforms like geeksforgeeks so you can submit on it on any one of them and thank you we'll meet you in the next question you
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
1,762 |
today we're going to be solving leak code problem 1762 buildings with an ocean view currently this problem is really popular with facebook amazon and microsoft so this is definitely one to know for your upcoming on-site interviews all right upcoming on-site interviews all right upcoming on-site interviews all right let's read the prompt and jump right in there are n buildings in a line you are given an integer array heights of size n that represents the height of the buildings in a line the ocean is to the right of the buildings a building has an ocean view if the building can see the ocean without obstructions formally a building has an ocean view if all the buildings to its right have a smaller height return a list of indices zero indexed of buildings that have an ocean view sorted in increasing order so for example if we were given this input of heights four two three one which we can see here in the diagram we would expect to return zero two and three because these are the buildings with an ocean height let's see how we might actually derive this well if we look at this building one here we see that it always will have an ocean view because it's right next to the ocean that's cool okay so we get to the three this one has an ocean view why because it's taller than all the buildings to its right so clearly this one has an ocean view so that means that this is an answer but now we get to this 2 obviously doesn't have an ocean view because its height is blocked by this 3. so that means that this 2 here does not have an ocean view and this four does have an ocean view because it can see over all the other buildings meaning it can see the ocean so that's our result and as we can see this matches up with what we expect because the indices corresponding to 4 3 and 1 is 0 2 and 3 which is what we expect out of the answer so conceptually the way that we want to solve this is actually we're going to start here at the right and we're going to track the largest height that we've seen so far and we'll initialize our initial max height to minus one and what we're going to do is we're going to iterate from left sorry from right to left and we're going to compute whether or not the current height is actually greater than the maximum that we've seen so far if it is that means that building has an ocean view and we can append it to our answer and since it's greater we're actually going to update our height so for example starting from the left we'd see okay is 1 greater than negative one yes it is that means our max height is now one and we would add that to our result array right cool then we're at this three and we see okay is three greater than our max height yes it is that means we have a new ocean view uh and then we can add this index apologies this should actually be three here because we're adding the indices not the values uh and then we're gonna add two here and then we're gonna move on so is two greater than our maximum which is three no it's not that means that this does not have an ocean view and we simply continue then we're gonna go to this four here and we're gonna see okay is four greater than the maximum we have so far yes it is so we can update our new maximum which is four and we can say okay what index does occur at zero and at this point we're actually done because our array is over and what we need to do now is actually just reverse this since we went from left to right we just need to go oh sorry we went from right to left so we need to reverse it so that our answers are left uh to right because you can see that the problem asks for sorted in increasing order so we want to make sure that we actually reverse it what we could do is actually use a deck here instead of a list to avoid reversing that but that's a little bit of a micro optimization um cool so let's actually put this into code and see what it would actually coded out and make sure that our solution is going to work the first thing that we're going to want to do is actually make sure that our heights array isn't empty if it is then there's nothing for us to process so we don't actually need to do anything so let's check that first we're going to say if not heights we're just going to return an empty list cool so now we actually need to do the processing so let's declare the variables that we're going to need for this if you remember from the drawings we were keeping track of the maximum height we've seen so far so let's declare that and initialize it to -1 declare that and initialize it to -1 declare that and initialize it to -1 and we need a container to basically store our result indices so let's say res equals collections dot deck um cool and the reason that i'm using a deck here is because we're pending each time and remember that at the end we had to reverse our array and using a deck i can actually append to the left of the array in constant time which will actually save me the need to reverse my array in the end so just you know a little bit of a micro optimization you don't have to do this i just like to cool so we need to go from right to left so let's set up that for loop 4i in range len heights minus one we're gonna say that the current height is going to be equal to heights of i and we're gonna say okay cool if the current height is greater than the max height that means that the current building that we're at has an ocean view so we need to append to our result so we're going to say res dot append left we're going to put the index in there because that's what the answer is looking for the indices and we're going to update our maximum height so maximum height is going to be equal to the current height and that's really it this is quite a simple problem all we need to do now is just return res so we'll go through our um array from right to left and we'll do this at every single step as we saw in the diagram and all we need to do now is actually just return the res so let's do that and verify that our solution works and it does excellent so now that we know that our solution works let's actually go over the time and space complexity here because this is an important part of any algorithms question so what is the time complexity well we know that we have to traverse every single element in our heights array uh and each time what we're going to do is we're going to do a constant time comparison against the max and potentially update the height here which is all just o of one operations so realistically our time complexity is going to be big o of n and space complexity well in the worst case every single building in our uh array is actually going to have an ocean view which means that we're going to have to store the index at every single height sorry of every single building in our result which means that it's going to be big o of n because in that case we would have to store everything so that's going to be our solution quite a simple problem relatively straightforward and i hope you enjoyed if you did please like comment subscribe and stay tuned for more videos
|
Buildings With an Ocean View
|
furthest-building-you-can-reach
|
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line.
The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height.
Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order.
**Example 1:**
**Input:** heights = \[4,2,3,1\]
**Output:** \[0,2,3\]
**Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
**Example 2:**
**Input:** heights = \[4,3,2,1\]
**Output:** \[0,1,2,3\]
**Explanation:** All the buildings have an ocean view.
**Example 3:**
**Input:** heights = \[1,3,2,4\]
**Output:** \[3\]
**Explanation:** Only building 3 has an ocean view.
**Constraints:**
* `1 <= heights.length <= 105`
* `1 <= heights[i] <= 109`
|
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
|
Array,Greedy,Heap (Priority Queue)
|
Medium
| null |
103 |
tension I am smile breathe inside you and the black and today you might Justin this with Steve significant sings a hope to find you open up your eyes blinded by the lies so you can see to dice Sidra sauna took a swing at a wrecking ball and I prayed for Maddow and thought a way to reconcile cos in my heart it's not worthwhile it's the bloody battlefield where sunk down on us here and it's all the same all you can do is play that again one day to wanna live but I've kids spitting at my feed and it forced me down a dead-end street forced me down a dead-end street forced me down a dead-end street when all I had went up in flames burning all the dark room names on my skin you know I don't like the person who want to play all I can do oh dude say goodbye refused to question my I'm decide to sing a sorry so light and pretend that you're okay where the chill you trying for one day wanna live a lie Cinco Foley's okay if I capsize my favorite with you hi with you
|
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
|
389 |
hello everyone so in this video let us talk about a easy problem from lead code the problem name is find the difference so you are given two string s and t string T is generated by random shuffling the string s and then adding one more letter at a random place now you just have to return the letter that was added uh to T now uh what you can understand is that if in general I can just really explain the problem that you have a string as resuppose the characters inside s then add one more extra character and then whatever the new string is formed that is called string D you just have to tell that from both s and t what is that after that is added got it now the thing is that because it is reshuffled like it is everything like the string P that is formally shuffled what you can actually do is that you can first sort out both the strings when you sort out both the strings they both come in the exact manner as they were eventually use okay now what can happen is that the first mismatch is the string character that was added additionally because if they were same every character will be same because they are sorted and they are in the same position only but if they're in the correct position and the sorted manner that it is good but if it is not in the current position in the sorted manner also which means that one of the character is added extra that is not in the correct position and that's the character I'm looking for that total logic that a second small example to understand all of that let us say that I have a string that is let's say ABCD so A B C D and then there's one more string that is a b c d e now what you can see is that I like both of them are sorted you can like if you have a nice thing you have to sort it out also then you can then sadly matching out this is matching this matching the last one that is left is e that is extra that is added let's say that you have string like this let's say if there's another example okay it is not so uh let's say that I have a string like this so a and the other uh string that is e c b D so what you can first do is that you have to first sort out the string so it is a b c d and again the other string is a b c d e and again you can at least match up this is matching this matching the one that is not matching is false but in this thing let's say there is such that this is having two B's okay let's say it has um one more B like this doctor sorting it will become like this so that is a b c d now you'll keep on matching a is matching with this B is matching with this now C is doesn't match with this which means that this character is externally added which is additionally added so this is bad just print it out that's over Logic for this particular problem so I'll move on to the code part now so what we have done is that we have to first sort out both of the strings and then keep track of the we have used two pointers okay one character moving along the S string and other on the T ring so it starts from zero now if both of the characters at I on the I like on the SS string and J on the T string if both of them are matching out then I'll just move my eye that is moving from this for Loop and J is moving uh additionally by this okay that is moving along the T string okay now but at any point if we do not match out then obviously the string or the other pointer that is pointing on a t string because on the T string only an additional character is added so the pointer that is J it should break out and whatever character J is on it is the additional character added that is added extra so T of J is the additional character that is added you just print out or just return on that part like that not too much fancy about this particular problem I hope you understand the logic and the good part for this particular problem as well if you still have any doubts you can mentioned on in the comment box of this particular problem thank you for watching your video till the end I will see you in the next one I'll give coding and bye
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
383 |
hi there in this video we'll be looking into a problem called Ransom note let's jump into the problem statement so given two strings Ransom note and magazine return true if Ransom note can be constructed by using the letters from magazine and false otherwise so each letter in magazine can only be used once in Ransom note okay so we are given two strings to us Ransom note and magazine we have to check whether Ransom node can be built using the letters available in magazine by using only each letter only once ok so that means if we take the example of this one so here we need two A's to build Ransom node are those two A's available in magazine yes okay and we cannot say if magazine is a b and Ransom note is a we cannot use the same letter twice to obtain Ransom node we can it should be that if it has two letters of a particular character then its magazine should also have same number of letters in it of the same characters such that we can obtain Ransom node if you see the other examples we have given a magazine like B but Ransom note is a so obviously we cannot construct so the output is false and in this example the one which we just discussed so this is also false and the constraint given to us is like the lens of Ransom note and magazine is greater than 1 or equal to 1 and less than 10 power 5 so we don't have to worry about strings which are empty or null foreign one more is a ransom note and magazine always consists lowercase English writer so we can leverage this because we it is given as a constraint to us like Ransom note and magazine will always have lower case let us in it let us try to come up with an algorithm to solve this problem so if we take the example given to us let's say this is uh this is the ransom node and magazine given to us is a and b okay can we construct R using M we can write because we use we need two letters we have two letters in Ransom node first letter is a which is a available in magazine as well so yes and second letter is also available so s let us say if the ransom note is AAC it has three so a is available good a is available again good C is it available in b no so for this we cannot construct from m okay that is the problem statement so if you see here one approach which comes to our mind is we can have a hash map maintained where when we uh so we can Traverse through this first then we can Traverse through this first we can maintain the counts of all the characters which we come across then do a comparison and you know obtain whether the number sorry the ransom node can be built from magazine or not but the thing is it requires three steps first step is we have to go through this then we have to go through this we have to build two hash Maps then we have to uh third step is we have to compare those two hash maps to obtain the result we have one more easier way by using a one-dimensional array by using a one-dimensional array by using a one-dimensional array so if we take an array something like account and the constraint given to us is this particular words these particular words have only lower case letters so we can have our array to be of 26 size because the number of lower case letters are 26 so each index in the array starting from 0 to 25 which is of size 26 each index defined a letter right till z so the approach we are going to take is simple what we do is it's simple so we have magazine is like uh what we have to use to obtain Ransom note right so first we will see what is available in magazine okay we will be going traversing through this magazine and we will be updating so in the case of aib so we will Traverse through this when we see a okay we will go and update index 0 to 1. again we see a we ah incremented to one more one which when it becomes two right B we increment it to it will be 0 initially so it will become 1. right now when we Traverse through Ransom note what we do is we go and check whether if this is available in this particular magazine the idea is we go and check whether there is an a which I can use from this index so here it says 2 that means magazine has to so you can use one so I can strike this off saying I can use one from here okay and get this particular letter okay now this will go off now it has only one as the count I take when I come here okay I go again here and see okay a is available to us so I will use it and it is constructed now there is nothing to construct in random node so Ransom node can be constructed using Magazine first suppose if there is a b for suppose so a so it this will be 1 and 2 right so a b now initially I go with a so I can consume one a then I go with second one I can consume one more then I go with a it says I don't have anything right that's when I will understand that Ransom note has something which is not available in magazine right when this count is becoming negative right so as on when I uh Traverse through this I'll remove decrement the count from the index and I'll base on the ASCII value of this particular character right ASCII value of this particular character now when I decremented then I am at this particular iteration I will go and decrement it to one when I am here I'll go and decrement it to 0. when I'm here if I go and check that the decrement is happening to minus 1 that's when we have to understand that Ransom note has in letters which the magazine does not have right if you do the comparison other way around the use case is not solved so if you first Traverse through Ransom node and increment the indexes here what happens is there might be like you might have Ransom note like this and magazine like this you will say that yeah so you will increment this to three now when you are going through magazine you will see that a it is available okay I am good but there is one more a which Ransom note has but magazine doesn't has so the comparison should be first we have to go through magazine then we have to come to Ransom note okay let's solve this so as I mentioned we will be taking an intera of size 26 because the constraint given to us we can have it as count itself the constraint given to us is both the words Ransom note and magazine has only lowercase English alphabets okay now first I will Traverse through care okay I can name it as letter right and first I have to go through magazine all right first I have to go through magazine two car array okay I am converting that to care array now I am incrementing the count okay off letter minus 97 is the ASCII value of a okay I have to uh because in our index okay 0 at index is uh a right so this letter this value will be 97 for a so when I do 97 minus 97 this goes into 0 10 x so for B it will be 98 so it will go to First index now I am incrementing it okay now I will iterate through cap I will iterate through magazine dot sorry this should be Ransom note dot to care array okay now when I am decrementing it if after decrementing okay if after decrementing if it is less than if after decrementing I have to decrement it first if I do this count letter minus 1 decrement then what happens because you have to understand postfix and prefix and postfix of plus or minus operator right so here when I do minus over here what happens the value returned is first it will return this then it will decrement we don't want that we want to decrement here it doesn't affect us because at the end when we come to this line that value would have been incremented but here in the if condition what happens is we need a decremented value for this we have to say that decrement the value give us then decrement it and give us here what happens is Inc uh give me the value then increment it here we are saying give me the value and increment it but here if you mention minus prayer decrement the value and give me okay so if this is Less Than Zero that means if it is less than 0 then there is a letter in Ransom node which is not present in magazine that's when we have to return false for otherwise if this is passed everything for every Ransom note letter there is a letter in magazine as well so it passes this for Loop that's when we return true let's run this okay the test cases are passed let's submit this okay it got submitted and the runtime is better than 99 percent and the memory it says is uh better than 68 percent I hope uh this problem makes sense to you uh thank you for watching let's meet in another video
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
1,351 |
Hello everyone welcome you are my channel from where you get to learn a lot of things ok the name of this question is count negative numbers in a sorted matrix question it is very simple ok Amazon asked this question let's read the statement of the question Let's see what six is saying, it is saying what six is saying, it is saying what six is saying, it is saying that it has given you an M cross, which is correct in sorted non-increasing, correct in sorted non-increasing, correct in sorted non-increasing, meaning non-increasing means that it must not be getting bigger, it must be decreasing meaning non-increasing means that it must not be getting bigger, it must be decreasing meaning non-increasing means that it must not be getting bigger, it must be decreasing or it must be equal. Meaning, let's go like this, there is no flood, there is a ghat, okay till now it is clear, the order is to be returned both by icon and pen vice, the most important thing is to return by the return number, in this it is told here that the vice and pen vice are also sorted and in which order. Let's see in non-increasing order, what is there to see in non-increasing order, what is there to see in non-increasing order, what is there to say, this is the input, you can clearly see by seeing that brother, I am not going to code Broad Force, you can also do that, no one can do it, what do you think about Broad Force? What has to be done is to traverse the entire grate. As soon as you get any negative number in Off M Cross N, keep adding it to the result. Whatever is correct will be your answer. So you can make the root force. Its time complexity is Off M Cross. Why? Because you will visit all the cells and see all the numbers which are negative. Okay, now let's see what I said. I will tell you three approaches. Firstly, there is the force, secondly, it is a bit optical. Okay, why is that the optical approach? Okay, my mother, I will tell you that too and how to solve it, I will also tell you, so let's see first, let us understand that this is the optical approach, that is, we have just seen the brutal one, we are going to apply cross n and make it a little more optimal. How to improve this solution? Look at this solution. I tell you again that whenever you know that any container or any list given is sorted, then binary search should come in your mind once. People, at least it is being solved or if not then some other solution will be seen but explore it once with Ionic Sir, see you have nothing to do, you are in this cry like a mother takes you, right now you have to find out only this. No, which is the first negative number, but take this example, if you take mother, then I have to tell you that brother, this is sorted in non-increasing order, you that brother, this is sorted in non-increasing order, you that brother, this is sorted in non-increasing order, so it can be decreasing or equal, okay, 01234 becomes zero -3 -2 01234 becomes zero -3 -2 01234 becomes zero -3 -2 5. - 5. - 5. - 3 - 4 - 5 3 - 4 - 5 3 - 4 - 5 So if I tell you brother, how many negative numbers are there, you know that it is in decreasing order, although it may be tomorrow too, it is in decreasing order but okay, so you know. How many negative numbers are there, then if I tell you that brother, first find the negative number, then all the numbers after that will also be negative, because it is in decreasing order, not decreasing order, non- is in decreasing order, not decreasing order, non- is in decreasing order, not decreasing order, non- increasing, what does it mean that brother, if there is a number then It can also be equal but after that the component will always decrease, increase or decrease, never decrease, it will always remain equal, okay, so if you get the first number which is negative, which is the first number which is negative, then after this all the numbers will be negative, okay friend. You know the total from how many numbers, the total here from how many numbers from six numbers, N = 6, the total from 6 six numbers, N = 6, the total from 6 six numbers, N = 6, the total from 6 numbers, but on which index did you get it, which negative number did you get first, 3 but if you do 6 months 3 then the remaining is this. There will be three elements, right? I mean, what did I do? These are the total six elements. You came to know that this is the first negative element, which is on the third index, so three will come, that is, from here, this and these three elements will be negative, so you must look further. Not only that, you have found the first element which is negative, the ones after that will be negative only - I did not go to 4, no, I found out from myself how many more negative elements are there, okay, so from this we have taken advantage of one thing that brother We will not have to visit all the cells, okay, but look at the example here, what will I do here, I will do binary search, here I am on the first row, where did I find the first negative number in binary, okay in the third index and how many elements are there in total? There are tax elements in this room. If there are tax elements in this room, then what is tax minus three? That means I got one element. Here I got one element which is negative. Okay, now let's come to this row. Okay, binary search is done. Found the first negative number. In which index was the first negative number found? 3 How many total elements are there on the index? 4 How many elements were found on the index? The first negative element was found on the third and next page. So, 4 - 3 1, that is, element was found on the third and next page. So, 4 - 3 1, that is, element was found on the third and next page. So, 4 - 3 1, that is, here also in ISRO only There is one negative element here. Come, look, pay attention. Here, we have found the negative element first. Where is the index number on you? Look, here is the index number. I will have two negative elements first. This is also correct. Look, one, two negatives here. Look here, okay here, where did you find zero first, how many total elements are there in ISRO? First do the negative charge, that is, there is a negative element in total, which is correct, also do one, two, three and add it, what else to do, five, six, eight, answer eight. Is it yours? Look, the answer is eight. Total eight is in negative. Okay, now it is clear that brother, it is very simple. First of all, we will just find out the index of the negative element and then we will subtract it from the total elements to get the total elements in Ra. How many are the number of columns, how many are the total elements, one, two, three, okay, so now the question comes, brother, find the first negative element, is it okay, then you think for yourself, it is okay in an already sorted array, either non-increasing or either non-increasing or either non-increasing or Non-decreasing or total increasing, Non-decreasing or total increasing, Non-decreasing or total increasing, then total decreasing means particular sorted, isn't it? By the way, if you want to find the negative element first, 3 4 1 0 - 1 - 2, then it is obvious, 3 4 1 0 - 1 - 2, then it is obvious, 3 4 1 0 - 1 - 2, then it is obvious, what is the first option? Write your own binary search. Ok you can write binary search butt style to find the negative element first. If you have problem then please let me know, I will share the code for you in the comment area. Ok write your own binary search. Take the second one, brother, close the upper, I will tell him how to do it, I will also tell him how to do C plus, and I will do the same and tell him, now this is a shortcut, we will make it from a kind of steel, okay, I will do that right now. Let me tell you how to do both. Look, Upper Bandh also does internal binary search, right? But if you write your own, the debt bill will leave a good impression, but your practice will be very good. It is better to write it yourself with binary sometime and if not, then Please let me know, I will mention it in the comment area. So now let's see how to write upper bound brother. For this, let us briefly understand what is the reduction of 'Apar' bomb. So see ' what is the reduction of 'Apar' bomb. So see ' what is the reduction of 'Apar' bomb. So see ' Apparpan'. Do you know what upper bound bill does? Find 'D' Apparpan'. Do you know what upper bound bill does? Find 'D' Apparpan'. Do you know what upper bound bill does? Find 'D' index of. D first value which is greater give your life input element what does it mean then attention dog give greater okay what does this mean if I want to write upper bound then let's take upper bound mother your you have a vector here is a vector Okay, so we need to find which element is just bigger than which element. Do you want an element just bigger than one? Okay, so what will you write? Mom, let's take it. Okay, you have written one. Okay, so tell me what will the element bigger than one do, which will be the first big element, but example mom. Let's take this vector in which the value is 1234. Okay, if you want to say, brother, take out the upper cover and show that one is one here, so what does it mean, just bigger than one, the index of the first biggest value. Told that who are you, see who is bigger than one, three is bigger than one, there is also four, but I am the first one, right, the one who has got church from one, that is this, then index, I will get one, but yes, but closed, what return does the painter give me? Returns but what do I have to do to get the index? This is also an address, this is also an address, if you mine both of them then the index will be found. Okay, so come on, it is understood that if you take mother If you were here, you would get just the number from here. Okay, so this is understood, but friend, it is the same thing for us, first we have to find the negative element. If we have to find the negative element first, then here we don't understand. It has been said that first of all I have to remove the big elements, how will they be removed, okay, so now pay attention to one thing first, what is this negative bag in bag, what does it zoom, that is, you have given it in increasing order, it is okay, but if you have to do it in decreasing order. If you want to get this function decreasing in non-increasing order, If you want to get this function decreasing in non-increasing order, then here you give one key, brother, tell it that it is non-increasing, meaning it that it is non-increasing, meaning it that it is non-increasing, meaning it is in decreasing order, so you will have to pass this one lambda operator. Okay, this is lambda. You will have to pass the function, okay and then you tell it that brother, you want a value just smaller than tu, okay or you want a value just smaller than one, but what do we have to find out, brother, first of all the negative element and which is the first negative element which is zero? Okay, you will go in the number line, after zero comes one, you come, but just before zero, which one is in the negative? Minus one, minus you, minus three. Who is the first negative -1, minus three. Who is the first negative -1, minus three. Who is the first negative -1, so what do we have to say, brother, 0. Just the first element which is smaller than zero will be negative. Okay, so look here. Now what will happen if it is not greater here? Dan is your life input element and the first element will be the smaller value. Okay, whatever it is not in increasing order. If it is ok in non increasing order then my function will be simple like this, what will be extracted from it, I will min it from this, I will get the index and as soon as I get the index, first of all what is the negative index, what I will do is simply min it from the number of pen. Let me remind you, I was telling you a little earlier that I was mining the index with the number of pens, I was getting to know how many elements it had, how simple it had become, okay, let's see the code, what will I do? I am going to each row, okay, first of all, the end of the row is okay, first of all, if it is negative, then you will have to tell greater and then okay and after that I will say that brother, if you want a smaller element just before zero, then it will be a negative element and First of all, I will get the index of negative from here but how to get the index, I have to min it from the beginning of the row, it is ok, I am processing all the rows one by one, ok then how many rows is the total, ok So, what will I do in the account here? Count plus is equal, you take total, first last, my answer must have been stored in the account. Remember N - IDFC, you were Remember N - IDFC, you were doing it here, you got the negative first by processing the first row. The index of the negative element is found first. What is three? What is the total number of forms? 4 months 3 is 1, that is, there is only one element which is negative first. Here there is only one element which is negative. Here also one. Element which is negative. Here is the first element whose index was what was tu tha to 4 - 2 did 2 a index was what was tu tha to 4 - 2 did 2 a index was what was tu tha to 4 - 2 did 2 a i.e. there are total two elements which are i.e. there are total two elements which are i.e. there are total two elements which are negative. Its time complexity is also very easy. We are looking at all the days one by one. Na, here the total number of pens is fine, so how much will it take to be M*1, how much will it take, where will M of people be, where has M gone, we have got butter, let us do both the codes and see, after that we will go to our best approach, it is okay and this too We will understand why the time of this best approach is plus N, this thing is important, it is less + N, this is important from the is important, it is less + N, this is important from the is important, it is less + N, this is important from the interview point of view. Okay, so let's code, so let's start its code. First of all, you know that bread force. How to make approach? Okay, we have taken out M and N. Inter result is equal, it is very simple. If I < 0, then return, sorry, look at the result. After that, return the result. Okay, it is too much because you are going to each and every cell. Okay, we were going on all the rows, so this is my first row, okay, so what I said, whose index will come out first, whose negative element will come out, okay, but off off, this road is increasing and what will happen to it from greater than It will find the small element first and if I want the first negative element to connect with which, then I write zero, just small from zero, it will be negative and it will find the band first, the negative band is fine and all I have to do is result. Plus this is equal, you already knew what I was doing, I mined the number of columns, if we had to find the index, what do we do, we mined, sorry, this is a bigo, gave andro, after that first we give the value with which to compare. What we are doing is that here we will give zero in the last and in the last we give lambda. Okay, so at the time of explanation, I must have given this first and written greater but what is the correct format of this that first you give the value or just what? You need just a value smaller than the value, okay, after that give the lambda in the bigger one. Okay, and when I was explaining this, I have mentioned in the pop up that first there will be zero, after that there will be >t. Okay, first there will be zero, after that there will be >t. Okay, first there will be zero, after that there will be >t. Okay, now run it. Let's see if you have passed by submitting. Let's see if you have passed. Test cases. Yes they have passed. Using this question and second approach, now let's go to its best i.e. optical approach which is an even go to its best i.e. optical approach which is an even go to its best i.e. optical approach which is an even better approach. Okay, so now let's go to our best approach i.e. O of M go to our best approach i.e. O of M go to our best approach i.e. O of M plus N approach and we will also understand why it is O of M plus N and its time complexity. First of all, let us understand what is the build theory and how will it come to mind. The approach is fine, so think about one thing, it is given in the question, it is sorted in non-increasing way, Row Vijay sorted in non-increasing way, Row Vijay sorted in non-increasing way, Row Vijay and Kalam Vice also means Row Vice, if you move ahead, you will get only a small value, you will not get a big value and Kalam Vice. If you go down, you will get a smaller value, you will not get a bigger value, okay, I am repeating here again, see, if you go to the right side from here, you will get a smaller one and from here you will also go down, and this story also applies from here to here. From here to here from here and so on everywhere okay so let's look at the piece of information how we can do it now pay attention here mother let's take you right now you are standing on this cell you started from here okay so see if If this value is positive then it is an obvious thing, if you go up then you will get a big value, if you don't get a small value, because what can I tell you, the value is decreasing from top to bottom, isn't it at the bottom? If you get a positive one from the top, then it is an obvious thing that you will get a big value. There is no use of living above, if you go higher you will get positive value, I want negative value, what does it mean that if you get this element positive then all the elements above will also be positive because if you go higher, the value is getting bigger. So why don't you just stop here and discard the entire pen. Okay, that means you came to know and you were on this pen. If you take a mother then you will know. There are no chances, so I will simply extend the pen to Kollam here. I have brought it till here, it is clear, now look, now I see that ok, this band is negative, so see, 100% guarantee, all the bands after this will also 100% guarantee, all the bands after this will also 100% guarantee, all the bands after this will also be negative, why because as I just said, it is non-increasing in decreasing order. Will keep on decreasing or else will keep on is non-increasing in decreasing order. Will keep on decreasing or else will keep on is non-increasing in decreasing order. Will keep on decreasing or else will keep on decreasing. If this is minus one then it is possible that there will be minus one in future. It will never get bigger. The value will keep on decreasing either. It will either happen or the incident will go on -2 -3 - 5 and incident will go on -2 -3 - 5 and incident will go on -2 -3 - 5 and so on, okay. So why are you trying to know further, you will know here only how many elements are there and how they are. Look now which index are you standing on three, sorry are you standing on one, which pen is one, isn't it, and what is the total? If you have a pen then if you do one for 4 months then you got 3, right, you got three, here you know that there are three elements in total, here are three elements, you saw here which is negative, okay now one. Pay attention to this thing, what does it mean that this row is over for you now, what will you do now, put the row on top, row mines, okay, row, mines, now pay attention to one thing, it is a very important point. You did not extend your pen because you came to know that these three are negative. If you have come to ISRO, then brother-in-law this is a no point, If you have come to ISRO, then brother-in-law this is a no point, If you have come to ISRO, then brother-in-law this is a no point, you should check this also because this pen has already been discarded, because right now my pen is here, so I When I go up to Ro, I will further check the floods with this pen because this pen was completely discarded. Okay, it is clear till here, so look, now I have come to ISRO, so I will check again on Ro and tomorrow. If the story is repeated then it is positive, then does it mean that there is no benefit of life on top, in this pen, there are total how many elements are there in the benefit of life on top, that is, there are total two elements which will be negative and look at the correct thing, only two elements. One and one two means we have taken out both of them at once. Okay, so we have got two more elements which are negative. What does it mean that ISRO's less has been exhausted, this one has Ro's less has been completely exhausted. If you have taken out the negative element, then we will mine the rows, this time okay, let's move ahead here. Okay, we saw that this is positive, so what is the benefit of life above? If we find more possibles above, then what will I do with the pen this time? I will make it bigger, simply ok, I made the pen bigger, the row is still pointing to this, I had discarded this pen, the pen came here, I saw that there is a negative band in this row and this pen, okay one, that is, one If there is a banda which is negative then it is okay by doing plus one. We have removed all the elements in this room. Now we have moved the row of the ghat up. Okay. There is one negative element here. Yes, how many elements are there in total on the third index? How many columns are there? If we say negative then where did we go, it is over, we have seen all the days and our answer was already eight. Okay, so whose property did we take advantage of? As soon as we get a positive number, I know that this pen will There is no less Jaan above this pen. You can discard the entire pen and you also know why you can disassemble it because it is in non-increasing because it is in non-increasing because it is in non-increasing order. If this is one then there will definitely be a bigger element above it then Jaan above. There is no benefit, okay, if it is negative, then the next one will also be negative because it is decreasing if you go ahead, okay, so let us see how simple the code of this is, what did I say, where am I starting from, I see, I started crying. I had started from here and my pen had started from here, is n't it? So my M is the last one and my pen was started from zero, it was okay, I started this much, now how long were you running? Remember, until every day. Is it greater, give equal, you were zero and we will use the pen only as long as it is, and what is ok, now remember what I said, as soon as I found such an element, cry comma, if you were zero yesterday, then I am not less than the whole pen, so the pen. Go ahead, make that whole pen bigger, I can discard it because I only care about negative numbers. Greater den equal tu, if the number is zero, then that whole pen is not worth less to me. Okay, and if greater den equal tu is not zero, then Sure boll will be < 0 and if li den is zero Sure boll will be < 0 and if li den is zero Sure boll will be < 0 and if li den is zero then what did I say that banda is on g index which index is banda on ma let's take that obse kal is standing on n - kal take that obse kal is standing on n - kal take that obse kal is standing on n - kal total number of columns is n and that is on kal He is standing right now and if I do this tomorrow, what will be the total number of negative elements? The place where he is standing is not only negative but we have also counted all the negative elements beyond it and remember in science we have counted them in this row. Now I have found all the negative elements of Ro, so now I can take Ro up, then I will have to do Ro mines, the condition was very easy, earlier it was clear that brother, if it is positive or garden equal, you are zero, then this is the complete pen. Discarded and if it is negative then I can find out the number of further elements in the row and that too from here itself and I moved the row to the top in one go and went to the top, ok till now it is clear and what do we have in the last We have to do return result, we have to do dates, it was so simple, okay, now we just have to see why its time complexity is M plus N. Can I break it down and write like this? Look at M plus, so I am trying to understand why this is Off is M plus, now we have to understand it with an example, so let's understand from this example why its time complexity is M plus N, where what is and what is my number of pen, you can write it like this also, now tell me one thing. I have given a small example, mother, let's say that this is five, this is four, this is three, there will be something above as well, right now I am not in India, he will come to know just from this, but you are right, you were starting from here in this approach. Okay, as soon as you saw that it is positive, the obvious thing to do is discard the entire pen. Dog, okay, someone has discarded the entire pen because this guy is positive, so the numbers above will also be bigger. If it is only positive then it is okay, then you have discarded this pen, then you have come here, you have seen that brother, this is also positive, so you have completely discarded it, okay, then now you have come here, you have completed this also because If it is positive, then see how many times in a year you had to try as many times as the number of pen, one, two, three, then O of pen times, you traveled only 3 times, you had to travel only 3 times, as many times as the pen, till here it is clear, now let's go like this mother. Let's assume that your example is something like this, okay here mother, let's take -5 -5 -5 and here minus four, here too there will be something, I have also not written it, understand this mother, you are late, you have seen that okay, this is negative, so the ones after this. All will also be negative because obesity is on the right side in the decreasing order and not in the non-increasing order, so the is on the right side in the decreasing order and not in the non-increasing order, so the is on the right side in the decreasing order and not in the non-increasing order, so the right side will also be either minus five or there will be values smaller than -5 which will be or there will be values smaller than -5 which will be or there will be values smaller than -5 which will be negative, as you came to know that it is negative. So what did you do, you removed the negative element of this row in one go and now you moved to the next row, so you did not have to travel the entire cell, you removed it from this, so you removed all this rock in one go. Similarly, here also you have seen that if it is negative, then you must have found out how many negative elements are there in one go. You have reduced the entire row in one go. Similarly, here also you have reduced the entire row in one go. You have done it in all the cells. You have not lost your life here. You have removed it directly from here. It is all right. So now see how many days you have put it. Rohi felt it is right and the whole pen. You travel only once, you can also write it like this - Ro + you can also write it like this - Ro + you can also write it like this - Ro + Kal or Off M + M which is mentioned, it is Kal or Off M + M which is mentioned, it is Kal or Off M + M which is mentioned, it is okay, I did not see the explanation in that much detail, but in the story, so I thought I will mention it in the video. Why is its time compressed of M plus N? I hope I am able to help you. Let's code it quickly and finish it. So let's solve it quickly with our best approach. We had already figured out M and N. What was told that Ra which rows will start from -1, the bottom rows will start from -1, the bottom rows will start from -1, the bottom row is from 1 and where will the pen be, the pen number will start from zero and there is my variable named Inter Result in which we will store the result, how long will it last till the roll is greater than equal to you. There should be zero and the pen should be < < < Till then, what I had said was that the first condition was as soon as I saw that the element of the current row and the current pen is equal to you, what does it mean that all the elements above it are also equal to this. Will grow up or will be equal because from top to bottom in non-increasing fashion, I don't have any shortage of pen, top to bottom in non-increasing fashion, I don't have any shortage of pen, top to bottom in non-increasing fashion, I don't have any shortage of pen, so I discarded the pen and made pen plus and if it is not so, that banda is negative then cry him. I can remove all the elements at once. Negative elements are the result plus it is equal to the total number of pen, how many mines are there in it and what is there in this that if the entire row's less is finished then row minus the mines, it is okay in the last. What to do, return the result, let's see after running it, quickly submit it, okay from 3rd April, do more binary search and see, even this has passed sir. Comment area video. Thank you.
|
Count Negative Numbers in a Sorted Matrix
|
replace-the-substring-for-balanced-string
|
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution?
|
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
|
String,Sliding Window
|
Medium
| null |
363 |
um hello so today we are going to do this problem which is uh part of august daily challenge max sum of rectangle no larger than k so basically the maximum of any sub rectangle in this in the rectangle that we get as input that is smaller or equal to k and we get the k value um and yeah it's guaranteed that there is a result um and so let's take a look at this example um so if we take a look here we want a sum that is the largest sum that is small or equal to two and this one would be three plus one four minus two is equal to two so yeah that's the largest one we can have um yeah because it's literally equal to k so we can't go past two and so we just return this um so that's the idea um let's see how we can solve it um yeah so the main idea for that we can use to solve this is to think about um how would you solve it in an array right how would you solve it in a just a simple array like maybe something like this um well definitely you will do maybe you will do the prefix sum let's say this is a larger than this maybe five seven nine so you'll do the prefix sum which means basically you will just add up so this becomes one minus two minus 1 2 7 14 and then if we put 9 23 i think or something like that so we'll get the prefix sum and then we can that way we can easily find the sum for the sub um sub array so for example for this sum uh not that one for this here it's easy to find the prefix it's easy to find the sum of that one uh instead of having to traverse the entire thing and add it up we can just take the boundaries um here and do subtract right so five plus three minus two that's eight minus two that's um six um and that's just seven minus one right so just subtract the boundaries that will give us the sum of the subsequence so we know that for a sub array the solution is to create a prefix sum and then just subtract so we can just scale that idea up to a matrix right and so we can calculate the prefix sum for the rows right so for the matrix um let's maybe take a larger one zero one two uh two minus one three one four five six two three one eight uh maybe nine okay it's going to be tricky if we try to do kind of the prefix sum for the sub rectangles but so we let's see how we can simplify it instead of doing that let's just do the prefix sum for the rows so that's the first idea prefix sum four rows which means basically this row is going to become the sum of this row plus this row and then this row here is going to be the sum of all three rows and then this row here is going to be the sum of all four rows right so that would mean basically we'll add this up so it would be so the first one stays as it is but for each i we will assign we will add up i minus one right except of course the first row because there is no i minus one right and so that would be three here minus one four three and then we do this we add up to the to this one so that will be three plus four seven um minus one plus five four three plus six nine and then one three and then you get the idea we'll fill this one as well um yeah let's actually just do it ten four plus one five 9 plus 8 17 and then 2 11 yeah um yeah so once we have the prefix sum now how do we how does this solve the problem remember the problem is max sum smaller than or equal to k so once we get this here we can just take each to find the prefix sum for uh for a sub matrix but here we have for the prefix sum the only way we have to start from zero row and at zero column and end at columns minus one this is the length of columns to find any from i 1 to i 2 so to find any sub rectangle sum that starts from 0 to column minus 1 we can just take this here and subtract from this here so if the matrix is large then to find the subrectangle starting at let's say row 2 and ending at row 5 then we can just take the sum in row 5 and subtract it from the sum of row 2 right so that will cover finding the solution for just the rectangles between rows but the problem is we might the sum the larger sum may be something here right if let's say this was positive and big uh and this was negative if this was minus 3 and this was 9 then maybe the prefix sum the largest rectangle would be this was smaller maybe two than the largest rectangle some may be the an inner rectangle and so the column is not zero to columns minus one so we need a way to handle that case and so to do that we can do a sub problem and solve that problem how do we solve that um well we do the same thing we accumulate the each row inside each row right so we do the same thing we did in the array here we do it for each row we do it for the row and then we binary search for the closest sum to k and that will give us the solution because once we do the prefix sum it's sorted right and so we just binary search for the prefix sum that will give us that is like um s minus um the limit k and s here would be just the all the prefix sums for the row right um you might say why are we binary searching for s minus k because the prefix sum it's p2 let's say sum here minus p1 that's the sum for the sub array and so s would be somewhere here and we are looking for an x that is we are looking for an s minus x so this is what we are looking for smaller than k because this would mean we have the prefix we have a subrectangle between s and x and we are binary searching for this x and so if we find this so to do instead we don't so we are looking for this x so we can just change this formula to be s minus k um so we can just change this formula to be s minus k and then just um smaller than or equal so here this means this is the same as s minus k smaller than or equal to x all right so we can just binary search for this and once we find it that means we found a prefix sum that is equal to the largest sum we want right um or not equal but closest right and then each time we do it for now the question becomes how do we iterate for each two rows and then check for the sub columns well the answer is easy so let's say we have 0 1 2 3 4 5 right let's just try all two pairs so we try this between 0 and 2 and then which we will get the we have the prefix sum to find the sub rectangle here some and then we just do the prefix sum for each sub column to check if any sub um sub rectangle here is the max so we try every pair zero two we try one three we try one four we try one six and in python that's easy we can just do combinations of length two and that way we get every two pairs right um and that's pretty much the idea so first do the prefix sum on the rows then pick every two combination of every two rows right get the prefix sum for the entire rectangle from 0 to columns minus 1 in between these two rows check if that's the max if it is assign it otherwise the max maybe in the sub matrices in between the columns so not 0 to columns minus 1. so to check that we do the prefix sum also for the columns inside these two rows and then binary search for the closest one to k return it and check if it's the max if it is assign it right and that's pretty much the idea so the main idea is prefix sum per row by row and then by column and then binary search for the closest 2k um cool so let's implement this and make sure it passes test cases um okay so let's write down the solution that we just saw in the overview so the first thing we need to do is um we need to do the prefix sum so prefix sum for rows so to do that we need to go for we need to have the first the size let's just make this m to make it easier to read and the rows number of rows and the number of columns um and then we do prefix sum for rows so we start for range of rows uh we need to start from one right because the first row the sum is just the same the values in the row and what we want is something like this to assign to add to the current row the previous row values so to do that we just need all the columns right so range of columns here and what we need to do is just do this for every column j and so this would give us the prefix sum for rows um one thing we want to do just to be able to have uh to consider the prefix sum of just the first row um we want to add zeros so we want to be able to add a set of zeros for as many columns as we have so that basically let's say if the first row in the matrix maybe it has 9 12 13 uh like just big numbers and the rest of the matrix is all negative so the pref the largest sum would be actually the first row so to be able to consider that because we'll take a pairs of all the rows uh we don't want to take one and one um we want to take different values right and so we will append 0 just so that we can start from this one so this would be a sub matrix with two different rows right so to do that we'll just have the matrix will append a list of zeros a row of just zero values right because that won't impact the sum right so this in range of columns this would be the new m plus m um and then we want to go through every take every combination of two rows um and basically we want to and then we want to check every sub matrix in that range of in between these two rows right and so to do that we'll take its two rows r1 and r2 and then we'll do the combinations uh for the range of length of m um so this would be just the rows range of rows and we want to do every two pairs so this is how um combination function works we need to give it the range of the numbers and then how many combinations we want we just want to and now remember in an array to get the prefix sum it's just the value at it would be at r2 minus the value at r1 right so that's what we want and so to do that we just go for the zip of the two rows right so that would be r1 l2 um and this will give us all the sums the combinations of all the sums in the two rows right so that we consider all the sub uh all the sub let's say this is zero to four so that we can consider all the sub ones and so here the row would be equal to let's initialize our row every time we'll just append s2 minus s1 the larger one minus the smaller one um so now that we have our row we can actually write this slightly better so this would be s2 minus s1 and then for both are equal to this okay so now we need to do it for the sub columns um and so to do that let's just say column range sum like that and we want to give it the row that we are going to look at and we want to give it so this is basically gives us the values in between for that row right because um similar to an array it's just this minus this gives us the that gives us that um subrectangle right and so here we want to we get a sum here let's call it s and we want to check if that's the best we have so far and the best we need to define it let's say it's just um we'll start with the smallest possible number just so that yeah so that any value find is better and we want to return the best so far we find and now we need to define this function where we said we need to do the prefix sum for the row and then uh binary search for the answer and so we need um we have an array and we need let's call it limit instead of uh instead of k um and so to be able to binary search we need a sorted list right so let's just have a sorted list let's start from zero again just similar to what we did here just in case the first value in the row is the largest maybe this can happen if we have a row that is like um 9 and then minus maybe one minus two the rest is all negative right so the first one is the answer so we wanna but we wanna add zero just so that we can take care of that um okay so now we go through the prefix sum so to create the prefix sum for an array you can do it like with a for loop where you go through every i and j index and just every i index and just say prefix of i is equal to prefix of i plus prefix of i minus one but in python there is an easier way to do it which is using accumulate um and so we'll just use that and so we'll do this is in error tools by the way uh library um and so this will give us the prefix sum so actually let's just call this uh prefix sum and then we'll do like that um and then we need to binary search we'll use python's bisect left instead of writing our own we want a binary search for this prefix sum minus the limit which we said that's that will give us the x value that we are looking at and the x would be just the other prefix sum that we need to consider and that way to get the sum we'll just do uh s minus that value right so this would be let's say we have a maybe a prefix somewhere there is an x here and there is a an s here and this sum in between the two needs to be small or equal to limit and so if we binary search for s minus limit and find this x value um we know that the sum itself is just uh s minus x right so the sum here is just s minus x and this is what we are looking for s minus x and so this would give us the index we are looking for so it's called i um and if i is smaller than the length of the row that means we have a valid solution if it's bigger that means we don't have a valid solution so we don't want to do anything um and then we want to return the max of this row right so let's call it row range sum actually um so best in row let's call it um and let's call it base best here um and so for the best here what we want to do is max we want to initialize it to some smaller values so that we can get um so we do minus infinity um and then here we want to get the best is the max of best and the sum remember it's minus x and x here is just the value in list at position i right and so this would mean here we need to say s minus uh let's call this x just so that it's super clear uh minus x and that will give us the sum between the two all right so x is the sum all the way to the left up to this point and s is all the way to the left up to this point and so the sum of the subrectangle is just s minus x um and once we so we have this prefix sum we want to add it to the sorted list so that we can binary search for it next so we append uh or actually add for sorted list and so we add um let's add uh s right that's the prefix sum we find um and then at the end we return um the best we've found so far and that's what we return here and we check if it's the best overall um and that's pretty much it so let's run this i hope this part was clear um yeah just write it down and try to see the different rectangles and should be clear there so we need to import a couple of things so we need to from sorted containers you can of course like is if you don't want to use sorted list you can put all the prefix sums in an array right and then sort that they are origin arrays so you can sort them if you want um and so here we want to say in sorted list and we want to import from error tools we want to import accumulate that will create the prefix sum for us so if we run this import not in okay submit um yeah so the problem here is we don't want to check the length of a right we want to check the length of the list we are looking at so that should be list here um yeah so another problem we have here is that i was using rows here but because we added a new row so the length is no longer this rows here right so we need to use a length of m so let's actually use that everywhere so that we don't confuse ourselves um and this would be a length of m0 so let's try this again okay so that passes let's submit so that passes um yeah so the idea prefix sum for the rows then prefix some for the columns and binary search for the answer um yeah so that's pretty much it for this problem please like and subscribe thanks for watching and see you on the next one bye
|
Max Sum of Rectangle No Larger Than K
|
max-sum-of-rectangle-no-larger-than-k
|
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.
It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.
**Example 1:**
**Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2
**Output:** 2
**Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2).
**Example 2:**
**Input:** matrix = \[\[2,2,-1\]\], k = 3
**Output:** 3
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-100 <= matrix[i][j] <= 100`
* `-105 <= k <= 105`
**Follow up:** What if the number of rows is much larger than the number of columns?
| null |
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
|
Hard
| null |
1,589 |
hello welcome to today's video we'll be looking at lea code problem number 1589 the maximum sum obtained of any permutation the problem says that we have an array of integers and an array of requests and the ith request gives us the starting position and the ending position of that request what that means is we go to the start index that we're given and we add up every number all the way to the ending index and we're told that the start and end indexes are zero indexed it doesn't seem like too hard of a problem so far but what makes it tricky is that we're given the freedom to shuffle the nums array and we want to return the maximum total sum of all the requests among all permutations of nums and because this answer might be large we want to return it mod 10 to the ninth plus seven i've gone ahead and written down the first example our nums array is one two three four and five as the values and i've gone ahead and written down the indices below the requests we were given were 0 1 and 1 3 and i visualized these a little bit in purple it means from indices 0 to 1 we want to include those and also from one to three we want to include those as well now if we keep track of the count of how many times each index appears in our request index 0 appears once index 1 appears twice index 2 appears once index 3 appears once and index 4 doesn't appear at all what that means is if we left the nums array as is the number 2 would be included in our result twice the number one would be included in the result once the number three would be included once and the number four would also be included once but that doesn't give us the maximum value we want the maximum value achievable what we want to end up doing is taking the biggest value in the nums array and putting it in the position that appears the most what that would look like after we shuffle so we'll shuffle the array a little bit we know index one appears the most number of times in the request so the biggest number should go there that was five i have a bunch of ones here doesn't really matter which one we choose if i choose the index zero what's the next biggest number it's four the next biggest number is three and then two and then one if i were to multiply everything together i would get 4 plus 10 plus 3 plus 2 for a total of 19 once i add that up and that's what this answer ends up being now notice i didn't have to do four five three two i could have done four five two three one and that would have given me the same answer and that's why this question isn't asking for the specific permutation it's just asking for a permutation that gives the largest value like this the crux of this problem really comes down to figuring out an efficient way to keep track of how many times each index appears in the requests one way you could do it and this is an inefficient way and i'll say why in a second is you could look at one request at a time and process it so for example in this first request from 0 to 4 it means index 0 1 2 3 and four all appear which means i can keep track of the count on those values then i'll look at my next request and it's zero two which means zero one and two i'll get an additional count and then my final request is one three so i'll go one two three like this and that's processed but that's actually not a very good way to handle these requests because if you have m requests and n nums this operation could be an m times n operation and that's very slow there's a better way we can figure out how many times each index appears in the array by using something called the prefix sum and with the prefix sum what we'll do is we'll keep track of the first index that a request appears at and then the first index which that request is no longer valid which means for the request number one from zero four we have one starting at index zero and the first index no longer counted it would actually be index five so i'm going to put like an out of bounds here for index five in the second request from zero to two we have two requests starting at index zero and the first index which this request is no longer valid is three so i'm going to put minus one here and finally from one three our last one here i have one request starting at index one and then the first index in which this request is no longer valid is index four i'll put a minus 1 here and i was actually going to put a minus 1 outside here too now with the prefix sum what we want to do is we want to add these all together in such a way that each index is the sum of itself with the previous value what that looks like is this 2 plus 0 is 2 1 plus 2 is 3. how we can interpret this as when we're at index one we know that there's one request that starts here and if we look previously there we're already handling two requests on top of that for a total of three when we're at index two we have no requests starting here but we were in the process of handling three which means there's three total at index two when we get to index three there's one request less that we're handling but we're in the process of handling three which means there are now two total requests we're handling likewise when we get to index four there's one less request we're handling but we're in the process of handling two which means at index four we're only processing one request finally outside the array it doesn't really matter but if you look at these numbers these two three two one they match these values up here two three two one and the time it takes to do this is way faster if we have m requests this is an o of m operation it's much faster to handle the request this way the next step then is to sort everything if i were to sort the numbers from smallest to largest i would get one two four six and if i were to sort the count the prefix sum from smallest to largest i would get one i'm going to use a different color here i would get one two three and from here all i need to do is multiply everything together and keep track of the sum i would get one i'm gonna change colors again i would get 1 plus 2 plus 4 plus 12 plus 18 here for a total of let's see 12 plus 18 is 30. 4 plus 2 is 6 plus 1 is 7 for a total of 37 as my answer let's see how this can look in the code the first thing i'd like to do is make my mod variable now the problem said that it has to be 10 to the ninth plus 7 like this i'm going to just make this a static variable because it belongs to the class it's not going to change for instance okay i'm going to create a variable to keep track of the sum and i'm going to make it a long variable just because i don't want to worry about overflow and this is just a trick that you can use to make it so you don't have to worry about overflow quite as much i'm going to grab n for nums.length and we're going to create our counts array which keeps track of how many times each index appears in the array make end of them i'll process each request now using our prefix sum technique for every request in the request we'll say we're going to start at request at index 0 and we're going to end at whatever the request at index 1 was but i'm going to add one to it and that's because we actually want to include request at index 1 inside of our sum the first index that this request doesn't apply to is one greater than it what i'll do is increment counts at the start by one and i'm going to do a quick check here if the end is less than n i will decrement here by one and that's in case my request goes out of bounds like we saw in the example i don't want to destroy my array here now to apply the prefix sum we'll create a variable to start from one and we'll go all the way to n by 1 like this and the request sorry the count at that index is just going to be whatever it was plus one minus that plus the index one before that next we're going to sort the nums and we'll sort our counts too finally here's the fun part we're just going to go through and we're going to multiply the nums at index i times the count at index i and add that to our sum i'm going to convert those to longs just create a vowel and whatever nums that index i was and we'll cast this two along as well counts at index i like this and then our sum can go up by that value once we're finished with that all we need to do is remember to return as an int whatever our sum was but modding by the appropriate value here let's go ahead and run this and see if it works forgot my semicolon in the first line of code i wrote that's okay in the example we get the expected outcome let's submit and see if we get it right yes we get the answer right here let's look at the run time complexity real quick if i have n as my nums.length however if i have n as my nums.length however if i have n as my nums.length however many numbers i have then for the time i have an o of n operation and then counts and nums are both length n and because i'm sorting them they're n log n each this is another n the worst i've seen so far is n log n time is actually going to be o of n log n you might be wondering about this for loop with the requests and there could be m requests but n log n is going to be a more significant factor than just m which means i'm going to just ignore that if you wanted to be really specific you could do n log n plus m where m is the number of requests and for the space complexity i'm only creating an array of length n so it's just going to be o of n you could if you wanted to instead of sorting these values is put them into a priority queue but i don't like that as much because a priority queue is extra memory and it's going to be the same time complexity as just sorting the array thank you for watching the video if you have any questions please comment and i'll get back to you or if you have any video suggestions please let me know thank you
|
Maximum Sum Obtained of Any Permutation
|
maximum-sum-obtained-of-any-permutation
|
We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_.
Return _the maximum total sum of all requests **among all permutations** of_ `nums`.
Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], requests = \[\[1,3\],\[0,1\]\]
**Output:** 19
**Explanation:** One permutation of nums is \[2,1,3,4,5\] with the following result:
requests\[0\] -> nums\[1\] + nums\[2\] + nums\[3\] = 1 + 3 + 4 = 8
requests\[1\] -> nums\[0\] + nums\[1\] = 2 + 1 = 3
Total sum: 8 + 3 = 11.
A permutation with a higher total sum is \[3,5,4,2,1\] with the following result:
requests\[0\] -> nums\[1\] + nums\[2\] + nums\[3\] = 5 + 4 + 2 = 11
requests\[1\] -> nums\[0\] + nums\[1\] = 3 + 5 = 8
Total sum: 11 + 8 = 19, which is the best that you can do.
**Example 2:**
**Input:** nums = \[1,2,3,4,5,6\], requests = \[\[0,1\]\]
**Output:** 11
**Explanation:** A permutation with the max total sum is \[6,5,4,3,2,1\] with request sums \[11\].
**Example 3:**
**Input:** nums = \[1,2,3,4,5,10\], requests = \[\[0,2\],\[1,3\],\[1,1\]\]
**Output:** 47
**Explanation:** A permutation with the max total sum is \[4,10,5,3,2,1\] with request sums \[19,18,10\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `0 <= nums[i] <= 105`
* `1 <= requests.length <= 105`
* `requests[i].length == 2`
* `0 <= starti <= endi < n`
| null | null |
Medium
| null |
790 |
Hello friends, the liquid problem to be discussed in today's video is Zamino and Prominent Rigs Problem, Very Jab Very Sweet Problem Kya Hai Bhi Two Types of Tiles 2012 Millon Se Electron Shetty Excessive This Is Your Domination Tap Control Man Is Okay NDA government teacher and I have written a number of way to toilet to class and to drops and that to-do list number is Russia and can and that to-do list number is Russia and can and that to-do list number is Russia and can overpower and from here in blouse airplane mode of 21st of now see the problem what did I tell you that every filter Number Office So let me tell you one thing, keep it in mind from now on, whenever you get a question about number sending, number waste, energy at last, number, friend, best tourist destination, important tabs on number, road, whenever you have problem in deciding the number, there you go. But through time, you are going to have to do dynamic programming duty there, dynamic programming does not come automatically by immersion, you have to do observation first, I have to see some cases, for this you have to think, after that you had it at this time, okay you are in this when BD If you drink then what you have to do is help number is fresh means deposit means you will have to do some operation for some test which will be weighed and what will you do with it man's procedure if you are sitting next means write your code for green leaves so let us see. Let us tell you every day that Deepika has a problem, send the number, now let's go to observation, then what can we do, okay and let's go to this channel till I tell you, see how they are representing these domino tiles. Which this one is acid on girls, how come you should not take toothbrush So that you can write easily, you go ahead with the health of your observation. What will we do on the channel? One, we will make a deputy director, that is, he will take the duty, who will show the numbers to Team Anna and waste oil into corruption. J2 Pro To clear the friend, if you add the depend on the answer, then the first thing is that while doing the deposit, do not forget to subscribe, then subscribe number 250, do not do anything and you will melt for yourself, you do not have to do anything. One is, don't do anything to him, now I will go, 121 meaning, the way to call skin, subscribe to this channel, type this fat from side effects, keep the time of 1000 first time, I do the work, the answer of this updater phone is that you have it and it is fine and further. Let me now talk about DP Yadav, I am fine with you, I am just not seeing Amazon, okay, so what should I do, there is no update in respect, but what should I do, who among you means, we will also make some information in our questions. Now it's a matter of whose DP I will give and how much can I do in the difficulty. One, you two verticals, vertical tiles, two tile numbers throughout the year and or else you give this result to you the day after tomorrow, tile number two, you two also. If there is no other way to deal with it, then I will do this, so what will you do? Okay, now I will move on to this. Defiance is something to show the special option, I will still kill on dp3. Okay, now see here which is the bar, now there is an OTP. Show what and how to write to fill the button. There is a way that you think that all three of them are filled by doing two chillies under three medicals or the way is two horizontal and one quality tomorrow or what is the way that you put one medical on it. Baad Center Lucknow is ok or is there any other method? You can use this style to pay the money by using villagers. Problem is, you can appoint these people and one more you will keep it aside. Subscribe to this channel so that I can watch from here. If I try, then like you tukur this if to ask union status how many calls is fine from now onwards ok but by bringing 123 such hatred trophy 1238 and this means script written press from here if you have to type you will get a Let me tell you that your doctor is fine, so before you do this, let me tell you that if you message me that I will go to office today, subscribe to the channel and mention it, then what does it mean to DP you if I tell you? That I deposit, so if you know, fill the DP bteup, after that you have a way, you mean one vertically upward, set the alarm tomorrow, okay, I have a political code number one on a medical tile, so you can use it and fill it in. Can it's okay whose decision it is then difficult to press a quarter Okay with this if you have to respect one thing or another thing I am saying that if someone you what is this 203 whether this is the style Okay, trust that your style is there, now after that if here I have one thing opportunity that if here you are so mean that this last one, fill it up, okay, the last Ali or Ali grade will remain close, this above one, what is there in this? The proof is in the above in which after now see this is our upper part here it was happening here that you first here it means that it is like this your unknown earliest superintendent Manoj Nirbhay that this is an already filled with first girlfriend and what do you If you have to fold two then you have to do this what like office collection was defeat of one day B4 meaning this much thing your solid returned back so much thing and related that how much diplomat got up now in the last you only had to do it here what is the first one already If you have to select the first and the rest, then what will you write about it, DP Funny, if the way to seal it, this is the way to fold it, okay, the way to do this also, you will say which repairing, this one, which means this, only, this This method of sealing can also be done, it means that you have a doubt that I will click from the double center, okay, but what is this thing, you are difficult and consider what was the meaning of wickets, what is there in the deposit, if you have duty BCD. The special thing about ₹ 1 here was if you have duty BCD. The special thing about ₹ 1 here was if you have duty BCD. The special thing about ₹ 1 here was that whenever you choose, you will add your vertical lines in the tiffin, then look, if you add vertical lines, then this is that when it tells you that there is a phone, you have a medical facility in the oven. So if you two will give this stain to the pimple also, right now you will get your money, both of these, this will come out in the house, then it was that Sunday news product, when replace a medical, you had taken the case, okay, so what you have to do, of the proven planets. Have to play till now these two fine rava kiss date wear are already covered tips you with its texture and this is what is dp for ke war dip zero inside that this is what you want to write this means what I have explained to you here. There is no result for the last time, for the first time, friends, I will start Droos and Friends, you have to do this third option, in this is the two front, then you have to install this, what is there, all the three fields are there, if this is here, then you have to complete it here. Here quickly plus together this method is okay so here you guys this means you quote this you have fee this way that why don't you write it like this why do n't you write it like this or like this So why did you appoint me like this, then this way, this ghee is needed in it, so there is no need to worry about them, here you just use only, then you have seen that whenever you like from a disgusting channel, this is the way of thinking. If you find a way, then I have searched here that how easy it is to reach from the restaurant menu, how much is the way, what did you do from the one, did you put 2 green chutneys, did you reach Delhi and will you give, see this is the way, if it depends - I covered. Have done Mr. Panchal depends - I covered. Have done Mr. Panchal depends - I covered. Have done Mr. Panchal RD PF end means end minus one end disbelief end store where can you reach in one way depend on Vijay you deposit mms-2 means - mother tongue I am deposit mms-2 means - mother tongue I am deposit mms-2 means - mother tongue I am your ODI and you and where you reach is difficult Then it depends on the verification one i.e. how is this two one method, how is this result i.e. how is this two one method, how is this result i.e. how is this two one method, how is this result added inside and its first rumor, but as soon as you wash the mark one and a half 75 below the end minus two, this is your instability method, what was the second one method, you write like this. feet second cut it like this what is the second in the house okay so towards mirchi what debit did we have above is that way through bittu that you are below then you have these two ways that you do another operation once write object saturday office Try ok deposit, press it, how much is there in his day, how much is difficult, write down with you, come, if there is your depression, then there is a method, then if you did your DP of urban, then how much do you like this method, you have it, okay, I have talked about it. Here you can see that it is 12345 Subscribe to you from 2015 to subscribe Accused - - Verb - Soon - Verb - Soon - Verb - Soon happened Depend know ok so what you do is the way of OTP Free Plus Marks This is the way where to reach here Okay, after that if you deposit mention means that this was D3 then if you forget the end manners then what will you get tip two then if you remain * then your skin is the method, how is your health, is remain * then your skin is the method, how is your health, is remain * then your skin is the method, how is your health, is this method ok, we will see this thing. How else is it, for the first time I had written it completely once, after that now it is DP of one, DB reached the phone, then there, if you like this method, then you see the answer, how much is this, which method is this, then like this method, this one. Come back to this method is fine, I have done this on this lineage, but now do not forget to subscribe and MS Word 2003, the makers of the sea, so that is cute and that two methods, what will be this planet, this thing, how do you see this. Here, if you do this, then this will be like this, how much is this, how many feet is this, how much is this important, that ₹ 50 go for how many feet is this, how much is this important, that ₹ 50 go for how many feet is this, how much is this important, that ₹ 50 go for sacrifice and what is the next one way, if you add like this and develop then you can So you have this thing filled gift f5 inside were on YouTube and minus one and end is above okay so you will be its will depend on the way on reaching that like you end Vastu under the cartage you anniversary positive for admin Surya Varsity Blues If there is a box, then the method is on MS Word, I have the right, so for you, how one of our donkeys gave a white color and this one method of ours is ours, now we have added the second method of ours, secondly, you have adopted this method, okay, so now we In this 1 minute this how this disgusting way from depression he is stressed you need it in three ways I want to do it to you that you date of birth and you need that like you need another and you need this that we so this There is no need of thing that every time you subscribe to MS Word, subscribe to the channel, subscribe to this channel in this way, this dha dominant has covered this thing, that is why you need to visit him. No, whenever you go down to MS Word, you will see what this will be, only these two will decide the ad and the rest of the sacrifices. If you leave this phone from here, her vagina is tight, this is not a diploma certificate, it is five, okay, deposit, how many countries? It's 5s, you have turned it around, it's okay, look, the unappreciated is taking his help, how difficult is the ticket, that the way is different because from where you were from, there are two ways, Superintendent, this way is NDA 's way, that is the way of Deep's Divyaarth. 's way, that is the way of Deep's Divyaarth. 's way, that is the way of Deep's Divyaarth. Even on 1000 and that when he said that if you had lived in the forest then you would have got the opposite, so if you want to do it regularly then terrorism file and this method will create a stir on the heart, there is a way to add it to the five plus two k. With Toofan Play Store, how much has it become seventh, okay then it has been invested, there are many side effects including method, but of course, how can you add these three main things, okay, how difficult will it be for you to get a refund, then one and a half. Total how much should I find because dedh apne pen hai but aa remaining and after that remains is famous that the person who dies every day seven plus two 7 whose daddy one and a half because like how much for 2004 2ND year after year deposit verification more this you Aisa 527 aur Toubro Edition 1134 kitna ka eleventh mirch aapko hai this thing of mine had reached the diff and while when the advance to give a specific hoga hans ke jio zinc his theirs was the same as the other account and simriya spiritual finally Bigg Boss edification is ok If you try to write this solution, then how will you write it? If you have to write a MIDI file, then it is okay for you. If you also have the file with your OTP of Tamil Nadu and is equal to five, then it is okay and how much is that, then there will be a way. MS Word how much is this plus the only way is this single Marathi a single power meaning medical time is ok after that if you write refill - 2nd PUC then after that if you write refill - 2nd PUC then after that if you write refill - 2nd PUC then how much is that after that diameter is the only way which is this is ok if you write this thing This is medical till Bologna because in 2004 he is fine by giving him chocolate, after that we and I myself got anniversary covered, Admin, when will you come, as soon as you go down, Al-Masri advance will be of the you go down, Al-Masri advance will be of the you go down, Al-Masri advance will be of the highest but for the anniversary instead of most of the times. If you also have this mantra of your own, what is the way to make DP difficult, then there are two ways of DP Yadav, the leader of the rear, one is difficult, meaning what have you previously done, two problems, total, what is the total you have, press here, how much cleanliness, caller, prompt meaning. 123 456 वीर्वर वीर्वर Show this thing 456 वीर्वर वीर्वर Show this thing 456 वीर्वर वीर्वर Show this thing 's settings Subscribe to Plane mode Mute Educational and Management and to me If you at this time will that problem be done so that to make overall decision that thing is covered in thing and advanced that you can check Okay, so that and this is the method, what is the second method and the second method will be fine, if you have white vinegar, with that, let's go to this, come to the prescriptions, go to Admins and MS Word, DPO, and then chili, you have filled one. So one method of sealing is known, while two are famous for the method of fitting. Okay, this one has one method or Twitter is different, so you remind me how to fill, the method of bringing to front, this one thing, this end. Along with me you and this and how can you keep this egg so the method is like you want Bapu's milk Edit under many-2 Okay now you have want Bapu's milk Edit under many-2 Okay now you have seen this and Ayaan that, now you have come to this five our Here, if you are using MS Word or Bigg Boss, it is okay if it is not covered, then it is okay if you get it, then here is how you will cover it, there are two more ways, and in that way, see like this, you will keep it like this, okay This method is fine and apart from this, what are the other methods? You can see this is the best side like Meghna, okay, so I fried it here for two minutes. Now use both the sides like this. You can also add that in the subscribe way like soon bromine complex will be started here, commission, I have started from three, I am till this York, the second method will start happening in front of that much chili and if you have difficulty, I will remove it from here. How will it come out but if you go to click on 'A Difficult', then go to click on 'A Difficult', then go to click on 'A Difficult', then how much is the way for Deputy Editor of TVpur to make it difficult? 1111, you are a love letter about yourself, which is fine, then if you add more, then what is the difficulty here? Difficult digestion. Regarding verb rest, your Ashwani is that little yellow oneplus 5t, you and if you go to graduate, then DP October is how much it would be and after that it is how much it is and the evening one is Bittu. After that it is how much it is. Tatya is because then how much is required for this, you are understanding this completely, how can others do this problem, after this see here rational kg Stuart Broad and gas will be made, what will happen to the authorities and okay and How much concentration can you change here also? Along with this, those whose Bluetooth has become two-end, you should definitely whose Bluetooth has become two-end, you should definitely whose Bluetooth has become two-end, you should definitely do nothing to them in one way and if you can varicocele them in two ways, then how much will that role say about the Interpress traffic jam. What do you need from noise to land? Let's go. Def and if you have to write VPN, if you have to write then what can you do. It will depend on what you mean and minus one. So with that you can reach only through a single way. Difficult on this. Hai Simreli, which will be your DP of MMS-2, enter into syrup, what will you DP of MMS-2, enter into syrup, what will you DP of MMS-2, enter into syrup, what will you do, you will be able to reach in a singer way, depending on this, after that, whatever will come after that, DP is off - reel is ok, anniversary is the same, come after that, DP is off - reel is ok, anniversary is the same, anniversary prescription, whatever is my distance, how am I? You were caring - it has become how am I? You were caring - it has become how am I? You were caring - it has become okay, director govt. job will move forward till it also reaches more districts, okay whatever it will be, there will be poverty in all of them in one or two ways that you are easily America's valley when the end - 1m Aishwarya Rai valley when the end - 1m Aishwarya Rai valley when the end - 1m Aishwarya Rai Regional Dekhe Stree Lemon Adhuri Posterby Prakash Le Do Raath Ho Depend Aapke Kya For Mriga Bhi Aap MS Word Plus Def And Minus Two Plus Two Independence realme2 DP Update Se Jahar Ko Kya Steve Thanks For Mulayam To Ye Humko Kya Deputy Chief Editor for Telling, if you try to appear, then our formula also depends that this is also not a reply, boys, look at that, you will have to completely reverse MS Word, you will never be successful, what will we do with this. We will try to apply so that it was in a very short form so that you can call it easily. This formula is also complex. Okay, so to supply it further, we will make mathematical issue different from what benefit got depend defamation cases equipped up to 100 to you. Like now if you tweet all the things then interdependence re art and studied a dead skin equation in were ok that depend on minute then how will you write MS Word meaning and you will replace MS Word Android you were asked these questions Tubelight White Thank you Shifan, what to do if you replace them with NH10, then this point question is the last, now the equation is - Sid, question is the last, now the equation is - Sid, question is the last, now the equation is - Sid, if you do Vacation 1972, then this is complete mathematics, if you try with help, then what will you get, Radiff is MS Word and default is - Chief Administrative end - default is - Chief Administrative end - default is - Chief Administrative end - difference next Vikram Thakur ji, you will get final till dividing it by post and Malaika got difficult times a day of annual plus deputy chief end - or that annual plus deputy chief end - or that annual plus deputy chief end - or that you will get final and military area's final formula, will be DP of D chamber. Of Cartoon Times Depend - And Plus For Cartoon Times Depend - And Plus For Cartoon Times Depend - And Plus For Difficulty What Will We Do During This Attack We Will Solve Our Questions This Player I Three And Cent Missile You To The Temple We Are Going To Get Our Amazed-Amazed Cody Get Our Amazed-Amazed Cody Get Our Amazed-Amazed Cody But A This Our Code This Is A Sharp On the mode, we will first modify it, for that the applicant behind the non-preferred friend will be equal to applicant behind the non-preferred friend will be equal to applicant behind the non-preferred friend will be equal to 2014, so you are going to be the same way, it will be okay, life will be there, so we have written that you what cigarette is the way, then it is life, then what should you become, it is okay to compete. If the end is equal to two then you check the mixture of cast and but that then you return to Katha, this is what everyone in the country has to do, then you have to suffer in both the ways and embroidery. So what do you do with 510? So, this is our beans, how we have covered the PAN earlier, the return fair of MS Word Open, do you want all the upcoming features, those who are using up I mention are fine, what is Android of Islam that your Kiran Reddy has not messaged anyone. Okay, I have made the batter. What all has he got? 20011 equals one two equals two three four army beans. We have already tried to walk on the border bottom of thumb and if it is respectable bottom-up then and if it is respectable bottom-up then and if it is respectable bottom-up then you have done it first. To whom did you give the benefit of your elders, this zero one two three cutting was full of it, meaning I hate my life is good, you have canceled it is difficult, you have installed it two times a day for relief, meaning it is mentioned from here, if it is fine then this The basic rules of Diplomat were modified on the same face and I kept applying Freemont, wondering what the front arm hole is like, okay, then you will just do the certificate of Deepika and Moradabad returned FD, time bomb acid will be talked about, where you mean on enter. It is useful for chatting and reducing speed. Look, here you have created your test career here. Okay, you can also activate its Speed Congress. You tried to can also activate its Speed Congress. You tried to can also activate its Speed Congress. You tried to think of something and try to write these quotes, pants, quotes. Okay, otherwise you And that means do the video secondary, if you find it difficult then it depends on 12-WW, it depends on 12-WW, it depends on 12-WW, it is ok, it depends on the strength you have got, it depends on the management university you have come to, then you need to take it completely. Should I maintain the previous free play list here? Have I come till now? If you have to maintain the earth, then you will have to do this as well. Okay, so we will make it clear by covering the method first and make it our base like this. Vidya n incomplete 235 population, how many previous ones are there to maintain the balance p2p three, what is there in the rupee forest by killing these three, you are your DP like aa system, peepal tree, this is your five, okay Bittu, what will be the deposit in it, your day two TRP methods will be done, pay the rally of the current environment or with your hand only matter do you answer glances2 time DBFI love I mention so come mention your store in it AP man mein to tut sp1 plus piti miss of a specific artiste That 330 after that it is done and for that you update the appeal by beating P3 send this appeal that today Happy 181 will be started Answer in the best director Yash Biggest go to then yours which if business - widower decision will be taken This I want to go to business - widower decision will be taken This I want to go to business - widower decision will be taken This I want to go to Bangalore means what is behind the back, what is it where Pintu will be set, okay then update this recipe and the interested circle, what time is it here, it will be over immediately that your single family that you have This costing enables you to keep this question in mind. To reach next, first do that call me to set 5181. If you are on WhatsApp then friends, I hope that you have understood its expression and donation. We also saw the specific monthly and in the end. If you have any problem then do tell in the comment section if you like this video then like the video and subscribe the channel or share it with us Saathiya Aa Hamara DP Apni Ka Meaning Dynamic Programming Playlist One Sided Love Problems ABC Explanation If you watched it, I hope it will strengthen your DP. Thank you for watching. Television Institute and Take Care Point is the victim's friends.
|
Domino and Tromino Tiling
|
global-and-local-inversions
|
You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Explanation:** The five different ways are show above.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 1000`
|
Where can the 0 be placed in an ideal permutation? What about the 1?
|
Array,Math
|
Medium
| null |
153 |
So hello friends, today our dec31 is that is the point minimum in routine solidarity, so what to do in this question, we must have been given solidarity for BSE but in the rotated way, like Gyani here, if our name is late, now in this that Whenever you rotate, please set the app one time and then do comment along with it. Okay, put ₹ 4000, not 6, but Okay, put ₹ 4000, not 6, but Okay, put ₹ 4000, not 6, but then increase it to five. Had to increase the entry of love, so ultimately our rotates got sorted and this is how it happened. From bottom to top it is there but then after that 4 5 6 7 question look at the simple question it will be easy to find out which is the recipe number but keep in mind that it should not be done that we have to point out the minimum then why do we give such a question. Neither do I have to use Roti's software nor do I have a little brain, so what will we do bubble sort and what is its method? We know one thing that somewhere in the middle there will be a part that we have already sorted. Okay, the matter is from zero to city, what is the minimum in this, the minimum of zero has been found, which is the minimum number, so in such a solid case, there is no problem, but how will we know that the software has kept the road and i.e. stopped till this much. We have software has kept the road and i.e. stopped till this much. We have software has kept the road and i.e. stopped till this much. We have shown that from 1 till now, we can break it to any number. If you rotate it four times, you can rotate it seven times so that there is no such problem, so what have we done? First of all, we have taken the first official answer as 90. I have taken the name. Okay, we have taken the answer in these pictures that let's have an answer, we will find the minimum, okay, so here we have taken left and right and put the lap on our zero side, Campaign 09 - Manti and until Loots from the right, 09 - Manti and until Loots from the right, 09 - Manti and until Loots from the right, how will it work if and is disappointed, if by God's mercy it turns out to be already pointed, that is this a co- if by God's mercy it turns out to be already pointed, that is this a co- if by God's mercy it turns out to be already pointed, that is this a co- time rotator, then it has come or set zero time, it has come now, it does not mean mute the volume, then it is like this So it is so logical that we have to apply our mind to see that Ajay Bhai, the one on our left is smaller than the one on the right, it also means that our work is going on easily, then the answer will be our minimum of answer or left. Of the ones inside, we have Christian missionaries on the left, so there is no problem, so here 1 liter is simple for me, if not, then this meter will be charged, it is of meat, we will initially assume that the chillies are plus white, Vijay Shankar festival. If we come to the center, then we divide it by age plus are you two. The interior is divided, so we will reach the center from here, there is art inside it, so we will reach somewhere in the middle, at 4. This is where our media will go, so we will know our mind. We have to put it, we give an example, it was already sorted by here, it has come to five, now to find out our brain, we have to search here and this is the left side, so what we have is the medium answer, what does it do to us 2030 Who else is Jatin, so here you subscribe, this song is in the middle, so people are so beautiful, that is the song, we are doing this, the answer has been given the minimum, so if the mental lights have been appointed to the left appointed to the left appointed to the left Three, four, five, it is saying that it has increased by 5, it means that if subscribe like subscribe was here, then it means that we have to take it on the right side, one step back in whose pile, so this is what we have to do, if the middle number is bigger than the middle one. Leave it to me, otherwise subscribe, I have come to Sadhna a lot.
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
338 |
Hi guys welcome back to my channel in this video we are going to solve counting mid day one problem of march list in challenge switch problem one and give wealth and exam whose link will be end plus one and its element will be All the numbers from jio to end numbers are there - in the representation, there - in the representation, there - in the representation, how much is the tweet from the number off? Okay, so in the stuck example, we have added two and we have added all the numbers from zero to two in the binary representation of that side numbers. We will see what is the number of units of those OK, if the by representation of NGO of vegetables is zero, then what is there in it, what is there from tweet from salt, will be zero, Jhala A representation of first element one is there, so what is my number of set, how many are one in it? One came and two came, what will be my number in 2010, I will not have one, so I have to type here, let's take an example, then let's see, my channel is fine and what will I have to do here from and till the end Presentation, we will see what is the percentage, so it will always be there, here I am, the number is off, I have submitted, if there is one, then there is a rectangle, you and I, how much is this in two, in 1020, how many number of seats will be one each in Pathri. What will be my you body former how much will be mine 102 in this of the buildings in this inside of this in the file of this number of eight nine 2,000 white how will this number of eight nine 2,000 white how will this number of eight nine 2,000 white how will he see so always for zero so what will be the number of seats will be zero okay kha when we for one We will keep one till the end and when we see it, what will we do? We will end the representation about both the cant number and the previous number. After doing the end, we will see the number upset basis in which we will see how many are mine, what should we do in that one. If you add plus then the answer of 140 will be added in binary presentation. About doing end, we will definitely get it. If we add plus one to it, then there is video from Namo in zero. Okay, the number is fabric. Whatever is there in it and if we add one plus to it, we will get one. 1 Will keep it here, if we look for 14012, then my buy at present is one, which is this one, okay, then we will add both and end both, we will get employment in America, okay, there is salt in this, mine is 0204, what is this, I am one in this. What will I get after doing One Plus, I will get the same that if we look for feet 2013, then we will comment on these two, we will end these two, what will you get Kavandi, if we get 2010, then what will I do here, how much salt service is there in this, how much bastard dynasty and in this Will we do plus one, what is this world, two here, two is my doing, when we look for, then we will add four three, and to do, what will I get after here 07 2010, then zero plus one, when we do, then what will I do? You will definitely get it, here you are bin, okay and then when you look for five, you will add four and five, what will you get if you trend this a little and 06271, here is one, officer and add one, it will become two, okay mummy, two. Now basically what are you doing here we are remembering zero for life, we are looking at Jio for accounting two, here this zero of both is a little okay, the number of zero is the number of. Birth certificate which is there, then when you are looking at the method, then after doing the end of doing the work of both the cants, I am getting 1012, how much are you mine, now you my number is first in the black list, you can add the previous way. You are giving, so we will solve which one here, he sees, here we will take an air, a pint of batter, a painter v10 plus was the topper, the initial value of the battery is 510, the set number of civil surgeon roll is then we What will we do in this tie, we will carefully see that friends part plus seat, this MLA Lallu, mine will depend on this, OnePlus I and I - after dialing 110, there is a Baroda account on that number, it prevents that is I - after dialing 110, there is a Baroda account on that number, it prevents that is why we are here. Also Android will be indexed I & I - One OK indexed I & I - One OK indexed I & I - One OK let's look at this and what will we do in it One Plus will do a quantum will do this vector was the topic loot my device bile slaughter thank you
|
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
|
451 |
so here's the problem liquid 451 sort characters by frequency so problem setting is pretty simple you'll be given a string sort it in descending order based on the frequency of the character the frequency of character is the number of times appears in the Stream so if you see is t r e so descending all right so e comes two times so e uh in the first place then R then T if basically any character having the same frequency then just uh put it in ascending order so this is what the problem statement says the same thing see this C and A has the same frequency so you're storing this as any order so it is just understand problem so it will consider same exam history first thing I'm gonna create a map of character and int hint this basically count number of times basically appears so t comes one R comes one time then e comes two times right and what I want to do is after this I'll make a pair of character I eat this is my map right this is my map and now I'm gonna make a pair of character of a character and int I'm sorry up just character and ink and foreign store is character t comma one Character Are comma one and character e comma 2. so I will basically push it push all of them in a vector and then short it as a more shorter question requirements descending order of frequency if they are if basically both are equal then just sort it in ascending or so this is word actually the question is it's pretty simple just for better understanding just get the code so first make a map of character and ink map M let's call it m okay I forgot to put semicolon no issue then Traverse through the entire string into I equals zero yeah is dot size then type S Plus original map of s of Y Plus now and it has to be calibration fix it okay now what I'm gonna do is Omega vector right now I'm gonna make a vector as I've said it will be basically store up here of character and then in let's call it back well and then push basically if you see unlock I was pushing the container of map into a vector right so let's do that for const in three let's call it entry and three map in map m in mapping and I'm gonna push all of them push back it's entreated first and Trader first comma in see dot set okay so we are done basically and okay I just put it in my college brushes so that it can be present as a pair so we're actually done we're done till now I'm gonna short the vector right so sure back let's begin almost back a vector and dot in now you see is still short has its own comparison but here I want the mine so let's create custom comparator struct let's call it CMP no issue now basically we have to overload that operator okay this thing and we need that inch plastic const here of color I mean let's just take five different and on up here Again by the difference Okay so now if my P1 dot second means the frequency right is greater than P2 dot second then basically return true else if my P1 Dot second is less than P2 Dot foreign and then return false is just written uh P1 DOT first ascending all right so p on that first less than P2 DOT first so comparator is done specific CMP now let's create a string answer the blank will so I'm gonna take all of the entries so now after sorting it will look like Okay so Vector the vector will look like something like this you need comma two they are comma one this is one okay then uh t comma 1. so I'm gonna take all of them one by one right and when I'm seeing e comma 2 that means in string there was a e for two times so I'm gonna add e for two times e so it is R right this is R comma one so in my in original string there is war for one time so I'll take R for one time and T for one times but e for two times because you see there is a frequency of 2 so let us do this so for count or two and question p in the back for 10 times equals I equals to zero I is less than Vector size oh now oh it's not a is physical P dot second right frequency dot second and I plus and answer plus equals okay dot first so this is how this is what it should look like then you can answer I guess we are done let's just run and check here's our placement now okay so there is some problem where here p let's check again compile here we have a second okay spelling is that second so extra e not check again I guess should be a mirror at all okay it's accepted now this is supplement and fix it I guess yeah it gets attracted so this is how it is thanks for watching
|
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
|
215 |
hey what's up guys in this video i'm going to go through this elite code 215 okay it's a largest element in an array so let's look at the example in here um we are given an array of numbers so it looks like this and we need to find the largest the second largest number for this example so the largest one is six and the second largest is five that's why the answer is five and for this array the fourth largest is the is4 so a naive way to solve this would be sort of this array and take the k element in the shortest arrays but i will take a little bit time because the sorting typically takes a bit of end lock-in lock-in lock-in and so that's gonna be slow and uh improvement on that this would be uh we can use a heap a mean heap to do this let me show you an example so for example for this guy um this list we need to find a second largest so how can we use the mean heap what we can do is to pop off uh the n minus k elements and the n minus k plus one element will be the decay largest so in this example is the second largest obvious guy so we can pop off all this guy away and then we pop again with the mean hip always pop up uh pop off the minimum value so each time when we pop it off the medium value will be gone so we will pop off uh the fifth time that will be the second largest for this particular way and for this one and there's exactly this and we need to look at the fourth one the fourth largest and what we need to do is to pop off uh six times so one two three four five six uh when we pop off the mean value of the heap we always pop up the mean value so when we pop off the sixth time and that will be the fourth largest so a general formula will be let's say uh n is the length so then the list the length of the list and k is the k largest element that we're looking at and uh we use the mean heap will be n minus k plus 1 that's how many times we have to pop off from the heap so let's look at the code together either one will work right so first we need to heatify the numbers uh list and then we get the n and it's the length of this number and we pop off n minus k time first and then the m minus k plus one time will be exactly the k largest number or we can just use the n largest function of the heap and that will work as well so let's submit it and it works um in terms of the space complexity we need a uh it's a big o of n because we need that much space for the heap and for time complexity we will be k log n because each time we pop off a one number that takes a log of n and we need to do that k times so it's k times log n so this will be an improvement of the n log n sorting method so this is so much for my solution i hope you like it if you do please like this video and consid to subscribe to the channel and i will see in the next video thank you for watching
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
617 |
hey everyone welcome back and today we will be doing another lead chord problem 617 merge to Binary trees an easy one you are given to binary tree is root 1 and root 2. imagine that when you put one of them to cover the other some of the node of two are overlapped while the others are not you need to merge the two trees into a new binary tree the merge rule is that if two nodes overlap sum them values up as the new value of the merge node otherwise the north null node will be used as the node of the Nutri return the merged trip so the note is the merge the merging process must start from the root of the both trees so we have two trees one three twos five and this tree so we have to take a start from the root add them up and take the value put it in the new you can say at a certain location at that specific location uh of a new tree so this is just making a new tree and that's it like one plus two will return three and three at the same location with one at the second tree will run four and two with three will return as five and now we have three e left which is five but one at that location in this you can say we are going parallely so one does not have a left so we'll be assuming that it has a left that is you can say a zero so we will just add five plus zero and put it in the new binary tree and now we have three right we do not have a three to its right three doesn't not have a children to the right but one does have a children to the right so we'll just do the same assuming three has zero child and just adding them up and putting it into the new location and two does not have something on the left he does not have something on the left we will just add nothing in that case two does not have something to the right but three does something to the right so seven plus zero just you can say how we explained the other nodes so that's it 7 plus 0 will return us zero and that's it so first of all starting with if there is not a root one and not a root 2 we will just return in that case and if there is a root one you will take its value one you can say and root one dot well okay so in the IELTS case as we said that we will just assign that value is equal to 0 if there is a root that is invalid or null so root if second root we will just value doing the same to the second tree root value and in the else case assigning that to zero and now what we'll do is just adding them up so our root making a root node which will be 3 node and adding these values up so root at value 2. so this is done and we want to go to the left so root dot left will be equal to the self at calling the method again merge trees okay so now we will pass it the root one left only if the root itself is valid yes if the root itself is valid we will pass it otherwise we will just was none and doing the same to the root of 2 so root at 2 at the left we will see like if it is valid the root itself is valid then else or basically exist you can say so I'll be copying this line just for the right side and that's it right side and taking the right side also if the root one is valid pass the right if the root 2 is valid pass the right otherwise the none so that's it and after doing that we can just uh return what do we have to return like root yes I think it's it is root so that's it if you have any kind of questions you can ask them in the comments and see you later
|
Merge Two Binary Trees
|
merge-two-binary-trees
|
You are given two binary trees `root1` and `root2`.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return _the merged tree_.
**Note:** The merging process must start from the root nodes of both trees.
**Example 1:**
**Input:** root1 = \[1,3,2,5\], root2 = \[2,1,3,null,4,null,7\]
**Output:** \[3,4,5,5,4,null,7\]
**Example 2:**
**Input:** root1 = \[1\], root2 = \[1,2\]
**Output:** \[2,2\]
**Constraints:**
* The number of nodes in both trees is in the range `[0, 2000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
399 |
Came Trend Quality Tubelight England 27th September Refugee Dega To Problem After That They Division 10 Minutes Facebook Restaurant Problem Share Governor Equation For A Difficult Of Very Interesting And Real Number One Subscribe 0 Key Print Jeweler Tumor June 2012 Decree Will Result In No Division 101 With Dozens of Introductions Input Is Equal to a Question Is Equal to a Loss Will Also Be It Means Divide Baby and Values in the Balance Are Means Divide Baby and Values in the Balance Are Means Divide Baby and Values in the Balance Are Switch 2.0 Switch 2.0 Switch 2.0 That Similarly Divide Me See Jaan Service Three 500 Questions and Spider Verse Hai So Let's Take A Look And Example And See How Looters War Se Exam Vote De Shesh Kumar Superintendent Of Police Amazon Store 2.0 In This Bay CP Thakur 231 More Subscribe To What Is A Y C Request How Much Awadhesh Bhai Absolutely Tourists From First Week And See The Question Two Times B N Seven Recent Vacancy Result b.a. First Seven Recent Vacancy Result b.a. First Seven Recent Vacancy Result b.a. First to Three Times Thee and WhatsApp Status Sequence Tubelight Additional Vacancy BSP Pet So Let's Replace with Spelling of NCERT Question is Nothing But Two B and C Nothing But A So Its Peak Battery Radhe* 10.30 AM 2320 Peak Battery Radhe* 10.30 AM 2320 Peak Battery Radhe* 10.30 AM 2320 First Points 60 A Symbol of Made Night So 10 - First A Symbol of Made Night So 10 - First A Symbol of Made Night So 10 - First Career Photo Secondary And Men Also Stupid Just Hair Were Given Meanwhile For Vice Chancellor Absolutely Tube White Sorry Oh Wow 2006 Baby Cost 2.0 264 And Saffron More Na Video Balbir Which Is Not The Equation - Video Balbir Which Is Not The Equation - Video Balbir Which Is Not The Equation - Noida Number One Adhere Subscribe That Shubh at Experience Not in the Equation Right Since Protest 10 Hindi Questions Twitter - Seervi Exam Amazing Two to Do Something Different subscribe Twitter - Seervi Exam Amazing Two to Do Something Different subscribe Twitter - Seervi Exam Amazing Two to Do Something Different subscribe and subscribe the Tubes Loot-Loot Liye subscribe to the Tubes Loot-Loot Liye subscribe to the Tubes Loot-Loot Liye subscribe to the Page if you liked The Video then ki vacancy here YouTube is the stupid ad value And dahej best of the fried and b2c is the president of subscribe now to receive 12826 simply amazed of the video then subscribe to subscribe and subscirbe not want to give a new 2018 jai hind fifth in button press club 10 number right because one by two singrauli Only Excellent Quickly Find The Value Of To Be With Her Mother Is The Meaning Of The Word That Only From This War Question The Judge Is Directly Equal To How Much It Is In This Regard S One 22610 One President MLA Surendra Dogra Hey Who Is This Being Can Have Still Alive Mera Favorite Is Darz Ek Kama Bhi Ajwain Question And It's A Meanwhile Kumar C S Another Question Daku Maan Singh All Song for More Question Is Serving Equation Of B And C It's Way To Be Positive And Negative They Really Need To Subscribe Similarly For B Id Candidates B That And Situ Hai Will Be Actually Press Club Dance c2c 271 226 And Travel b1 B2 C B5 B6 B12 Class 10th Tomorrow Morning Can Build A House Map Like This And To Find For Giving Carry Forward To Find And Senior Difficult Starting From This Point Going To The Point Solitaire To PNB To Cigarette Like And Deposit Now Like Zid Now Clubs In The B.Com Subscribe Now To Three Four To Go B.Com Subscribe Now To Three Four To Go B.Com Subscribe Now To Three Four To Go For PUBG Game From Ubuntu That They Can Go To See Morning Can get a deficit item for elements in the map they can find flavor between value defense can you find what was the length of the particular bhi tight sonth wali sardi done for bhi funda the value of birth yadav life and vidyapeeth again dad i don't laugh and Definition of servi and the points difficult subscribe a super rich with your product updates 18.2 a super rich with your product updates 18.2 a super rich with your product updates 18.2 back will be product of but what is the best of this particular path in to the best option middle aged person if then subscribe and question rate from this question morning building subscribe now To receive one right subscribe reports ki raa hai so any where to go through this element subscribe if you liked The Video then subscribe to the Page if you liked The Video then subscribe to that if cylinder burst successful declare map with key A string and develop a map of living in the world map by the grace of the map that Anirudh equations I Ahmedabad News Ajay Ko 200 persons gotra decorations and builder mafia ho Shabd a super singh prostitute's persons were already present 210 current question is a Q and Check Weather Start Verification It's Already Present In Map Also Only Price Half Hour I Love Creative That They Do It Has Many Benefits Of Garlic To An Indian Help And 210 Yo Ram Idea For The Amazing The Correspondingly Judge Available Be And Develop So Ifin The Graph Sishat Accessibility PM The Path of your WiFi Normally Benefit For The Recipe Of The Earth Is Best Way To Take On The Right Side 108 In Clear Rohit Vadh Sexual Exploitation And People Peace One And Values Of Life In Those Days Peace One And Values Of Life In Those Days Peace One And Values Of Life In Those Days Back Okay So 10 Par Maaf Bird Once in this world map spotted that lineage put maths plate to go to shape a research and tech edifice on the map object and see the west journey entry photos from this placement main your start ka size lettuce main current during som say lap The rehabilitation definition number panel 14 result loot results 2011 should declare double result done four and the length of the results with stories and beautiful difficult need to pass map the variable this of caring key dot staff10 that dadri block are known to one and all should Have Enough Too Obscene Going To The Point Where To Make Sure That Will Regret Not Because The Visited This Will Create Visited S8 Rippling Alarm Set Up Change And Digvijay Singh Sardar Top Faujdar Given Lakh Ya Not The Ringtone Old Aage In Which Were Warried And Specific Return Year W is the result of the equation light of ki and si the result of pi ko stuff wow I let seedhi double pizza effects in the let them into positive Twitter - 1.08 so let them into positive Twitter - 1.08 so let them into positive Twitter - 1.08 so whenever * invalid date of birth ball sahal whenever * invalid date of birth ball sahal whenever * invalid date of birth ball sahal volume ki and akshar you can Celebrate Check Personal The - 100 The - 100 The - 100 Thanks To Jab Ballender Result And Student Can Do The Result Of It's Right The Function Of India Face Minute Dum Aap A Theek Hai Dada Giri 661 Ki In Q2 Aap Ahmedabad Attend Set Up Hua Tha That Hey Brother Worst Condition Laga Then wife's area tap were return dot the contents might even in that case eternal like just table train is such a show it's late friend that 2012 cute were going right were trying to find the equation q1 divide like you two what is the value so in Terms of the Year Printed on Thank You Tube and Security With You Need to Visit Again So Let's Greater Noida CEO Rajeev It's Not Present in a Map of What is Not Present Name Application Faizpur Eternal So Let's Side National Hua Tha Ki Naav What Is the you want you to his present in my map directly war value to be good in that case how can directly return Diwali lights of birth another condition that such a excuse why hotspot off phone why phone off stopped on today's date of a Cute to softcore toner that in this section directly vitamin E I 10 years you correct 209 Vinod is condition has to write the best to 8 10 current tune into the wisdom and will be different from the right so let's status * good thought and * good thought and * good thought and phone why closed Have another nala element edifice for the value of attract shop youth dot right brother that I forget even some of the given get return I have given you Rinku me the school why become well equipped 10 the Indian Air Gaur Vishal use dot this whose photo Loot bath going and 1431 in the given map and ends after doing to difficult that I office current measurement that Andhra period virus my current S8 morning I contest witch is the current's tube will be the same cute images in this method that android were Visitors Will Be The Scene Notification Awadhesh Any Too Returns The Amazing Part For This Particular Also Tight As And Artists Can Return Divya What To Where Is The Value Of This So Difficult Particular Plain Mode On Words Into The Current Value Of The States Of Just Don't Brother Give water get of his address will give me the value of the current pass tubelight so super example decision 2121 b1 b2 c hua tha ok year old btc right any to friend begusarai swift on road to become fuel here going through all the values of fuel here going through all the values of fuel here going through all the values of bride suryapal Singh Been Defined b2c Improvement It Means The Value Of But You See Now Finally To Return Back Right Any To Also On Tubelight Tasty Laddu In Hair Should Be The Value Of But You See And Good Bye This Will Give Me The Volume And The Path Of Tubelight What Is The Best All The Benefits Of Birth Sudhir And Identification No 225 Mist Talk Daily NC Favorite Grains In That Similar To Text Bone Function Wash An Undercover President Who Give If It's Difficult To Unlearn Were Returning - 100 Training Is Given - 100 Training Is Given - 100 Training Is Given Main Soya Thing's View Deteriorating Condition Ramesh Kumar And Expected Swine Flu Time 10 Soon Superintendent PK Member Dungarpur Mission The Complexity Of The School Also Sincere Building Member Of Assuring That In The Map Jaspal Beef And Space Complexity And The Time Complexity Of Buses Were Going Through all the career servi of Mulk who is the furious over your dream of few times and difficult from all the elements in the fight decision and few times when is the time complexity of Sudarshan for this video please like button and subscribe comedy thank you
|
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 |
1,481 |
it is an amazing problem hi guys good morning welcome back to new video it has been asked by JP Morgan a lot Amazon xedia and do let's quickly xedia and do let's quickly xedia and do let's quickly see what the problem says again it's a very good problem it is MZ medium but still it is actually a very good problem the last approach will actually be very good and not that easy to code right okay think it's easy but not to code cool let's see what the problem says it says that um least number of unique integers after care removal exactly same as what the problem ask us to do which means you are given an integer array called as ARR and you have an integer K you have to find the least number of unique integers right after removing exactly K elements so you have some elements you can remove some K elements from this array itself and after removing these ke elements you have to find the minimum number of unique numbers or elements in this entire ARR ARL so ultimately my goal is to get the unique integers right unique integers so I'll just simply can get the unique integers right now itself in the very beginning okay unique integers right now for me are five and four but RN I wanted minimum number and that to after removal of some K characters oh sorry K elements oh which means that uh I have to remove exactly K elements and it is the unique elements so I can't just say Okay remove the K Elements which are unique no it can have some frequency no of a element five it can have a frequency of two so if I'm saying I have to remove the K uniqueness which means I have to remove the uniqueness of five which means five should not be there so I have to remove two fives if I want to say four should not be there so I have to remove one fource because fource frequency is one so one thing I got to know uniqueness I can grab I have grabbed the uniqueness but I have to do some K removal for that K removal I need to know the frequency also so one thing is for sure I need to know the frequency so I have got the elements unique elements and also their frequencies okay unique elements are there and frequencies also there but now what else we have to do we have to get the least minimum number of unique integers oh we ultimately my aim is that in this entire above array which I have of unique elements I should have minimum number of elements remaining in this and operation is I can remove some K elements but K elements I will remove from the frequency itself so I know if something has a high frequency which means it has two frequencies so okay as you can easily see in this example itself my K was one which means I can remove one element so will you remove one of the fives if you remove one of the fives then still five will still remain so in total unique elements will still be one so it will still be two so rather what you can do is remove a one which remove a four which is a frequency of one so with this frequency of four will become zero which means four is gone out of the array now only five is remaining with the frequency of two and ultimately I'm concerned only about the uniqueness so uniqueness is only just unique one element which is five and that's how I can simply get and say that great bro um you have got Max minimum number of unique elements cool so now we have know got to know one thing that we can just grab the unique elements we can grab the frequency of those unique elements and then whoo has a minimum frequency I will try to remove those frequencies out of my key itself so that is the very basic approach which we can apply for this first for this question that's a Brute Force approach so what I'll do is I will basically sort all the frequencies which I have got first I'll get the frequencies now I will sort those frequencies and after sorting those frequencies I will actually remove the low frequency ones with the bandwidth of K because I know I can remove exactly k elements so I'll do exactly same just a small try run I have this array I'll get the frequency of all the elements because I know I want the frequencies I'll get only the because I know okay I want only the frequencies and for The Unique elements only so unique elements are these frequency for them I have just separate down and I sorted those frequencies down because frequency are two and one I sorted them down I got a one and two and now from the sorted frequencies I will start removing elements I will start REM moving these frequencies considering my K same way you have got the frequencies you'll get all the frequencies down see R in what about the unique elements bro every unique element is mapping to its frequency so if I'm saying I have four frequencies I'm saying I have four unique elements that's it cool so I'll just get start removing my K okay K was three I can remove one frequency okay remove that K now becomes two remove one frequency k now becomes one remove two frequencies K is one I cannot do that okay so for sure I can remove two elements so I can remove two elements remaining unique Elements which means minimum number of unique elements remaining are actually two so answer is two for us cool let's see the code it's pretty simple as what we saw firstly we will get the frequencies of all the elements right after getting the frequencies we'll just simply grab those frequencies in a vector and then sort that Vector because we cannot sort the unordered map so I will just Aran then why you did not use the map itself in the first place bro I want to sort the frequency is a value not the key and map sorts things on the basis of key not the value I want to sort the value so you will see I will push back the value in a vector called as frequency vector and then I will sort that Vector not sending order because I know I want to grab out the minimum frequency element so I just will iterate on the entire frequency V which I have sorted just above and in that I will just keep on removing the elements because I know okay if I am just going on in the frequency order from left to right I just trying to remove those elements from my actual because ultimately I want minimum number of remaining unique elements so as soon as I land onto some specific frequency Vector it will give me bro right now the frequency is this so I know that elements I can remove is this one now elements I can remove is this much but I have a limit of K right I have a limit of K if my Elements which I can remove exceeds k bro hold on stop right there and then return the frequency Vector minus I Aran this code is not understandable much no worries see what happens is you will go on to all the elements now you will have this variable elements removed so what you will do is elements removed right now elements removed is zero okay you will land on elements removed is one okay I can remove three elements removed is one okay now you go on to next I again one so I can simply add element removed is so far two okay great move on next I okay element removed I'm thinking element removed is actually Four but bro four is more than three which means you cannot remove it bro hold on you have exceeded your limit so how many you can REM remove you can remove these number okay how many are remaining are these number so indexing if I just put the indexing itself 0 1 2 and three so this index two represents I have removed two elements so how many remaining the size frequency which means the frequency Vector this frequency Vector dot size minus I gives me these number of remaining elements remaining unique elements so I just want that frequency vector do size minus I which give me the remaining number of unique elements ultimately we'll see that the time because we have sorted the frequencies and every element can be unique so it is in login and for sure we using map in the very beginning so an map so that will use of n space now interviewer will ask you can you optimize this now if you just look back and rewrite the exact same thing in just one line what you have done above so what you did was you your just getting the minimum frequency element and then trying to remove it by K that is what you doing right you are trying to get the minimum frequency element from this out of all the frequencies you trying to get the minimum frequency element and then trying to remove it by it that is what you were doing did you hear the word you trying to get minimum frequency get minimum get maximum if you have to get minimum or get Max maximum very fast then the first thing which clicks a mind is min Heap or Max which is priority Q so now I know that okay I have to get minimum or maximum then I can for sure use a Min Heap or a Max heap if that is the case then I will just try to apply Min he or Max Heap but that is just you have thought of maybe it can improve it but are you sure it will because what you have to get is okay we are getting the minimum frequency element and then trying to remove it by K oh getting the minimum frequency element which means to get something minimum out of all the frequencies you will first have to put all the frequencies in the Min heat now putting all the frequencies in a Min Heap itself is a n login operation login to just insert in a Min Heap and frequencies can be n in the worst case oh so sorting was itself good then but what will happen is after that okay I just complete the statement then what you did was okay you are getting a minimum frequency element which means you have to first push in all the frequency element in the main he then you just start to remove it by k which means okay you can just have at Max K removals so K removals at Max of a heat size of n it will keep on reducing that's the word so it will be K log n But ultimately you will see that you have got a n logn factor in your time complexity so one thing is for sure you can tell the interviewer that okay sir I thought of this which means you will just speak out loud that okay we can use a mean Heap but then you will also say that the time complexity will not reduce and for sure the space also because you will have to grab the frequency element so o of n space will for sure be taken so one way is you can just skip the coding part for this all together you don't have to code it but still for the folks who are curious how this will be coded simply exact same thing we will get the frequency element then we will just grab the priority CU which means I will have a frequency Min he because I know I want to grab the minimum frequency element and then I will just simply keep on pushing the frequencies all the frequencies in this mean heat right that is actually taking our n log and time and then ultimately I can now go on a trade on my Min Heap how I will say okay until my Min Heap is empty and I'll just exactly same I'll just grab the top element which say the frequency I'll just simply add in my removed okay this many number of elements I have removed if it goes beyond of what you can remove simply bro return the existing size of Min which says these are number of unique Elements which are still there and then if it is actually not there which means if you have if you can still remove the elements if you are in Bound of your k then simply remove the top element and then again keep on repeating the loop exactly same as what we did here also exactly same it's just that rather than now going onto the minimum frequency element by sorting I'm going on the minimum frequency element because of my main Heap but still you will see that the time complexity is still a n logn factor which will still be same but now again interview ask you can you bro please optimize it now bro is very confused how I will do it now bro will again go on to what he did and how we can improvise it so bro used a sorting and then to improvise that he thought of using a priority VI because of the statement which we saw but then both were taking and log in time now the interviewer is asking you to actually improvise it which means he's asking you to actually make it a linear time complexity making it linear which means I have to make it linear but then I have to also use sorting because I have to ALS go on and do and grab the minimum frequency element so sorting is also needed linear I have to do what can come to your mind things like bucket sort count sort all that stuff now for sure I know that I am grabbing the frequency of an element I'm grabbing the frequency of an element frequency oh of an element I have n elements so max to Max case the best case is every element has a frequency of one right Max to Max every one element has a frequency of n that's a case Right One cases I have all the unique Elements which means 1 2 3 4 5 all elements have frequency of one or first Cas every element which means let's say so I take a different 2 two so all elements which means just one element have frequency of 1 2 3 4 5 6 so I can simply say I wanted the frequency and I want to sort that also so can't I do one thing I will keep a vector in which index will say this is a frequency and the value will say how many times that frequency came in so I will be indirectly if I go on again how see now I knew one thing I will use I have to make it linear I have to also use sorting so for sure I have to use such sorting algorithm which actually is linear in time that is nothing but a count sort but now how to use that count that is a very good question so you know very basic thing that okay you will have the frequency and you want to go in the frequency the ascending order so for sure I will go on the indexes okay that is great I will go on the indexes what I should store as their corresponding values okay key I have got as the indexes but what I should show as the corresponding values that is a question so corresponding values I can simply say okay I have this frequencies I have got the frequencies so uh I can simply say that the frequency of one is just once frequency of one is occurring just once frequency of two is occurring only once okay only once it is how I'm okay with the information which I have right now I'm trying to build my this count sort algorithm because I know I have to apply that but how to actually code that up and how to think of the solution that it can actually handle our K case like because I have a limit of K so how we can handle that I have to think of that right now okay uh with the other example also let's see how this uh array will be built count array so I have a frequency okay I know that this thing it has the frequency okay this has the frequency now for sure one oh one is the frequency how many such one frequencies are there oh there are two so I just said one frequency occurring twice okay two frequencies occurring once and three frequencies occuring again once now uh that might be you can also try in and make your dry algorithm because of this two cases but it is very small and you might not understand that so I will take a better bigger example again I will take again I have just make out and see how I can actually use K because again my variables are now K and the specific array which I have built so to make a bigger example I just took more frequency so frequency of one is again this is a frequency array remember this is not a vector array Vector array will look something like okay and I'm again just building a random example to figure out the solution which I can have that's the same way I will do in a contest or in a OA or in an interview I made the frequencies I'm not concerned about the elements I made the frequency okay one frequency can be two three frequency can be two corresponding to it maybe for your explanation I made backward like just reverse engineered and made the array itself and that and you can see okay 1 2 frequency of 1 3 4 frequency of two 5 six frequency of three and twice so okay now I know that I will go on and ENT on all the indexes so as to make it linear so right now I will be landing on the frequency of one this one indicates the frequency of one this two indicates the number of the count of this frequency one is occurring twice this frequency one again it can be very confusing so listen it very carefully and also try to actually write it by yourself try run by yourself also at the same time so this frequency of one is occurring twice right so what I can do is I can say Okay number of elements which we can remove are actually two no R it is incorrect number of elements which you can remove are actually 2 into one bro although I can say number of unique Elements which I can remove is actually two but then you will say I in The Next Step what you will say it is four elements you can remove or you can remove two elements hold on I will tell you both the things so right now I'm saying I can remove number of elements as two right which is number of elements you can remove is two now Aran are you seeing unique elements are you seeing total number of elements hold on this will be cleared in the next example so but then removing elements does not define let's say here the frequency would have me nine but my K is itself eight so it doesn't matter I have to also take in consideration what key can do what my key can do oh I am saying I can remove two elements now my K ISS I'll ask my k bro how many number of elements you think I can remove from here he says bro let's say he says I can remove two elements and you can see I can remove one and two he says that because frequency of both of them are one so I'll ask and I'll go and ask k bro K what do you think how many you are allowing him to remove so K will say okay I am K the frequency of every element the frequency of every M right now is one so with that fact you can remove eight of the same pattern as a frequency of one you can remove eight elements oh bro is allowing me which means K is allowing me to remove K elements bro is allowing me to remove eight elements and I can remove two elements from here bro is allowing me eight elements I can remove two so for sure I can only remove two so I just remove two so what I'll do is I will take the minimum of K upon frequencies which is nothing but how many of this pattern I can remove which means the pattern is frequency of one I can remove it came out to be two which is this value which is the count of the frequency which is the count at which I'm building and K upon frequency which means how much my k bro is allowing me to do so minimum of 8 and two it becomes a two so now I know I can remove two unique elements oh which means I can remove these two unique elements for sure I have got the permission I can for sure remove it if I can remove this two unique elements then how many number of elements are remaining is one fact and what is the K remaining is other fact so in total if I just go and ask this frequency size will give me the number of unique elements at the very beginning I have six unique elements and I got to know right now that I can remove two unique elements so now my remaining unique Elements which are will be four so I have to now remove now go and say okay I have to now go and remove Four UNI elements but your K will also reduce because you have removed some elements right you have removed some elements you have removed two unique elements but you have used your K if you remember you have used your K to remove these number of unique elements okay two unique elements you remove two but corresponding to those unique elements what were their frequencies their frequency was the pattern which means the frequency was one for both the two unique elements so that's the reason I said the frequency for those two unique elements again I just grabbed it how much I can remove these two number of unique elements for those two number of unique elements the frequency for one so ultimately from eight I have removed total two elements so that's the reason my case six now that's the reason I told you just hold on because here the frequency is one so like that division multiplication will not much make sense but now it will make sense when the frequenc when the K has been made two and that's I just took a better example because if you remembered in the above example the frequency of one is two and for other are the frequency of one so to actually improvise the example I have to make a better example cool now we are at the frequency of two now my pattern now my right top pattern is all the elements these are the number of unique elements for them the frequency will be two okay which means right now I am at this portion again remember your K has been reduced now if you are at here you will now go and ask how many number of elements I can remove same way that okay two elements two unique elements he is allowing me my pattern of frequency of two says I can remove two unique elements and I can easy see two and if you go back and see you will have three and four as two unique Elements which you can remove okay but then how much K is allowing me K says bro K is six K is 6 k bro says that bro I am six which means in total you can remove six elements two elements if the frequencies again you can remove six elements right if I just make and say bro can you make a pair of two which means you have six elements I am going and ask my bro which means pattern okay bro I am making a pair of two elements which means my frequency is two so okay frequency of two so my case is if bro you are the pattern which means the frequency is two the pattern frequency is two then you can remove three such unique values you can remove but bro I only have to okay no bro remove two but I'm allowing you to remove three so bro like k bro said that okay I'm allowing you to remove three so K how from K I asked him the value K will ask me and give that K upon frequency is the number of unique values which K is allowing me to remove which is three how much I can remove only two so I'll remove those two okay I can remove two unique values so because of this two unique values I can remove firstly I will update the number of remaining unique values because ultimately in my answer I have to return how many number of unique values are remaining right so I will go and ask bro ultimately because of the above pattern my remaining was four but now here I got to know that I can remove two more unique elements so remaining now will be two unique elements I will still remain now because of this I have removed two unique elements but if you remember you have removed two unique elements but their frequency was a two so how is the how much K is remaining is six by default it was there number of elements you can remove are actually two and the frequency of each of them is two so that's the reason your K has now become a two and for sure if you will go on ahead and now see because now your K has been remaining as two if you go on ahead you will try on for different value as soon like you will keep on going when you try on you have got that number of unique elements you cannot remove anywhere which means this will become zero for sure your number of unique elements you cannot remove you cannot improvise your answer you your answer has become less than K you'll simply break out and say okay bro number of unique Elements which I have was having this is the remaining of un which you can give that's it which means a simple edge condition that okay if your K becomes less than your frequency then simply return lse exactly same as what we saw how what we saw just have a quick recap firstly we get the frequency because that is very important but from that frequency I have to make a count sorting kind of array right which can help me in count sorting now for that I'll simply go on and see this is a count of frequencies it's a array in which the index says the frequency and value of that index says how much times that frequency is occurring in so that's a simply count of the frequencies count of again frequency is the count of elements now my array this array is the count of frequencies so that's the reason I told you in the beginning that this actually problem is a tricky problem that's the reason it has me as JP more 15 times now uh I'll get the our counter frequencies aray now when this is done I'll go on to all the frequency which I have because I was going all the frequencies 0 1 2 Z frequencies not like it doesn't make sense so go on 1 2 3 up till n frequencies now I'll just check how many elements I can remove okay so my current frequency pattern says bro this many number of count you can remove but I have to also ask my k for permission bro K how much you can allow me to remove for this frequency pattern so both of them will give their values whosoever is minimum I will take that is the number of frequencies that's the number of unique elements which I can remove so it is a number of unique element which you can remove okay if that is the case simply out of your remaining number of unique elements remove the current number of unique Elements which you have or you can remove and for sure in your K also reduce the actual number which is number of unique elements multiplied with the frequencies number of unique elements multiplied with the frequency is the total number of Elements which I will have for that frequency I'll remove that from the K and then ultimately I'll just keep on looping it now in the worst case or in the worst case if your K becomes less than the frequency itself which means your K value you have nothing remaining frequency is you have to remove and for you have to remove that specific element whatever you have with that frequency you cannot remove that element because the frequencies because uniqueness says a element if the array is like this now K is let's say two but you are at the frequency of three this is the index frequency if this says my the V value will be here or maybe upcoming let's say this is a zero but this was a one but I'm saying no matter what going forward going on forward basis my frequencies are only increasing if I have anything whatsoever if I have any value non zero which means I will say okay I have one element having a frequency of four which means the element can be six 6 six having a frequency of four that's a one element have a frequency of four so no matter what after this point my K remaining is to after this point I can never ever reduce my unique number of values so please simply break here which means simply return here itself and that's the reason I can simply return from here itself ultimately if everything goes good you can remove all the elements and then ultimately nothing will like nothing will remain and that's how you can simply solve it again with this you are using simply o of N and you simply o of n space Also o of n the N size although space has increased a bit because of frequency are and the count are also but yeah the time is much more important for us and technically the space Also is just o of n itself okay it has o of n plus o of n but still it's again o of n itself and that's how you can solve it again the only reason I think this problem is a bit tricky is because of how you implement it thinking wise it can be easy depending upon you will be able to reach it's a account sort but implementing that it's because see frequency itself is the count of elements and then you are taking the count of those frequencies which actually great cool thank goodbye take care bye- bye thank you bye-bye if you care bye- bye thank you bye-bye if you care bye- bye thank you bye-bye if you want to watch these videos please go and watch these videos these are actually great bye-bye
|
Least Number of Unique Integers after K Removals
|
students-with-invalid-departments
|
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
**Output:** 2
**Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
**Constraints:**
* `1 <= arr.length <= 10^5`
* `1 <= arr[i] <= 10^9`
* `0 <= k <= arr.length`
| null |
Database
|
Easy
| null |
417 |
today we are solving Pacific Atlantic water flow problem there is an mcross and rectangular Island that borders both the Pacific Ocean and Atlantic Ocean Pacific Ocean touches the islands left and top edges and Atlantic Ocean touches Islands right and bottom edges this island is partitioned into a grid of square cells where the value of each cell represents height above sea level of the cell the island receives a lot of rain and rain water can flow to neighboring cells as long as the height of the neighboring cell is less than or equal to height of the current cell we have to return two list of grid coordinates where each coordinate denotes that rainwater can flow from that cell to both Pacific and Atlantic Oceans so here is an example Island and the same island is represented in 3D over here as you can tell the rows go in this way and the columns go in this way for example row zero is 1 2 3 and five and row two is 3 2 3 4 the water can flow from a cell to its neighboring cell as long as the height of the neighboring cell is less than or equal to height of the current cell same over here and we need to return coordinates of each cell from where the water can flow to both Pacific and Atlantic Ocean Brute Force way of solving this problem would be from each cell we do DFS in all the directions and anytime in the DFS we reach cells that borders with the ocean we note down which ocean the cell borders with and eventually when we reach both oceans we can add this cell to the result Pro Force way of solving this problem would be from each cell we do DFS in all the directions and anytime a path reach the Border cell we note down which ocean that is and during this whole DFS for that specific cell if we reach both the oceans we add this cell to the result and we continu this process for all the cells so the time complexity for this would be of M CR n * this would be of M CR n * this would be of M CR n * by m CR n so the first M cross n is because we are running DFS on each and every cell so there are M Crossen cells and the second M Crossen is because in each DFS in the worst case we might be visiting all the cells is there a way to optimize this what if during the BFS any time in a path for example here and we reach an ocean for each of the nodes in the path what if we cast which ocean these nodes can reach in the future if we reach any of these nodes we can just return the cached result this will bring down the time complexity to O of MN but there is a problem with this approach let's see what the problem is with this approach let me clean up some space let's take this graph for example let's say we are in the middle of a DFS path for this node let's say we have already explored the left neighbors now we have to explore the right neighbors so n the neighbor to the right has the height equal to the current cell notice the condition is the height of the neighbor has to be less than or equal to the height of current cell so which is true in this case and we can continue DFS down this path all the way until we reach Pacific Ocean so once we reach an ocean we note down that all these nodes in the path were able to reach Pacific Ocean right here and eventually here notice this node was already able to reach Atlantic Ocean following the left path so now we can add this note to the result and anytime we come across any of these notes again we can directly return the cast result so the problem here is you may be able to see this specific node can reach Atlantic Ocean by following the path like this but we were not able to explore to the left of that node because the left of that node was the parent node itself so in the DFS we cannot go back to the parent otherwise we will end up in a deadlock situation so because of this we could not explore path through the parent all the way to the Atlantic Ocean so that's why straightforward DFS with caching doesn't work how can we solve this problem instead of doing DFS from the cell to Ocean what if we change the direction what if we started DFS from the ocean to each and every cell in this direction let's clean up some space and work on this graph again here's the same graph again this time we are doing the DFS in the reverse order starting from the ocean let's say we start from Atlantic Ocean and for each TFS or for each ocean we maintain a different cache so let's say this node borders with the ocean that means we can reach the ocean from that cell so we start DFS from that cell and visit all the neighbors that have height greater than or equal to the current cell notice the condition is also reversed because we have changed the direction of DFS so we can visit this cell and this cell we cannot go any further because the neighboring cell has a height of six Which is less than seven so we stop here and for all the cells in the path we put them into the cache of Atlantic Ocean because all these cells can reach Atlantic Ocean so Mark a saying all these cells can reach Atlantic Ocean we repeat this process starting from Pacific Ocean let's say this cell neighbors with the Pacific Ocean which means this cell can reach Pacific Ocean so we start our DFS from here we go up this path because each neighboring cell has a height greater than or equal to the current cell go to left and all the way to this cell so we add all these cells into the Pacific Ocean cache Pacific so now as you can tell we have rightly identified both these cells can visit both Atlantic and Pacific Ocean and we should return them in the res so this solves our problem let's recap what we have seen so far now we do the DFS from Ocean to cell and we maintain separate cash for each ocean and we return the cells that are present in both caches so that's our algorithm let's write code for this I've copied the example Island here so the Pacific ocean borders with the left and the top edges and the Atlantic Ocean bers with the bottom and the right edges so let's call M and N the dimensions of the island of height and we need two separate caches for each ocean let's call them by their name Pacific and Atlantic and these are the set to maintain the cells that this ocean is reachable from next we have to do DFS from all those cells that border with either of the oceans for I in range M let's process the cell the cells on the left and the right Edge we calls with row number and column zero for the left Edge and column n minus one for the right Edge so the left Edge is Pacific and the right Edge is Atlantic so we need to pass the cache for the Pacific Ocean here and the land equation here let's do the same for top and bottom rows so we call DFS on the top row which is specific for row0 and column I and we do the same for the bottom which is Atlantic Ocean with row M - one and Ocean with row M - one and Ocean with row M - one and I so when we have all the cells in the ocean specific caches we just need to find the cells that are present in both the caches so the way to do this in Python is by finding intersection so we just have to return the intersection of Pacific and Atlantic Ocean this returns a set we just have to return them as list so now the only thing left for us to do is Define this function DFS we pass the cash row and the column number if the DFS has already been called for this specific cell that means this cell can already reach the ocean so let's add the cell to that ocean oh let's call this ocean and we are adding the row and the column so next we need to explore all the Neighbors which are row bottom cell top cell right cell and left cell these are all the neighbors if they're out of boundary we don't have to process those neighbors or if the neighbor if the neighboring cell is already in the ocean we don't have to process them or if the height of the neighboring cell is less than the height of the current cell we don't have to process them this is because we revers the direction of DFS now the neighbor has to be either less than or equal to the height of the current cell for us to continue DFS otherwise we don't have to process those neighbors finally we call DFS on the neighboring cell so that's our code let's try to run the code we pass both the test cases let's submit the code as you can see this is the most optimized approach if you found this video to be helpful please like the video And subscribe to the channel I will see you in the next video thank you
|
Pacific Atlantic Water Flow
|
pacific-atlantic-water-flow
|
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105`
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
| null |
142 |
hello guys welcome to deep codes and in today's video we will discuss Lead Core question 142 that says linkless cycle 2. so here you are given the height of the link list and we need to return the node where the cycle begins and if there is no cycle simply written null okay so along with the head you are also given one position here but this position is used internally to compute the cycle of the link list and so please don't consider it might be a little confusing but yeah originally that if the position is not passed as a parameter it is only used internally and yeah you will only get head as a parameter so you need to use only the head of the linked list to determine if there is a cycle or not so yeah let's say for the first example as you can see that starting from 2 there is a cycle like from 2 to 0 to 4 and again to two so we can say that yes there is a cycle and it is at a node two so we need to return the node where the cycle is present so it is at this node so we return this node okay now here the cycle is at the node one itself as you guys can clearly see starting from node one uh this node one to node two guests are connected to one so the cycle is at node one here there is no cycle so we will simply return earlier so I hope you guys understood the question that what we are trying to do we are simply trying to return the starting node of the cycle now uh for from the for the basic intuition part how you can uh get how you can know that whether a number is repeated or not so let's say you have some simple error like this like one two three one two five okay so how you guys can tell that whether a number is repeated or not see you can see that one is the first repeated number and if you want to tell that uh how you can tell this any number is repeated not or if you want to find the first repeated number then you can simply do this by using map or something like sad data structure so if any number is present already present then we can tell that it is repeated when we encounter for the second time so yeah that simple approach will also work here in the linkage part so we took one set of list node this is the data structure list node and we store the nodes so if any nodes uh its Warehouse value is uh repeated uh then what we can do we can simply return it so that means see hey what we here check the if you know dot find head equal to node and that means the node is non-com in the set in this set node is non-com in the set in this set node is non-com in the set in this set of nodes okay then we insert it else we simply return this head using this head pointer beta version so we simply written the head okay so that means we have inserted three node two node zero node four but after traversing from four we again get node two okay so whenever we encountered this type of situation where a node is already present in this set then we will simply return our pointer simple as it is but guys this approach takes a space complexity of we go offend and V and here the follow-up question asks you here the follow-up question asks you here the follow-up question asks you that can you solve this using big of one memory or big of one space complexity so yeah we have to find some better approach uh another then side so that we only we don't use any extra space in that now there is one specific approach to solve this question and I will discuss directly that approach and that approaches a Floyd's algorithm fluids algorithm or you can simply set a cycle detection I'll go in linked list so this is uh simply The Voice algorithm or cycle detection algorithm now here the question arises how this fraud algorithm will work and uh how it will work so I will discuss the upper approach to solve this equation using the floors algorithm see there are two things uh two pointers that we use in Florida's algorithm one is low pointer and one is fast pointer so ah this low pointer travels uh to the next element hit travel to next travel next element see what the type of pointers what we simply do we travel so the next adjacent element simple as it is and here in this fast pointer will travel next to next element so this means this will travel one element at a time but a the fast pointer will skip one element and travels uh so at a time it will Traverse to Eliminator time simple as it is so let me take an example here let me take a linked list and try to show you that how this slow and fast pointer will work to detect a cycle so guys as you guys can see here that this is the linked list and there is a cycle here at a node two okay there is a cycle because from five next point of Phi is pointing to 2 that is already Traverse before so yeah now we will uh do a tried and how slow and fast pointer will work so initially at this position both slow and fast pointer would be there in the initial head okay now in one iteration slope will travel to the adjacent but fast will travel here okay so let me write S1 and F1 so in one iteration and the second iteration slower Tower here so it's S2 it would be here but fast would be here like it will travel to pointer now S3 would be here now f 2 would be not here if here this would be F3 okay simple as it is it travels to one uh one this and second here now S4 would be here and F4 would be here so as you guys can see that in the fourth iteration the slow and fast pointer Collide these two pointers collide and whenever this happens whenever both the slow and fast pointer Collide we can say this tells us that there is a cycle this denote that there is a cycle in a linked list Cyclone link list whenever some pointers Collide okay now and but what we need to return the head of the cycle another question address is how to find the head off cycle okay so for that uh after whenever the uh whenever the slow and fast pointer Collide so at this point they Collide it we take another pointer the third pointer uh we can uh so we take third pointer uh and that starts from the head let me take it as entry pointer okay so now the entry pointer will start from here okay and we simply use slow pointer again so currently slow pointer is your entry point it is here now this they both will travel so in one trouser entry point third will come to here a slow pointer will come to here is again okay S5 so when the entry pointer and the slow point of it collide we will get our answer so the Collision node of Entry pointer and slow pointer is our starting node or node of cycle so this Collision where entry and slow point of collide is the starting point of motorcycle now this is the thing but there is some mathematical explanation to tell you that how this works behind so I will take the same example again it is one two three 4 5 and this is here okay so now let's I will take a so means there is an obvious question that why we have to take the third pointer why we have by the third point of it starts from the beginning okay there is some obvious question see slow and fast pointer will collect that we know this is a collision point but why when how to find this head of the cycle so for that we took the entry pointer now to explain you the concept of 5 will use the entry pointer uh and this low pointer again to find the head of the uh linked list then yeah this is the explanation for that so as you guys can see this is the uh this is the initial position initial this is the cycle initial cycle in it so this is where the cycle will start and this is Collision where the Collision has occurred this node okay so I will take some of the distances see L1 distance is let me take it as the distance from the initial position to the cycle initial so where is the head of the cycle it is distance between init and cycle in it okay let me take L2 as the distance between cycle and collision okay so let me take these two distances right now okay clear till here now let me take one another uh variable C that would be the length of the cycle length of cycle okay so using now we will use this variables now as you guys can know that what see first thing what would be the distance traveled by the scope pointer distance traveled by slow pointer what it would be simply this distance from the initial to the cycle head and from cycle head to the Collision this much distance it would be traveled by the slope pointer okay so that would be L1 plus L2 okay now distance traveled by the fast pointer how much it would be how much so it would be ah simply starting no from the starting node to the cycle head that is L1 from cycle head to the Collision point that is L2 plus let's say it has taken n times round of this cycle so I will take n times C so that means it has taus n times the length of the cycle okay got it now the third thing is third Intuition or third thing we know is uh twice of slow pointer length equals to fast pointer that means that twice the distance traveled by slow point or equals to fast pointer because fast pointer travels uh two points at a time so if we uh so in order to match the distance traveled by them we have to multiply two here okay that means 2 times L1 plus l two equals to L1 plus L 2 plus n times C okay now remove one L1 L2 from here then you will get L1 plus L2 equals to n times C now if you take L one ah then it would be simply what and C minus L2 okay now uh you have derived this formula now remember this L one equals to n c that is a cycle length minus N2 okay right you can simply also write this L1 is equal to n minus 1 times C minus L2 okay simply as it is see we just took one cycle and from here okay now the thing here is see what is L1 here this much is L1 right and this much was L2 and total was cycle length this total was what it was cycle length now um what is our answer L one equals to n c minus L2 now uh see L1 is this much and C minus L2 so let's say uh so let us take L1 here is length one L2 length is what four and seal that is cycle length is 5 okay now L1 equals to C minus L2 see guys so as you guys can see here that L one equals to what C minus L 2 c 1 equals to 5 minus 4 this is equals to one so this is satisfied now if you are still any confusion now let me explain you this once for all see this is the latest take this is the starting point this is the head of the uh cycle and this is a cycle okay there would be something some wrinkles like this so what is this distance is L1 now C is what C is the perimeter of this circle this is C and what is L to L2 is distance of the head of the cycle uh up till what obtain some Collision let us say Collision occur here then this distance is what L2 okay now as of for as our formula says L1 equals to what C minus L2 see L2 is this much and C is the complete now what is C minus L2 so this part this remaining part is what this remaining part is C minus L 2 simple as it is for a circle this is if this is L2 then C minus L 2 is this because complete is C and so C minus L2 is this part now is the formula has is saying that L1 equals to C minus L2 this both distances are same then if you start one pointer from this Collision node and one pointer from this head node and you would Traverse then you will meet at this point simple settings because the distance from here to here and from here to here is same so I hope you guys now understood that this that how we are ah how this formula works here okay this is the visualization right this simply states that so see what is this the distance between start of linked list and head off cycle okay and what is this thing the distance between Collision node and head off cycle okay these two things is it is what it states so if we start a pointer at this point and one pointer from the Collision then we both the pointer will eventually reach at what reach ahead of the cycle and that's why that's the reason that if we start a take one entry pointer and take one pointer where the correlation occur and if you start traversing you will always meet at the head of the cycle and that is the reason that uh you will get ahead of the cycle if you do this okay so I hope you guys understood this going through the approach now let me show you how this low and fast pointer will work so as I told you that we will first take this slow and fast pointer that will Point initially to head now we will now as I told you this low will point to one step and fast point to two steps and whenever we get something like this low equals to fast that means that is a collision point where the Collision occur now from the Collision Point what we take one entry pointer that is from the starting of the linked list and so it slows over the Collision Point okay currently slow will be pointing to the Collision node so one pointer from the entry of the English one pointer from the Collision node and whenever they both will be equal then that would be our head of the cycle okay so at that point we will return slow got it so this Loop will work until they both are not recover whenever they would be equal we would simply return slow I hope you guys understood this one pointer from the starting of the English 1.1 from the Collision node they both 1.1 from the Collision node they both 1.1 from the Collision node they both will end up to head off the cycle and this is how what we are doing here and this is how we've written our answer and yeah the time complexity here would be we go off and in the space complexity would be here we go of one so this is very much better approach for this uh for this question and yeah if you have guys any doubts then make sure you let me know in the comment section also if you have any feedback then do let me know in the comment section make sure to like this video And subscribe to our Channel thank you
|
Linked List Cycle II
|
linked-list-cycle-ii
|
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Medium
|
141,287
|
1,974 |
Hello Friends Today In This Video Will Be Going Through The Cost Your Problems From The Latest Patience Contest Friends Let's Start The First Problems To Find Out The Minimum Time To Type God Tuition Special Typewriter Health Center Soon Given That You Have A Typewriter With This Object To Apply For Slow ABCD Will Also Take Its Right To Food And Water Problem Also Give The Subscribe Now Subscribe Button And Don-2 Subscribe 108 You Can Go To Be In Verses In The Beginning Of The To Boy In The Control To This Festival Much Time E Request You To Type Of Difficult Words Not Understand Mode Where Is The Role Of A Journal Not Writing All The Best But Just Writing Down For Samsung City And Can't See Exact Date Is Difficult ABCD Only On A Straight Side GN Diverted Select You Want You Will Get you want to see the like this that ayodhya to see like this a web 2.0 why police alert to options web 2.0 why police alert to options web 2.0 why police alert to options which can get to free from airtel sim and from like poison and equation - you find from like poison and equation - you find from like poison and equation - you find the minimum step c request to get down from a to Z Grammar Complex Shop Like This App Dos Samsung Galaxy J2 Rate Playlist Se You Want To Get To G Thank You All The Best Option Se And Authors Percentage Of His Mind And Soul Who Sacrifice For Daughter In Water Park With Bf Chovatiya subscribe The Channel and subscribe the world will be lit Roopram Airtel set to learn it goes for a girl asked you do two options option * ok asked you do two options option * ok asked you do two options option * ok then third option incomplete do you do subscribe to subscribe our YouTube Channel Please Share Thank you liked The Video then subscribe to Setting Volume Maximum Matrix Organization Zinc Droz and Tricks and Custom Developments Post Only Numbers Under Wash Different Numbers By - One Can Change a Under Wash Different Numbers By - One Can Change a Under Wash Different Numbers By - One Can Change a Significant Number After to the Self Start How Much is the Value of the Number Give Number One That Last Mukhiya Surgical Selective Aap Matrix Let's Unite Is 28 That He Rose Those Problems Can Share The First Unread Post Multiple To Table Transfers And Pay Bills Broad Contours Of Tribes Anywhere And Subscribe 0 And A Caste And Divine Work Possible Clear All The Ground And With A View To add all the total number send matrix interactive lad number denge number and date of birth negative meaning of but in all cases and possible to maximize the total space of a matrix quantum negative number to the number which is the best possible because what is the meaning of the word whatsapp number de number 5 2010 subscribe Video subscribe 108 number subscribe and subscribe quid car and temple root and denver lutb negative andhe leaf punitive vidyalaya jadoula sorry for the self work here just to find the minimum number 90 number denge number the and minimum Subscribe To Flash Lights Jo Mara Trick And That's A Book By Jaswant Negative Number And Numbers Smallest Number So What I Will Do Risayat First And Roll Number System Number One To 4 5 Se Zulmo Number Will Find The Number 10 2010 1200 10 Number Which Total Submission Consist One Knack Office Let Consist Of Wealth But This Was Stretched 1.5 Subtracted From Stretched 1.5 Subtracted From Stretched 1.5 Subtracted From Midnight Chali Hu Is The President Of But Not We Elected For The Summation Of Despair Well 24 Number Plus One Quickly Swallow One Side Subscribe 12512 Chapter Video then subscribe to the Page if you liked The Video then subscribe to the Incompetent Execution Logical Sidewalk Water Problems If You Still Have the Intoxication of Both Girls Residential Coding and By
|
Minimum Time to Type Word Using Special Typewriter
|
find-customers-with-positive-revenue-this-year
|
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`.
Each second, you may perform one of the following operations:
* Move the pointer one character **counterclockwise** or **clockwise**.
* Type the character the pointer is **currently** on.
Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`.
**Example 1:**
**Input:** word = "abc "
**Output:** 5
**Explanation:**
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
**Example 2:**
**Input:** word = "bza "
**Output:** 7
**Explanation:**
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
**Example 3:**
**Input:** word = "zjpc "
**Output:** 34
**Explanation:**
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase English letters.
| null |
Database
|
Easy
| null |
201 |
hello this time we are going to take a look at question 201 bitwise and of numbers wrench in this question were given a range M in where n is in the range of 0 to 2 1 4 7 4 8 3 6 4 7 I think that's the maximum integer you can get and we have to return the bitwise end of all numbers in this range inclusive to do this we can do it as problem describes like we really do a bitwise operation of all the numbers in this range but that will be inefficient and we don't have to do it after we observe the pattern so the pattern is and there is a position in the bit form that to the left of that position every number every bits will be the same and to the right of that position every bits will be different but the after we do a bitwise operation to all those numbers the right part will only be 0 so the key point of our solution is to find out that position so let's see how we can code it but before that let me use an example so you can understand what I'm saying so for example M is 20 and n is 24 and we have to find out the those numbers from 20 to 24 21 22 23 24 and 20 number 20 is 1 0 1 and 0 1 0 and now the 21 is 0 1 and 0 1 so you already see the pattern so there are the little ones always the same so this is the position so the first 4 bits is always the same and the last 4 bits is always different but after we do a bitwise operation they will become 0 oh so you can see and after I finish this so whenever you keep going just to illustrate this idea so you can see every column there is at least 1 0 therefore the after you do a bitwise operation to all those numbers you eventually get a big 0 so this question becomes a lot simplified so what you need is to determine the position that so to the right of that position every bits you just don't have to consider it you just think that is 0 because it's going to be 0 after those operations and so the final result will be decided by the first a few bits that's to the left of that position ok so we get the idea now how do we code it so first we need account so we can know like what the position is and we use a while loop when M is not equals to n this wire loop is going to keep looping and so how this is going to work is that M is always going to be do a bit shift to the left no sorry to the right and n is always going to do a bit shift to the authority to the same direction as well and every time we do that we add we increment our count so we know that and that position is what's the position then at the end when we return we always we give back that position so we shift in or in that doesn't matter because they will share the same first for first few bits and we shift them to the left then all those numbered autos number to the right of the position will be 0 so the key point of this problem it is we have to observe the pattern and find out like eventually after we do all those bitwise operations so there will be a position so to the right of this position every bits will be 0 so this it's pointless to calculate them and to the left of the positions that's what matters and then so we only need to find out the right part which we don't we also don't need to calculate them because they are the same for every number and then we replace all those bits behind them to 0 then we get the final result
|
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 |
54 |
you remember those problems during your early programming days where you had to print something in form of a star in form of a ladder or something in form of a rectangle right there were so many different patterns and you just experimented with four Loops to get to that answer correct such is a problem available on lead code spiral Matrix and trust me personally I believe that this problem does not test any of your problem solving skills or it does not even test how value code but still I have found that it is asked if so many coding interviews and it is one of the interviewer's favorite so today I'm gonna explore this problem a little bit and work towards an efficient solution Hello friends welcome back to my channel first I will explain you the problem statement and we'll look at some supportive cases going forward I'm going to discuss something like how is this problem important and why do interviewers ask it after that we are going to solve this problem step by step and we will also do a dry run of the code so that you understand and visualize how all of this is actually working in action without further Ado let's get started so first of all I want to quickly make sure that we are understanding the problem statement correctly in this problem you are given a m cross n Matrix that means this has M rows and N columns correct and now you have to return me all of the elements in a spiral order so first of all what if a spiral order actually mean spiral is a pattern that looks like this correct so given our Matrix in our test case number one a spiral order will look something like 4 8 15 42 1 7 50 16 and then 23 right so all of the elements should appear in this order correct similarly in our test case number two you can see that it is not necessary that the Matrix should be a square Matrix you can even have a spiral order in a rectangular Matrix so in a second test case the spiral order will look something like this 1 4 7 10 11 12 9 6 3 2 5 and 8. because that is how a spiral order actually works so for a second test case my answer would be correct so you can see that both of these are in a spiral fashion right now if you feel that you have understood the problem statement now in a better way feel free to first try it out otherwise let me go into a little bit of discussion and see what makes this problem so important for all of these interviews so to keep things interesting I am taking a bigger example this time you can see that once again I have a matrix and in this Matrix I have six rows and five columns now personally speaking I have never understood why this problem is so important and why this is even asked in the interviews but from my experience as an interviewer I have seen some people and I have seen the common mistakes that they make and that made me realize okay this could be some problem which can assess how the candidate is actually thinking so first of all when I give this problem to candidates the first problem that they have is okay what do you actually mean by a spiral order so a spiral structure looks something like this right it will have consecutive inner rings and it will end at the very last element so sometimes people will simply fail to understand what you mean by a spiral order they will try to iterate the element in this fashion and then they feel a lot of problem like okay how do I even get to all the elements so that is the first problem so once you understand that okay a spiral order will be starting from all the edge elements and then going all the way inside so this is how a spiral order will look like okay now the next problem that I have seen candidates faces they do not know how to start to iterate this array because as you know the conventional way of iterating a 2d array will be a row wise manner right either you will go row by row or what you can even do is you can go column by column right but now what you have to do is you have to Traverse a row first then a column then again a row in the reverse Direction then a column in the reverse Direction so this gets a little bit confusing and this is the second point which I have often seen people facing a problem with next now even if they try to figure out that okay this is how they have to iterate then they will try to come up with all sorts of patterns and try to figure out a solution sometimes what they will do is okay they will first try to Traverse through the outer ring then they will go through the inner ring and then they will iterate through the innermost ring and that approach once again becomes complicated because you do not know if it is a square Matrix if it is a rectangular Matrix and then how do you manage all of your variables for these are the primary three problems that I have often seen candidates facing and I have often seen that okay candidates will try to rotate this array at every instance and then try to come up with a solution but I'm here to tell you that you do not need any of these approaches this problem is actually very simple and you just have to proceed in a very straightforward way the way you are iterating and printing all your elements in a spiral order so that is what we are exactly gonna do so what I have over here is my original Matrix that has six rows and five columns you can see all of these are my row indices starting from 0 all the way to 5 and all of these are my column indices starting from 0 and all the way up to four so now you know that you can refer to any element in your Matrix for example the element at Row 2 and column 1 will be 12 right for now you know a way to refer to each and every element in your 2D array correct you have to begin somewhere right so I'm going to initialize some variables so column begin will be defined at 0 because this is your beginning column and column end will be defined as 4 because this is your end column similarly you will have two more variables row begin which points at 0 and row and which points at 5. so these two variables are defining your beginning row and the very last row correct now you have to begin iterating so first of all what I'm going to do is I will start a while loop and this Loop will have a certain condition that row begin should be less than row N and column beginning should be less than column ending so that is how you will start your while loop because you have to iterate through every row and every column correct and now comes the fun part how do you Traverse this in a spiral order you will start from the first element and then first of all you will Traverse right correct so that is exactly what we're going to do over here we Traverse right and then we will start a for Loop that starts at column begin and ends at column end so you know that the row begin is 0 and you are running a loop that starts at column begin and ends all the way up till column end so what you're doing you are traversing the first row of your Matrix right so when you will Traverse this and you will print out all the elements you are going to print out one two three four and five right so what did you just do you took care of the beginning row so incidentally what we'll do next we are gonna do row begin plus because we are done with this row right for now my row begin will point at row number one and continuing our approach of spiral order what we have to do next now we have to Traverse this column now right in a way what we are doing is we are traversing down right and just look at this for Loop in this for Loop we start from row begin that is the first row and we end that row end that is the last row and we are going in a downward direction right so when this Loop will run you are gonna iterate all of these elements in a downward direction that if 10 15 20 25 and all the way up to 30. now we took care of the last column all of these elements are now covered right so naturally what we're gonna do we are gonna do column end minus and this will take my column end one value previous because you can see that okay I have covered all of these elements right now you may be able to see right what is happening going forward with that spiral order fashion what you have to do now you have to Traverse in the left direction right and that is exactly what we're gonna do we are gonna Traverse left and then now look at this for Loop that I have what do I do over here I start from the column end that is I'm starting from this column and I am going all the way up to column beginning right over here and I'm doing a minus that means I am going in the backward Direction so when this Loop runs what will it do it will print all of these elements in the reverse direction right so you are gonna get 29 28 27 and 26. and now what did you just do you took care of your entire row end for naturally what do we have to move this row and one value up right and that is exactly what we do a row N minus so you can see how we are doing everything in a spiral fashion right now you must be understanding what you have to do next you once again have to go in the upwards direction right and you have to start at row end and you have to end that row beginning so you can understand what we are going to do in the next Loop right just look at this Loop we Traverse up and in this Loop we start at row end and then we end at row beginning and then we do a j minus that means I am going in the upward direction right so when this Loop runs it will start to print all the elements from 21 16 11 and then 6. and at the same time what did you feel you see we have taken care of all elements in column begin so naturally we have to increment its value and now column begin 0.21 column begin 0.21 column begin 0.21 and that is exactly what we do by doing a column begin plus so this might give you some idea what will happen now when this Loop runs again once again you will Traverse right and then you are gonna cover seven eight and nine and then you are gonna Traverse down which means 49 and 24 going forward you will Traverse left that means 23 and 22 and at the very last you will Traverse up so 17 and 12. so you see right we are doing all of this in a spiral fashion right so this Loop will continue and at the very end you are gonna stop at 18 right and you might be wondering what are these two conditions so these two conditions are just sanity checks so that you do not encounter into index outperformed exceptions because you have to stop somewhere right the value of column begin cannot exceed column end and similarly the value of row N cannot exceed row begin right so this is how your code structure will look like you can say this to be a pseudo code of some kind and you can implement it in any language of your choice it could be Java it could be python it could be JavaScript right and however if you want to look at the full code along with its def cases you can find a link to my GitHub profile and it has everything the time complexity of this solution will be order of M cross n because we are traversing through every element and the space complexity of this solution is order of one that is because we do not take up any extra space to arrive at a solution I hope I will be able to simplify the problem and its solution for you as per my final thoughts I just want to reiterate that this problem does not test any of your problem solving skills or any of your coding ability it is just representation of how clearly and logically are you thinking when an interview gives you such a question sometimes you just need to follow the instructions step by step you saw this right you did not have to over complicate it you literally have to Traverse the entire Matrix in a spiral way and that was your answer in fact right so while going throughout the video did you face any problems or have you seen any of the problems which may seem that hey why am I even following this but they ended up being asked in your coding interviews tell me all set problems and any of the problems that you had 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 follow next until then see ya
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
714 |
hey everybody this is Larry this is day 22 of the legal Daily Times hit the like button to the Subscribe and join the Discord let me know what you think about today's forum and it seems like it's the classic tradition oh yeah I mean uh Lisbon right now in Portugal uh yeah this is the classic uh buy and sell start with this time of a transaction fee I already have a video on this but let's go away very quickly um I think the key thing is that I think a lot of people especially as a beginner um try to do everything at you know at the same time uh the way that I always like to do it I like to explain it is by just separating out the states as um yeah the states as much as you can and here um the thing to separate out is the buy portion and the sell portion right and the transaction is the transaction fee you only pay once for one completed transaction so you can pay it on the buy you could pay it in the cell as long as you're consistent in that double paying it should be okay so let's get started uh so the buy statement what's the buy stage that means that what does it mean uh that means that okay so the day and day is enough right and basically we do not hold a stack or dirt stock and on I've day right we can choose to buy and here we have two choices right so if day is equal to N I just think we went off prices then we're done right we're done we Return To Zero is the profit and then otherwise we're going to choose two things you can choose to buy or you could choose to sell right or sorry you could choose to buy or you choose to just skip ahead and bye uh you know let's just say though we buy the stock today right so then what does it cost it costs prices of day plus fee so that's the cost right so this is the cost that we pay and then the most optimal for that is that if we sell it on date plus one or afterwards because sell it's not this is in the cell on that day is to sell on that day or afterwards right so that's basically uh yeah by buying as you go to this and then not buying it's just you go to Pi of K plus one maybe right but today and then we return the max applying and not buy similarly uh we can do the same but selling one day it will be times zero uh otherwise we sell selling is equal to so we sell we can choose to buy it on day plus one and then we add the prices of the day because that's the money that you get back after selling and I'm not selling you just you know maybe sell on day plus one okay with a massive selling that's done and that should be pretty much it and then we need to return buy of zero and that is like ninety percent of the way done uh those of you who knows how I do it uh now we just have to add memorization noting that this thing for the same input for the same day input is gonna be the same every time so yeah uh the way that I like to do it for teaching reason is just by separating out the has portion and then the actual uh the value portion right and then here everybody has cash okay then we return by cache of day uh otherwise we set up the cache and we should be good I'm so tired say that a lot though still true I just need to stick more maybe and yeah so now that means that we can do it in linear time and linear space and that will be pretty custom optimal so yeah hopefully I why is this taking so long to judge hopefully that's right um if not then I it takes so long okay I messed something up what is n i mean n doesn't matter because we're linear right I actually don't know why just time's up um that is weird all right let's just test case let's find it real quick do I did I have a typo somewhere oh the cell I forgot to actually use this in cash uh I'm like I said I'm very tired oopsy daisies but it's now we demonstrate what happens when you don't cash by the time we see that one and again this is pending see much faster it's just that took a long time to actually get food but yeah another way hit submit it should be good sorry that I'm watching a little bit of time to mix it uh yeah back streak linear time in a space that drive for today let me know what you think stay good stay healthy to your mental health uh take care and I'll see you later bye
|
Best Time to Buy and Sell Stock with Transaction Fee
|
best-time-to-buy-and-sell-stock-with-transaction-fee
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,3,2,8,4,9\], fee = 2
**Output:** 8
**Explanation:** The maximum profit can be achieved by:
- Buying at prices\[0\] = 1
- Selling at prices\[3\] = 8
- Buying at prices\[4\] = 4
- Selling at prices\[5\] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
**Example 2:**
**Input:** prices = \[1,3,7,5,10,3\], fee = 3
**Output:** 6
**Constraints:**
* `1 <= prices.length <= 5 * 104`
* `1 <= prices[i] < 5 * 104`
* `0 <= fee < 5 * 104`
|
Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
|
Array,Dynamic Programming,Greedy
|
Medium
|
122
|
417 |
show you how to solve legal question 417 pacific atlantic water flow it's a median legal question it's also a very classic and uh high frequency question and this is basically they give you an island grid if you look at example here and there's pacific ocean at the italian atlantic ocean and if you look at here pacific ocean is on the top left side and atlantic ocean is on the right and a bottom and if the island is partitioned into grid of square cells and you are giving mn of the heights where the height is defined height rc represents the height above sea level of the cell at coordinates rc so basically this cell is two above the c and three above the c5 above the sea so it tells you that these are the value above the sea the island receive a lot of rain and the wind rain water can flow into neighbor cells directly from north south east west if neighbors cell height so basically it tells you it goes four directions instead of like all eight directions with the diagonal so you can't for the three you can only go up right down and the left and if the neighbor's cell's height is less or equal to the current cell's height water can flow from any cell adjacent to an ocean into ocean it's really confusing here but basically what it is that you see that they give you the heist information here is the output here right and these numbers the above the c level number are the answer like if you look at 0 4 it's basically this 5 and the what it asks you to find is less or equal to the current sales height so that means that it asks you to try to find a number five which is a number higher than the left number or uh right number that to allow it to flow to the ocean and for example like this four and it could flow to the uh pacific ocean is because four is bigger than three and four could excuse me can also flow into the atlantic ocean it's because it's equal to four basically these numbers are all like this five is all bigger than the other numbers that along the way when they try to flow into the ocean and if you look at a seven and it's the same thing and also this number it can float into both pacific ocean or and atlantic ocean so your goal is to write a function to return a 2d list of grid coordinates results when result i equals to rc denotes the ring water can flow from cell rc to both pacific atlantic ocean and this the highlighted cell like five four five these are the answer so looking at this question um and then they also give you another example here and these are the answers there are some constraints here and this is a question asked by google ten times over three times in the last six months so it's a very um important question that you need to understand looking at this question here um what i'm thinking is that the first idea is that we want to make sure we could totally use that for search or buffer search or whichever way that you prefer to solve this issue if we're using buffer search we probably want to use a queue to pop the neighbors if you use that for search it will just continue to do the death research on its neighbor and we also wanted to define two hash set for the pacific ocean and for the atlantic ocean to make sure that we don't visit the same cell again if we have already visited the cell so for the main defer search function we want to add each cell that we visit into the different search function and once we do that we want to do calculate its neighbor calculate the new neighbor right and we want to do some condition check if they are meeting all the requirement then we want to if like they're inbound they have not visited before and also if they're old they're bigger the numbers are bigger than the along the way that when they flow into the ocean then we wanted to repeat the developer search on these neighbor cells as well and then after that what we wanted to do is run the data search um called that research function on each cell and in the end we want to return the result that the rc that are in both pacific at atlantic oceans hashtag so then we get the answer i'll show you how to do this in code so first we want to roll out some edge cases if not heights or not heights zero then we in this case then we just simply return empty right and then we want to define the rows and calls first and land of heights right this is how you define the um you can also use m or n like it mentioned um heights and a zero right and then like i mentioned i want to use our pacific ocean at atlantic ocean um visit that to keep save all the cells rc that we have already visited before and i want to define a defer search function and for the defer search function i would have passed the parameter as r c another important parameter is basically the visit set and the at the folder cells that i have already visited basically the pacific at atlantic ocean so just call it a visit here i basically ask the visit set and i'll before um first thing when i start the diver search function i want to add the rc to the visit set first all right so then the next step i'm going to do is calculate whatever cell that i visited its neighbor in all four directions so for the rdc in all four directions 0 minus 1 0 1 one zero minus one zero right so that's in four directions yep that's that looks right so i'm gonna calculate the new row and columns uh correct the position and the row column is basically its original value r plus dr and c plus cc so i'm gonna add this value and then i'm gonna do a condition check so if the new row is out of bound or call is out of bound or it's bigger than the entire rows or call bigger equals calls or um let me move this a little bit yeah or um i have already visited the road call in visit already all the heights row call the roll call if in the answer that we're trying to look for is bigger than the original rc right but this is a condition check that we want to rule all the cases so it should be smaller if that is the case what do we gonna do what we're gonna do is continue we just continue to the next cell right and then after we go through this outer boundary scenario all these scenarios that we want to continue on for the rest sale that meets all the requirement what we wanted to do is actually run the diver search function on the new row and the new column and the visit set right that is the main part of the defer search function then i'm gonna call the that first search function for r in range of uh rows sorry and so when i run that first search on the row and i'm gonna run this is how you do it and that's basically try to run it on every cell right and the row is always for r in range row is always r and then the call could start from zero or the last call which is calls minus one and if you look at our zero so any rows and the colon is zero it's actually pacific ocean and the last scenario if it's any row and that the call is minus cos minus one and the neighbor is bordered at the atlantic ocean so for the force for c in range of calls so this is i'm calling the diver search function on the colon so i want to start with zero row zero and the column right and then row zero column and you can see it's still pacific ocean and the diver search function and this is rose minus one basically the last row nsc and it's atlantic ocean and this is i'm calling all the diversif search function at this time the atlantic and the pacific ocean should have the answer that i needed already but what i'm looking for is the answer that is in both pacific and atlantic ocean so i'm gonna assign there and the result i'm gonna return like this and then i'm gonna do a 4r in range of rows so i'm gonna for c in range of calls so basically every single cell that if this rc in the pacific visit set after running the dafa search function right calling the developer search function and rc in the atlantic visit set as well what i'm gonna do is rest a pen so i'm gonna append the rc into the result and i'm just when i uh go through the heights this grid thing i'm just gonna continue to append the result and after this entire for loop what i'm going to do is i'm going to return the result and that's it for the code let's see yep accept it and i hope this is helpful and please like my video and subscribe to my channel and i'll have more legal question for you coming up soon bye
|
Pacific Atlantic Water Flow
|
pacific-atlantic-water-flow
|
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105`
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
| null |
156 |
hey what's up guys this is sean here so today uh let's take a look at the lead called problem number 156 binary tree upside down so this is not a tree problem you know so you're given like a root of a binary tree and you need to turn the upside turn the tree upside down and return the new root so the way you're turning the where you can kind of rotating the tree is that you know for example you have this one right so basically the new root will be the left child and then the new roots left child will be the current root right the right trial which is z right and then the new roots right child will be the current value so that's why after the rotation or after the turns right after turnings right so the new tree will be comes to y c and x and here we have some more we have another examples here right and it says that you know the steps are done level by level which means that each level will do the same thing and also that you know on each of the node right it's guaranteed that we have zero or two child so the reason being is that you know if the child if the node only has one child for example this one you know then we cannot rotate this one or we cannot turn because to turn a tree right upside down we need three nodes and yeah so that's why you know for this one no we have like these examples here right so we if we turn the tree upside down layer by layer so the first layer will be the left most node because the left most node will be the new root for the new tree right because the left one will always be the new root so if we traverse it all the way to the bottom then the leftmost node will be our new root so that's why the new root will be four and then after that we are rebuilding the links of that so here is just one of the examples actually so maybe a more complete example is like this right so this is like complete tree so if we're trying to use this one you know similarly right after rotating the tree here basically so again this one will be the new root here right and then after this one the new edge will be like this so this and this one is gone this is gone and then this is the new root the new edge right this is gone okay and so one more thing is that to be careful here is that you know so this part right so for this part it didn't change at all because the rule to rotate the tree is that you know uh for the z here right so basically this is the z part for the z part we just move it uh to the left and we don't recursively do the uh do the rotate for this part because it doesn't make sense because again right so the tree can only has one root right if we do recursively try to rotate this part so what we'll have like this one we'll have this one as another root maybe and this one will have like this one right obviously this is not a tree right that's why you know we only uh rebuild the hydras for this part and the for the g part we just leave it as it because we cannot have multiple roots that's why would there we just won't uh do the rotate for the right subtree only for the left subtree and that's the that's one thing we need to be careful here right so okay so and since we have decided that we're gonna do the rotate for the left subtree only so the first thing first is we have to find the new root for the entire tree which is the left most note okay and after finding that we have to some we have to rebuild uh rebuild this uh this relationship layer by layer okay and assuming we have this one we have one two three four five right so let me try to draw this one here one two three four and five okay so we recursively call the left uh the dfs on the left node so at the beginning where we are here and then we are coming to here and then we are we were at four here right and whenever there is like no child on the car no left child on the cart note we simply return the current node because that will be our new route so this new root will be four so now we return this four back to two okay so the new root is four and the current is two right because the new route will be the route will be uh returning all the way to the top so now we have the new route we have the current right so what's left we have so what's left we need to rebuild the uh basically we need to rotate the tree right so which means that we have to rebuild the edges from four to two and five and then what is four so four is current dot left that's four remember so two is a current right and to build the address we have a current dot left right so what's this one that's this edge right so this add what's the five is current dot right so that's the left how about the right one so we have a current dot left dot right so what is the right it's just to happen happens to be the current which is two and then after that right as you guys can see here you know we have some unnecessary edges here right because we have two to five and we have two to four which means that we need to remove those two edges right so we just need to do a current dot left equals to none and also the current dot right equals to none so that's basically what we need to do on each of the recurs uh dfs recursive call here and so the reason being we use the current left not the new route right it's because you know if we try to do a new route dot left equals to this one you know when we are at one here right when we add one this is the current so what's gonna be the dfs return from the previously curve it's also four right because we remember we're only we keep returning this new route back to the top if we use the new route to calculate that to rebuild the edges here you know which is right because now we're trying to rebuild ads for two to one two to three that's why we need to use current.left to find we need to use current.left to find we need to use current.left to find the current level that we want to rebuild right um yeah cool i think that's it right so we can start coding i guess and this one so the code is pretty short actually so dfs right so ninety-nine percent of time dfs right so ninety-nine percent of time dfs right so ninety-nine percent of time when you see a tree problem it's a dfs so return df as root okay so if not uh current dot left right basically if there's no child for the current one we simply return the current and else the new route will be the dfs of the current dot lab so these two lines here this few lines here will guarantee that you know we will always return the uh sorry return the new route in the end so this few lines will guarantee that now we the dfs will always return the new route which is the left most node okay and the remaining part is just to rebuild the uh the edges right for those for the trees so like i said the current.lab.labs so like i said the current.lab.labs so like i said the current.lab.labs is current dot right similarly current.left.right current.left.right current.left.right equals to current right and then we need to remove the old ad to avoid a cycle in the tree so that's that and since we have this kind of special edge cases you know uh and we're not uh handling the non current here because if the root is none right so we if we do a current dot left we'll get the narrow exception that's why we can just handle this special case separately so if the root if the tree is empty we simply return none yeah so yeah i think that's it right so if i run the code accept it submit yep so i guess for the times time space complexity it should be pretty straightforward right so we have dfs i think it's going to be a log n time complexity because we'll be calling these things i think at most log n times and yeah depending on the tree right so if it's a balanced tree uh it's log n time so but for the worst case scenario so the so what is the worst case is like this uh we have this one because each node can only have zero or two right so i think this is the worst case right uh we have this one yeah this is the i think this is the worst case scenario so um yeah i'm not sure the time complexity for this kind of unbalanced tree here and yeah maybe i think it's i think if the tree is like this one i guess it's close to n instead of log n because this one is it's not like balanced tree right so i'm not quite sure about time complexity to traverse the uh i mean the height for the for this tree so maybe log in yeah cool anyway i think uh that's everything i want to talk about for this problem and yeah i hope you guys like it thank you for watching this video guys and stay tuned see you guys soon bye
|
Binary Tree Upside Down
|
binary-tree-upside-down
|
Given the `root` of a binary tree, turn the tree upside down and return _the new root_.
You can turn a binary tree upside down with the following steps:
1. The original left child becomes the new root.
2. The original root becomes the new right child.
3. The original right child becomes the new left child.
The mentioned steps are done level by level. It is **guaranteed** that every right node has a sibling (a left node with the same parent) and has no children.
**Example 1:**
**Input:** root = \[1,2,3,4,5\]
**Output:** \[4,5,2,null,null,3,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree will be in the range `[0, 10]`.
* `1 <= Node.val <= 10`
* Every right node in the tree has a sibling (a left node that shares the same parent).
* Every right node in the tree has no children.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
206
|
153 |
all right let's try to solve question number 153 fine minimum in rotated sorted array we're gonna read the question come up with a couple of solutions trying to analyze our solutions and see which one we should code up we probably think about the most optimal solution and that's the one about the P coding up suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand for example you're a regionally is zero one two four five six seven might become four five six seven zero one two three cool find the minimum element so pretty much find the smallest thing okay that's it sounds easy you may assume no duplicate exists in there arraign great I don't the chance for like some edge cases great so in this question it seems pretty simple you know find the smallest value in the input rate right with a caveat here though so when we analyze the question a little bit more sometimes we would understand like well if it's just simply you know find the minimum element in you're giving an array that's pretty simple right why bother mentioning all these other points well some of these other points is actually there to help you optimize your question to be even more efficient right so let's try to first of all come up with some of the more naive solutions first right so to reiterate this question is simply your given array that rate originally was sorted and then it got pivoted at some point par verb you know in this new semi sorted pivoted array far the smallest element right it seems relatively simple right one of the solutions you may think about is like well maybe I could just simply iterate through every element of an array for example I would I can iterate through four or five six seven zero one two three and just keep track to see what is my smallest value right I can just create a variable pop in a value there check it as I area through everything and boom I'm done right find the minimum value now what is the time complexity of that particular algorithm right if you need to iterate through the whole thing you know and store something and iterate and then compare it that's all of n time complexity right with a I would say o of one space complexity because you only store in that initial variable so space is pretty good right and time generally speaking of n is good but let's see if we can actually try to solve this problem even better well if you think ever so slightly maybe the question you know so what I like to do sometimes is like okay we know that would be the brute force way of solving it maybe there's a way I could solve this in a more you know smart intelligent way right and another way you can think about solving this is that well why not try solving it with the cute one liner right I can simply just go here and return something that's called math dot min right and I could just simply spread gnomes right and that should probably solve or give me my solution right let's see if this flank is meeting my solution yeah it does give me my solution and it's pretty darn fast to write however that is also a ton complexity o of any time because effectively this is simply the same thing as Boeing using a for loop going in comparing everything and that doesn't really solve a problem with the most optimal thing so what can we do so this is where we start looking at the description and one of the couple of elements that they were highlighting right we know certain patterns of our input right we know the pattern is that it's going in ascending order originally so sorted in nature so we know that the leftmost element would be the smallest the rightmost element should be the greatest if it were not pivoted right so that's one attribute that is very critical it's really key it gets good information so one thing we could think about is like okay what can we do in this particular array that would shorten our time from oh of n to something smaller like perhaps log n right so in any log n type a solution you always have to think about can I solve this problem by always making my element smaller and smaller as I look at it right or at least look at it in a half context right or at least start from the midpoint of every element and then reduce my array from that midpoint right so that's something that we could think about and if we were to improve it to the next step then we may need to do something of oh of log and right and in order to do that you can only think about well worth what's what can we do we could do a binary search sheet above algorithm to see if we could find the late least amount number right yeah I think we could do something like that right so what that really means is that okay well all I need to do is ensure that my point of reference is comparing to like something in front of me if it's gonna be greater than that particular element then I can just readjust my boundaries right so what I mean by that let's look at some code and maybe you'll understand a little more so when we look to diplomat some sort of binary way of searching for the lowest value we want to establish like two boundaries right so we want to put a left segment and the right segment so let me just create a left will equal to starting from the zero point as an example you'll be at that index 0 and then left let my right will equal P to be this particularly elevate on the right so I'm gonna go say numb stop length minus one right cool now what I'm gonna do is ensure that my left index is gonna be less than my right index so what does it mean I'm gonna be changing my left and right index based on how I compare things that's what we're gonna try to do but before I do that let's actually create a midpoint right so in any binary thing here so let's go midpoint to remember what we mentioned earlier what we're trying to do is trying to reduce our iterations so it's log N and in order to make it a log n thing with ensured that every time we adjust our array that we keep analyzing it should be smaller and smaller so you can skip certain things if we know roughly how the array looks right so we're gonna create a midpoint and gonna call math.floor from the left right plus math.floor from the left right plus math.floor from the left right plus right / - that's my midpoint right so in right / - that's my midpoint right so in right / - that's my midpoint right so in this case it's like the midpoint right here right cool and what we want to do is check whether or not my numb point at the midpoint is going to be greater than my nums at my right point right what does this do so before if this is greater than my right point for example if I'm in the middle right and my right point is to the you know to this point if I know that this is greater than this then I know effectively this is not my left I should I adjust my left right but if it's not then we should Charlie change the right to the midpoint right so I'm gonna do here it's gonna be left will equal to midpoint plus one right so what that really means is that okay cool I if I know that this is greater than this right because our idea of things going in a sending order right if my value here is greater than my most value that I know for a fact that my next value can potentially be the solution that I'm looking for right because think about it we're talking about ascending order right so meaning that our leftmost part would be smallest my right post part would be highest right so this is something for us to check that and then otherwise I'm otherwise if that's not the case I'm going to change my right to equal to the midpoint all right so what this really does is that okay if my if this for example if this was the value that was being checked at me if I know it's not the midpoint but for argument's sake if it was and if we're checking my right mmm okay there's nothing but best examples show that but okay let's just show something like this so for boom my right will just become my midpoint and you're gonna move this point back into here right so those are for the cases where your zeroes are gonna be more closer to the front segment that deals with this point this is more when it's more towards the tipping point it's doing more to the roots right all right cool so we're going back into here return the actual solution which is gonna be your left are you know right boom so once you've gone through everything and these mix the condition then a fifth of the EQ should be will solve the problem right here and this should be the solution all right cool so sometimes you may ask yourself like why even though in theory this is a better efficiency why do I get less you know less time on here right so like I wanted to tell everyone you know don't pay too much attention to how fast this is not accurate or that accurate right but the better it's more important to understand your actual algorithms itself to understand like what you're doing and to see with your and when you're analyzing see the space complexity time complexity and that should help you move forward and not focus too hard on like oh I'm faster than X 1 percent because that really it really there's lots of things to consider the latency extra et cetera if this were to be accurate you know if I were running again then I should be getting the same value right which in this case it will not do so I'll put submit again just for you for argument's sake but I got a different one year sixty eight point seven one and then 86% it's like it goes seven one and then 86% it's like it goes seven one and then 86% it's like it goes all over the place just to prove a point okay so any point focus on your solution and not some and understand your time complexities from that solution and not focus too much on the actual like milliseconds etc from that point okay hope you find this video helpful if you liked it please add a sub on my next video and we're trying to do something more what my audience asked for which is described what recursion is all about so if you guys want a little more stay tuned I'm probably gonna release that sometime this week as well and yeah I'll be like it base
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
2 |
hello everyone welcome to day 12 of january lead code challenge and today's question is add two numbers uh it's a simple question we are given you in which you are given two numbers in the form of a linked list the digits are present in the form of a linked list and you need to add those two numbers and return the a new number again in the form of a linked list let's walk through a few examples uh 2 4 3 5 6 4 when you add 2 plus 5 7 you get 4 plus 6 is 10 0 1 carry above and then eight the new number becomes seven zero eight uh both of since all the numbers in reverse order you can reverse it but not needed as part of the question and what you need to return is the reversed number itself uh and hence 708 is the link list that you need to return 7 being the head of the linked list without much ado let's quickly walk through the algorithm that i have created and let me just start the slide show so let's i have taken a bigger example than what was specified in the question so as to cover all the cases but just before jumping on to this uh if the first linked list is null return linked list two if it is null return link a second if second is null return the first linked list it's always good to write corner cases in the interview because it tells the interviewer that you have the ability to think about all the possibilities that are happening around if you don't do that it gives it slightly leaves a negative impact because uh you are not able to come up with the corner cases which is very important in any interview that you give so now let's go for the case where l 1 and l 2 both are not null and as the first rule of interview it's a linked list question what we need to do we need to create a dummy pointer with the value minus 1 being a dummy pointer indicating a dummy pointer and we will use this to store the head of our new linked list so let's start this is l1 and this is l two so three plus nine three plus uh six is nine so you get nine you create uh the if you establish the link it's less than 10 uh you so the new carry is 0 because there's no carry value because it is less than 10 and you also need to take care of the thing that whenever the sum becomes greater than 10 its actual value will be modulus of that sum so sum will be equal to uh the sum would be equal to some modulus 10 because uh this is what will be actually stored in the new linked list as a value let's move ahead so we connected nine and the carry is zero so we can maintain a carry variable and let's add so 4 carry plus 4 plus 7 it's 11. some would be 11 modulus uh 10 which is 1 so we get 1 and carry would be 11 by 10 so carry is 11 by 10 and you establish the link from nine uh till one and you increment the less pointers so l one gets here l two gets here and let's move ahead now we have carry as one l1 is this l2 is this so 1 plus 7 is 8 eight plus five is thirteen so uh thirteen modulus ten gives us the new key value which is three and carry would be thirteen by ten which is one so you get one again so you carry becomes one the new sum will be also we will increment l one and l two so the new sum is one plus 2 plus 9 which is 12. so 12 modulus 10 gives us uh 2 is the new value and 12 by 10 gives us the value it gives us a new carry which is one since uh you so you establish this links and this becomes null this also becomes null now comes an important tricky case if there is a carry value which is equal to 1 and both the linked lists are nullified by then you simply add a new element the value of the carry to your linked list and get it pointed something like this what i have done here so this is very important point which usually people tend to miss out that they forget to update the last carry because that's the remaining portion of the summation that we established and did so this is how we came up with the algorithm and what is the time complexity of this approach time complexity is equal to the length of m plus m order of uh maximum value of l1 comma l2 the length of first number and the second number so max of that will give us the time complexity of this approach what is the same space complexity of this approach uh the number of digits in the new uh some summed number the number of digits in the resultant number gives us the space complexity so again space complexity would be equal to max of l1 comma l2 length of l1 comma l2 plus 1 though but that's constant so we can ignore that without much to do let's quickly code this up let's start with the corner cases if l1 is null return l2 if l2 is null return l1 and let's generate for the other case where both of them are not null what we'll do we'll create a dummy pointer which is the thumb rule for every linked list question and initialize a value minus 1 there and let's keep a new iterator for this pointing to dummy so what am i going to do if l1 is not equal to null and l2 is not equal to null tell the name both of them are not null let's calculate the sum so also we need a carry variable carry is 0 integer sum is 0 and sum equals to since both of them are not null l dot val plus l two dot val and let's create uh the new linked list node new linked list and what will i assign the value to it some modulus 10 and what will be the carry will be updated to sum by 10 also i forgot to add a carry here so carry is very important never forget carry because it can cause trouble for you and once we have done that let's assign the nodes so i t dot next the iterator dot next will point to the new node i t equals to i t dot next and l one equals to l one dot next l two equals to l two dot next simple or just updating the next pointers once we are done with this logic uh we need to do a similar kind of a process uh for the linked list which is remaining in nature how we will do that simply copy paste uh the node what we have written above remove l2 for the case l1 is still there l2 is null and remove everything related to l2 we are done again let's do a similar kind of a thing simply copy paste and for the case when l1 is null while you have still have elements in l2 just remove everything related to l1 so l1 goes now the last part the tricky part if we still have a valid value of carry if carry is still equal to one what we'll do we'll decide we'll create a new node with the value one because uh both of them uh less both of the values are null both of the lists have been completed reversed and you will connect establish the connection pretty simple return dummy dot next looks good it works and let me just submit it accept it let's quickly talk about the time complexity of this approach dci dc and sc as i said is order of max of a length of l1 comma length of l2 similarly for the space complexity because this is what how this is these are the number of digits that will be there uh in the your answer plus one for the carry part but you can ignore that thanks for watching the video hope you enjoyed it
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
70 |
Hello friends welcome back to the PM softic Solutions basically in this session we will going to solve lead code problem number 7 is climbing stairs so without further delay let's go to the dashboard and try to understand the problem statement the statement says that you are climbing a staircase it takes an step to reach the top and each time you can either climb one or two steps and how many distinct ways can you climb to the top so uh to solve this problem we will going to use uh dynamic programming and uh the idea is to build up uh the number of ways to reach each step starting from the bottom so uh we will going to use an array to store the number of ways to reach each step and then we will going to iterate through the steps to the calculate the number of ways to reach each step based on the previous steps so let's uh Implement uh this code first of all uh we will going to apply some uh base cases uh here you can see we can either climb one or two steps so first of all we will going to check that if n will be 1 or two then we will going to Simply return one and two so if n is equal to 1 return one and if n is equal to 2 then simply we will going to return two now let's uh Implement uh the mo main portion so uh next we will going to initialize variables to store the number of vs from the previous two steps so for that uh let's create a variable previous one is equal to 1 and previous 2 is equal to 2 let's also implement the comment so that you can understand that what we have did so we are going to initialize variables to store the number of vs for the previous two steps okay after this we will going to calc calculate the number of ways for each step starting from the third step so for that we will going to use a looping here I'm going to use for loop I in range of because we have already checked for previous two steps so here we will going to iterate or uh we will going to calculate from the third and uh n + 1 so here we will going to create one variable current is equal to previous 1 + previous 2 and uh let's update the previous one and previous two both variables so previous one and previous 2 will be updated through the previous to current so we have uh updated previous one and previous two previous one will be updated through the previous two and previous two updated through the current so let's also implement the command for this so that you can get what we have it so we have calculated the number of ways for each step starting from the third step and uh finally let's return this so what we have to return yes we will going to return the previous two so this is the complete implementation of your program let's run this code and check that it's working properly or not you can see all cases has been passed and code is working fine let's uh try to submit this code also you can see the code is submitted or accepted successfully so that's it for today's session if you have any query uh regarding this staircase uh problem or something else regarding programming languages so you can put your query in the comment section as well as you can also send your query through the Instagram Channel or telegram channel so whenever we will get your query we will try to resolve your query as soon as possible see you in the next session with a new problem till then keep practicing keep learning take care bye-bye
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
304 |
welcome back to this video in this video we're going to solve this coordinate equation range sum query to the immutable in this problem given a 2d matrix handle multiple queries of the following type calculate the sum of the element of matrix inside the rectangle defined by its upper left corner row 1 column 1 and lower right corner row 2 and call 2 so we are given a matrix and we are given upper left corner and lower right corner we have to find out the sum of the sub matrix for example if we are given this matrix if we have to find out the sum of this matrix in this case we are given the index of this the row one and column one and row two and column two so row one and column one is one and one row two and column two is two and two the sum of this matrix is 6 plus 3 9 plus 2 11 okay so for this matrix and for this indices we have to written 11. if we have to find out the sum of these metrics in that case we're giving these the index of this element and the index of this element this is upper left corner and this is lower right corner we've defined the sum of this matrix 3 plus 2 5 plus 1 6 plus 1 7 so for this we have to written 7. we have to solve this problem the name solution to this problem is that if we are given the index of 6 and the index of 1 the upper left index and the lower right index we can just find the sum of this region using two nested for loop but that is not efficient solution we can just run to nested loaf for our given index row 1 column 1 and row 2 column 2. we can solve this problem pretty easily by iterating this entire sub matrix but that will takes time complexity o of m times in where m is the height and it is the weight of the query or the sub matrix this is not super efficient can i solve this problem efficiently yes we can first thing what we're going to do we're going to construct a dynamic programming table let's assume this is our dynamic programming table we have one extra row and one extra column the first row is filled with zero okay the first row is filled with zero and the first column is filled with zeros now we're going to iterate from this cell to this cell now we have to construct it so how we're gonna construct it so what i'm gonna do i'm going to store the summation of this matrix right here the summation of these matrix right here okay so the summation of this matrix right here always to the lower right corner we will add the sum all just to the lower right corner so here we will have some here for these matrix so we will have some for all edges on the lower right corner so if we have here some let's assume that we have some right here for this entire matrix for this portion of this matrix we have some right here and we are given a query for finding out the sum of this portion then what i will do will we can just subtract this region and this region okay we can just subtract this region and this region if we subtract we see that we are subtracting this same region twice so we have to add this region to this value and then you can just substract this region and this region so it will be sufficient and that time complexity will be constant just find out the value for this cell and just subtract for the value for this cell and subtract the value for this cell and just add this value for this because we are subtracting this area twice this video we can solve installing efficiently and the query operation will takes for this kind of approach constant so we can run our query operation in constant time so how we can construct our dynamic programming table here we have this cell right so top is zero left is zero so top plus left plus our current the current is three so that is three and here we have zero plus three plus zero is three then we have one so zero plus three plus one equals to four minus zero is four we're subtracting this value because here we'll have the value of this cell and also here we'll have the value of this cell so we have to subtract one of this value now here zero plus 4 is 4 minus 0 is 0 plus 4 but here we have 4 okay so 4 plus 0 is 4 plus this 4 equals to 8. so here we'll have eight and here we'll have zero plus eight plus two equals to ten so here we will have the value ten now for this cell three plus zero plus five equals to eight so here we'll have eight now for this cell the game started here so three plus eight equals to eleven plus six equals two it'll been plus six equals to seventeen but here we will not have 17 that's because we have to subtract this 3 because this 3 is included on the top for this cell on the top and also on the left so we have to subtract this diagonal value if we substitute we get here 14 so we get here 40 and you can calculate the value right over here 6 plus 5 equals to 11 plus three goes to fourteen so here we will have fourteen we have here fourteen now for three four plus fourteen equals to eighteen plus three equals to twenty one 21 minus 3 equals to 18. so here we will have the value 18. let's calculate the value right over here so 1 plus 3 4 plus 6 is 10 plus 8 10 plus 5 plus 3 goes to 18. so here we have 18 and let's calculate this value for here as well so here we'll have 18 plus 8 equals to 26 plus 2 equals to 28 minus 4 equals to 24 let's calculate the value here okay so up until this point we see that we have the value 18 so 18 plus 6 equals to 24. it's okay right now we'll calculate the value for the rest of the cell using the same concept i'm not going to waste your time by showing you all the computation i think you get the point this is our approach to solve this volume to construct this dynamic programming table it will take speak of a min time complexity and it will takes of m in space complexity where it is the height and n is the width of the given matrix and the query operation will text the query operation will takes is time constant time complexity so let's find out the query operations and the query for this portion okay let's find out the query actually for this portion so here for three we have the value 18 right so we have 18 minus we're gonna subtract this now we're gonna subtract this sub matrix which is four so let's substitute here four then for this sub matrix this submatrix we have here 8 okay 8 and we see that we have subtracted this 3 twice so we have to add 3 so what you will get here we'll get here 12 okay 12 18 minus 12 equals to 6 plus 3 equals to 9 okay so we get here 9 and here we have 6 plus 3 equals to 9. so we find out our answer this is our algorithm to solve this problem now let's code of this algorithm now let's implement our algorithm first i'm going to create a dynamic programming table so in db right inside here let's initialize so typicals to new int the number of row is the length of the matrix plus one so matrix dot length plus one the number of column is the length of row plus one so matrix zero dot length plus one now let's run loop for int r equals to zero are less than matrix dot length r plus r for row now nested loop into c equals to zero while c is less than matrix zero dot length c plus right inside here let's populate this dynamic programming table the first column and the first row we have to fill with zeros when we created integer 2d matrix this matrix is filled with zero so our first row and first column is filled with zero by default so now let's calculate the value for the rest of the cell so dp r plus 1 and here this is for row index now for column index c plus 1 equals to the top value so the top value is for rho so r and c plus one this is for tough now for left dp r plus 1 and see this is for lift plus our current value so matrix are c minus we have included our diagonal velocity so we have to subtract it so dp r c when we're done with this for loop we will have our dynamic programming table from the dynamic programming table we can find out the sum region for the given index so return dp will have sum at root 2 plus one and call to plus one and we have to subtract okay we have to substruct dp so for this kind of inputs if you are giving this kind of inputs we'll have one extra cell okay if we have to calculate the sum region of this so here let's assume for this red area we will have our answer here for this entire matrix without the last column so now what i have to do we have to subtract this matrix okay this sub matrix so let's subtract it we can get that we will we have to use the row index so here row 1 and here we will have call 2 plus 1 for this value okay so call 2 plus 1 and also have to subtract this entire matrix this is our column matrix we can see so here we'll have the answer so dp will have at root 2 so row 2 plus 1 root 2 plus 1 and here we should have call 1 if we subtracted this matrix and this sub matrix we saw that we have subtracted this matrix twice so we have to add it from this value we can get that simply using dp row 1 and row 2. so we have to add this value okay so sorry here we should have column one and here we have to add this value and we have to written this value okay this is our algorithm to construct this dynamic programming table it will takes time complexity of m times in where m is the height and n is the width and this sum region this query will takes constant time it will takes constant time and it will takes constant speech this query operation will takes constant time and constant speed to construct dynamic programming table it will takes space complexity of m times in as well this is our algorithm now let's run this code accepted let's submit it we have solved this problem thanks for watching this video
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
419 |
hey how you doing guys it's ilya bell here i recorded stuff on youtube share description for all my information i do all legal problems um make sure you subscribe to the channel give me a big thumbs up to support it and this is called bottle soups in the board um unit 2d port count how many bottle sweeps are needed 2d matrix the bottom slips are represented with eggs empty slots are represented with dots you may assume the following rules you receive a valid board made of only battleships or empty slots bottle ships can only be placed horizontally or vertically in other words they can only be made of the shape one by n one row n columns or n by one and rows one column where n can be of any size at least one horizontal of vertical cell separates between two bottle soups there are no adjacent bottle shapes as you can see there is an example in the bob board there are two bottle sweeps the first one and the second one uh the reason by the example this is an embodied board that you will not receive bottle soups will always have a cell separating between them could you do it in one pass using only constant extra memory or without modifying the value of the board yes we could do that um you need to count the first top left cell of every battleship that's the point every time you see a door you skip the door also for example when you are at the position of x right here you need to make sure that there is no x to your left and there is no x above only then you can increment count by one means that you see another battleship for example right here we increment count by one there is one battleship uh then we skip those dots we are here we increment uh count by one again we got count s2 right is equal to two uh here we skip and then here x we got um you know like dot to your left there is no x um but we got x above so we skip we gone open yeah go for it first we create a few variables and that is the number of rows word dot length and number of columns board at the position of zero dot length count is zero in order to count battleships in the case when the number of rows is zero return zero automatically otherwise create a for loop we're gonna iterate uh to those records in port and i is zero is less than uh the number of rows i plus um and j is zero j is less than the number of columns uh j plus and as i said before you check in the case when ah we see door we gone moving we skip that dot otherwise we need to make sure that we are within bounds say i is greater than zero and board i minus 1 and j means we are you know above we check above in the case when uh above we got x we skip there we go on looping otherwise uh j is greater than zero also to make sure that we're within bounds and word i j minus one means to your left we got x then we continue and otherwise the case when we see a new battleship we increment count by one finally return count that's the whole problem let's run this code accept it let's submit success good yeah thank you guys for watching leave your comments below i want to know what you think follow me on social medias i do all liquid problems give me big thumbs up to support my channel um have a good rest of your day bye
|
Battleships in a Board
|
battleships-in-a-board
|
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`.
**Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
**Example 1:**
**Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\]
**Output:** 2
**Example 2:**
**Input:** board = \[\[ ". "\]\]
**Output:** 0
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is either `'.'` or `'X'`.
**Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
| null |
Array,Depth-First Search,Matrix
|
Medium
| null |
157 |
hey guys how's everything going this is chaser who is not good at algorithms in this video I'm going to take a look at one five eight the read end characters given three four call multiple times or given a file and assume that we can only read the file using before we plan implement a method to reach to read any characters my method may be called multiple times okay so this is read for with four will accept a buffer and he refer will write the string with length at most four to that buffer right this is the file but index will be kept among each calls so the first time in the code to the return ABCD the next one you will return e f g h the next one is ijk so really for just to read the file at four characters each time and now we need to extend the excreta read which we which accepts arbitrary account arbitrary amount right like read one issue is return a and then to it should return bc right what I think it's pretty simple we just uh if the number if a four is not enough we just kept reading right just keep reading until our nan this week satisfied and if you if it is more than what we need we just pop them out right Luke just pop them out until the amount matches right yeah let's try to do that so if we will Walt buff net this man will keep reading right the read for accepts a buffer so we create a new one and under read for in it right if buffer for no equal zero break right there's nothing to read and we will push them push the buffer for in right now there's a problem if that we read too much we need to pop them out right and the letters will pop will be used in next time we would call read uh-huh read uh-huh read uh-huh so I'll create it say it use a closure what cost is last on read of course for here we actually we need to use first so wow buff then end path push okay and it will end at when and when n characters are put into buff if that's not enough we read for and if we read too much you pop them out right so finish speaking it we will pop and the pop tournament will be put in a screed so wait on shift buff pop and then we need to return a buff mint right we're required to return the number what this is it the try submit yeah and now we're accepted so I'm not sure with her why this question is labeled as hard maybe it's because JavaScript to use dynamic things so it's not static and it's much easier anyway so that's all for this one see you next time bye
|
Read N Characters Given Read4
|
read-n-characters-given-read4
|
Given a `file` and assume that you can only read the file using a given method `read4`, implement a method to read `n` characters.
**Method read4:**
The API `read4` reads **four consecutive characters** from `file`, then writes those characters into the buffer array `buf4`.
The return value is the number of actual characters read.
Note that `read4()` has its own file pointer, much like `FILE *fp` in C.
**Definition of read4:**
Parameter: char\[\] buf4
Returns: int
buf4\[\] is a destination, not a source. The results from read4 will be copied to buf4\[\].
Below is a high-level example of how `read4` works:
File file( "abcde `"); // File is "`abcde `", initially file pointer (fp) points to 'a' char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = "abcd ", fp points to 'e' read4(buf4); // read4 returns 1. Now buf4 = "e ", fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = " ", fp points to end of file`
**Method read:**
By using the `read4` method, implement the method read that reads `n` characters from `file` and store it in the buffer array `buf`. Consider that you cannot manipulate `file` directly.
The return value is the number of actual characters read.
**Definition of read:**
Parameters: char\[\] buf, int n
Returns: int
buf\[\] is a destination, not a source. You will need to write the results to buf\[\].
**Note:**
* Consider that you cannot manipulate the file directly. The file is only accessible for `read4` but not for `read`.
* The `read` function will only be called once for each test case.
* You may assume the destination buffer array, `buf`, is guaranteed to have enough space for storing `n` characters.
**Example 1:**
**Input:** file = "abc ", n = 4
**Output:** 3
**Explanation:** After calling your read method, buf should contain "abc ". We read a total of 3 characters from the file, so return 3.
Note that "abc " is the file's content, not buf. buf is the destination buffer that you will have to write the results to.
**Example 2:**
**Input:** file = "abcde ", n = 5
**Output:** 5
**Explanation:** After calling your read method, buf should contain "abcde ". We read a total of 5 characters from the file, so return 5.
**Example 3:**
**Input:** file = "abcdABCD1234 ", n = 12
**Output:** 12
**Explanation:** After calling your read method, buf should contain "abcdABCD1234 ". We read a total of 12 characters from the file, so return 12.
**Constraints:**
* `1 <= file.length <= 500`
* `file` consist of English letters and digits.
* `1 <= n <= 1000`
| null |
String,Simulation,Interactive
|
Easy
|
158
|
484 |
hey what's up guys chung here again so and so this time let's take a look at another list called problem number 484 uh find permutation uh okay so you're given like a secret signature consisting of only character d and i where d representing a decreasing relationship between two numbers and i representing an increasing relationship between two numbers okay and the number range is like it's the length of the signature plus one and your goal is your job is our job is to find the lexical graphically smallest permutation from 1 to n and based on given the sacred signature in the input so what does this mean it means that okay see so it means that for example this uh if we only have one i here it means that the first two numbers should be increasing and if the first two numbers if the one is d here it means that the first two numbers should be decreasing and then three here and then another three here and you need to find the smallest lexical graphically permutation from one to n when n is the length of this the stream plus one okay so um so what's our what's going to be our approach right i mean i think we can only get uh get our approach by listing more examples here let's say we have like um or maybe the easiest one is like if everything is i then our answer is simply one two three and four okay right and how about this how about if i do a i d i how about this so since the first one is increasing it's one okay and the second one is two okay but the third one is d here this one represent represents one two three and four so it's going to be since we have two d here so the smallest one is going to be a 4 3 2 and then 5. right so that's our basically that's our results how about this how about id dd how about this one five four three and a two okay maybe some of you already find the pattern here right so what's the pattern means that whenever we have i here we uh we check how many consecutive d's we have seen so far for example this one here right so the first one is one here right and then the second one is supposed to be d as suppose it's supposed to be two here but since we have a d here we cannot put two here what we need to do is we have to so the two and then we have two three and d but then we have another i here so basically where what we need to do here is every time when we see an i here we have to reverse the consecutive these numbers in this case is a four three and a two okay yeah and the same thing here right same thing here is that since we have three consecutive this year we have to reverse this five four three two so how do we do the reverse we can simply use a stack we simply use a stack basically every time when we have a number when we see the number here we always uh push this number to the stack first and then we check if the current signature is i or not if it's i we simply pop everything from the stack and append it to our final answers so in this case for example the first one is i here we are we have one here right and then we push i here we push one in into the stack and then we have i then we just pop this one out then our answer is it's four yeah our answer is one and then the second one is d and the numbers for the second signature is two right so we have two here but since it's d we don't pop it out we keep it inside the stack here and the third one is it's also d it's three here okay and then now it's the ice is i here it's four right remember we always uh push this current number into the stack here now we have four three two and the current one is i then we just pop this one out so that we can reverse that and in the end since we have like we need one more numbers after looping through the signatures we just we need to add the last one into this stack here into the stack in this case it's five so we have five here so the reason why is that it's for example this one right so and let me do another example here same so for the first one is one right and it's insert so we pop these things so now we have one here and second one is two third one is three and the last one is also d it's also four here right and then we're done looping through all the signatures and so that's why we have to push the five here we always push the whatever the last one into this into a stack after like looping through all the signatures so that we can pop these things five four three and two right so by using like a stack we can like very easily reverse the numbers we're trying to reverse i mean this is like a grady like a greedy idea here because we're trying to reverse the minimum numbers to satisfy the signature right that's our the smallest one there could be other like possible ways of coming up with satisfy the signatures here but we are trying to find the smallest one that's why we're only like reversing the minimum number here yeah i think to be able to solve this problem you have to be able to figure out the pattern like when we need to reverse the numbers here okay and okay so with that being said let's try to code these things up okay so first we have an answer right with the uh with a list and then we have a stack okay and then we just do a i uh character in enumerate right enumerate s here so like i said we every time we have a number we always append this thing to the stack here since uh the reason we're doing in i plus one is because the uh the i is a zero base but whereas our number is one based okay if c is i okay then we uh we pop right pop everything in the stack while stack answer dot append okay stack dot pop right we only pop it whenever we see an increase that's when we know okay oh we need to reverse the previously the previous like these uh decreasing numbers if there's anything in the stack okay and after this like we also need to add the last one stack dot append so the last one is going to be the length of s plus one okay and then we do the same thing here whenever there's anything here okay and then in the end we simply return the answer yeah i think that should do it let's try to run these things here uh you know what i'm gonna remove this clear this okay so this one accepted let's try to submit it cool yeah it passed yeah i think it's a very good problem as long as you can figure out the pattern like the relations between the reversed numbers and the number of these here right so the greedy idea comes in like for every time we always use the next number right the next number try to see okay which position we need to put into this posit into this number and uh yeah so how about space and time complexity i think since we have we are looping through everything all the numbers by i believe it's n so since we're only inserting these numbers once and we're looking through this uh each number once uh it's all of n so the space time complex is o of n space is also often because we have a answer and stack right so 2n which is also o of n yeah so the i think one of the takeaways maybe you guys can take from this problem it's the uh it's how you can like construct a permutation right and how to greedily construct a permutation so greedy in it means that uh whenever there's i here right whenever there's i we assume the current indices is the one we need but if we have some like these before i then we need to reverse those these numbers so that we can make the uh the entire array satisfy the signature okay so that's our greedy method because we only keeping we're only reversing the minimum numbers that we needed and if we don't need to reverse it we just keep using the current number and append it to the stack yeah and as long as you can figure out that one i think it's the rest should be just implementations you can either use in this case i'm using a stack right to uh to reverse the uh the last numbers or you can use some other techniques like you can what you can you use a range or you can use a two pointer right i think uh whichever you prefer okay yeah cool i think that's it for this problem yeah thank you so much for watching the videos and stay tuned see you guys soon bye
|
Find Permutation
|
find-permutation
|
A permutation `perm` of `n` integers of all the integers in the range `[1, n]` can be represented as a string `s` of length `n - 1` where:
* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* `s[i] == 'D'` if `perm[i] > perm[i + 1]`.
Given a string `s`, reconstruct the lexicographically smallest permutation `perm` and return it.
**Example 1:**
**Input:** s = "I "
**Output:** \[1,2\]
**Explanation:** \[1,2\] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
**Example 2:**
**Input:** s = "DI "
**Output:** \[2,1,3\]
**Explanation:** Both \[2,1,3\] and \[3,1,2\] can be represented as "DI ", but since we want to find the smallest lexicographical permutation, you should return \[2,1,3\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`.
| null |
Array,Stack,Greedy
|
Medium
| null |
347 |
all right this is 347 top K Freon elements and so essentially in this question what's happening is you're given an array nums right and you're also given an integer K and this k um is supposed to determine where you cut off with the Kos elements right so we have three ones two twos and then 1 three and we're only returning one and two since one has three of them and then two there's two of them and that's pretty much what you're doing and so let's work with this one right let's do here nums and so how you want to go about this is that you want to have a hash map right so we want to have a frequency map to keep track of oops to keep track of the frequency the time we see it so essentially what we're going to do is it's going to be something like this it's gonna be like one um one well like this then two and then two so that's how it would look like right we're going to keep track of the frequency map and then we're also going to have the top K Elements which is what we're going to return at the end which is just going to be um an empty Ray and so what that would look like at the end is it would look like we're returning one and two right um It also says we can return it in any order so it could easily be two and one right and so how we're going to do this is we're going to instantiate the frequency map with some variables and essentially what we're going to do is we're going to for Num in nums we're cing every individual number and then we are going to so frequency map at num and then we're going to append let's see we're going to append num oops and so essentially how this is going to look like is how I said before it's going to be like one is the numb and then we're going to add one and if we see one again at one we're going to add another one and so on right because there's a key and then there's a value and that's how it's going to look like but to use aend we're going to have to turn this into a default dictionary and then we're going to make this the default is a list so if the V if the key is not found if one wasn't already in the dictionary then we started off with an empty list and then you're able to append one afterwards and so after you've done this we can start sorting this list right sorted um so let's change this to sorted frequency map um oops this equal to and then we want to sort it so that it looks like uh we want to sort the values so essentially um so one oops so we want to do like this one two and then three and so we want to sort it in the way that it's let's do like this so we do three oops three so then that's how it look like and we want to sort it so that it looks it puts the one with the most frequencies at the beginning right so it would look like this and then we want to do it like that and so what are we sorting we are sorting the frequency map values right so essentially what this is looking like is it's one right two and then three so we want to sort the values not the keys the Val values these are the values so we want to sort the values and then how do we want to sort it what is the key that we're sorting it by we're sorting it through length so this has the highest length afterwards and this has the last highest length so we want to sort it by length and then but then how that would look like is it would go in ascending order right so it would look something like since we're shorting it by length it would look like uh one and then 3 three so what we want to do is we want to reverse it is equal to true and then it would look like this right then it would become this after you sort it so essentially once we've done that we have the C most frequent elements right and then you have it in order so then once we've done this right we're pretty much almost done with this problem so then we do for the groups inside of the sorted frequency map right so then these other groups we want to slice it by the K element that we received at the beginning right so what this is doing is let's say the K is equal to two right we slice it here so now we're only keeping this right and so now that we've done this uh we're going to do how we're going to do this we're going to do the top K elements the array we had at the beginning and what we're returning we are going to we're going to let's say we're going to pen to it and then we're going to what are we going to append we are going to append group at zero pretty sure so then group is this right each group and then group at zero is just the first element and then that's what we're doing so then now we just return top K elements and since we don't have to put this in order um that's pretty much what we have to do if you had to put it in order you would just sort it right you go like that but we don't have to so then oops we could just return this top elements um that looks about right let's see sort of frequency map frequency values oops I forgot that this is a function let's run here and then submit and there you go that's 347 topk frequency elements
|
Top K Frequent Elements
|
top-k-frequent-elements
|
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
| null |
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
|
Medium
|
192,215,451,659,692,1014,1919
|
1,312 |
Hello everyone welcome to my channel but it is very similar to the diary which we have read till now, it will be very easy, it is ok my I insert the steps, you make a string parallel to the question, who did the question? Amazon Microsoft Google Let's understand the question once. Okay, so in the question you have been given a string named SS. Okay and what you can do in one step is that you can add character in any index. Ho in string in one step you can set other character date other index of date string ok minimum number of steps tell me my number or insertio say minimum number of how much will you insert string of characters whatever it is then pass the drum become ok You already know what Parnor means, but see the example here. This is already a palindrome, so there is no need to add anything. Its answer will be zero. I am looking at my example. This one is fine, so see this also here. There is no parallel because what happens in parennum is that come here, look here, this character is equal, right and this character is B, this is D, then it is messed up, meaning, if one character is a miss match, then what do we have to do? It was absolutely correct, now as soon as I look here, sorry, let's erase it, look here, then what A went here, B went here, but look on the right side, B is there, otherwise B is A, B is there, otherwise B has to be inserted, then B. Now I added B so both of them matched ok and look here D is correct here there is one di but there is no D here so I also added one di here so that these two matched ok after that in the last this child If it is A here, then notice that we have extracted which two characters, which were not given here, so we added them, and if it was not there, I added B, then both of them, we will have to add two characters, this is the minimum. First two characters have been added correct, so let's see how we will approach it. Okay now look now pay attention. Here I have taken this example to understand how we will approach it. When I was explaining above that I was matching. No, I was matching this with this, okay, then think for yourself, it's an obvious thing, even if you go, it will be like this, no, will you keep an ice painter here? Will you keep a painter of yes? Correct, then now you will keep matching, if mother. Let's take a match, it is a very good thing, we will flood further, like look at this is a character of string S and the win rate both are equal, so it is an obvious thing, we do not need to do anything, what will we do, simply do I + 1. We will take and K minus one do, simply do I + 1. We will take and K minus one do, simply do I + 1. We will take and K minus one because both of them are already matching, I don't need to do anything, so what will we have, now what will be left in the string, now we will be left with MBA, MI, where has A gone, A has been here. And this is here, okay, it is looking quite simple till now let's move ahead from here and okay, now pay attention to one thing, now what is the problem that both the brothers are not matching, correct character wins, character does not match. If he is doing it, then look, I have two possibilities, I can think of two things, first and second, so first of all I know what I am thinking that let's assume that there is B here and there is no B here, okay? Here B is in the rectangle character and here also it is not there, okay, so I will think that brother, mother has taken that, let's assume that brother, here I have inserted B which will match with it, okay and maybe When the match is done, when it is matched, then I will expand it further. Okay, and I hope that when I expand it further, I will get it further. This is a very good thing. The TV will match. Okay, this is possible. Okay, what I said is that I will put this character on the right side, okay, so I and that character will match and I will make I bigger further here, I will find more here that maybe I will be next, so I will make I bigger further. I will leave K to remain the same. Remember, I was here and K was here. Okay, I did not find B here on the right side. Maybe, let's take Ma. Insert a character here. Okay, insert a character. Diya and he came after matching and I will increase I further, I will go here A is ok and I will hope that if I do n't get the future, he will be found further, it is ok by increasing I, okay so I came here, so what was the condition I said first that I will make I+1 what was the condition I said first that I will make I+1 what was the condition I said first that I will make I+1 and leave K to remain the same, I hope that I+1, if I go further, I will hope that I+1, if I go further, I will get the Jeet character in the story, so what I did in this, brother, on the right side, I made Assam or I inserted B. I have done it, that's why I have been made bigger, right, so that is, what I have done is that the same 1 + I have done it, okay, another one, and Adam Assumption, what can I do, that it is possible, I can also think that I have inserted it here, okay, sorry, I have inserted it here and it matches with K, okay, and I will move left hand to J and hope that this Joe B is the director of this brother-in-law, hope that this Joe B is the director of this brother-in-law, hope that this Joe B is the director of this brother-in-law, right? Let's get the story but if I take K to the left side then it is okay, so what did I do this time, I left I there and took J to the back, okay mother K, I am going that this D is the left side, I have set it. Here also I have done plus one and inserted one character. Okay, so these are two options. Look, you have seen multiple options and you have to find the minimum, then that is what is hinting that brother, this is the question of DP. It is possible that there is a DB query, we will also do memorization, you are looking at the butt, now it is very clear, you must have come to know that there is a problem of DP, okay now let's move ahead, it is an obvious thing, if I do plus one with comma, then something. My string here will look like this, you do n't have to do MBA D M shirt here, go ahead by doing Adam, you just have to extract the count, why would you insert the character correctly, it is not necessary to do the character correctly, you have to count it only. So we have to remove it, OK, so i+1, that is, A is only. So we have to remove it, OK, so i+1, that is, A is only. So we have to remove it, OK, so i+1, that is, A is here, OK, it is still near Di, what is here So, it is near IB here, and Jack had brought it further back, that is, now K is here. That's it, now look here, then we do n't have character equal here, then we have two possibilities, okay, absolutely all possibilities, like I explained above, we will either check on I + 1 J, okay, so here. But what will happen MBA D M Okay so I + 1 K So I will go M Okay so I + 1 K So I will go M Okay so I + 1 K So I will go here A will go Okay and here A will go and K is also here So here also we inserted a character Okay and here where is I Look, if I move ahead then it is an obvious thing, I will simply make I + 1 and I will make K minus one, it will be I + 1 and I will make K minus one, it will be I + 1 and I will make K minus one, it will be equal, isn't it, I agree, here also there are characters from both. Now pay attention here, I is there, is n't it, here also I is, which is greater than zero, it will go further, so it is there, now by the way, we will return it in this, meaning we have exhausted all the characters and correct till here. If it is clear, then look here, that is, what has happened, I give greater K, what will happen in K, here I just write, okay, your string will be formed, so it will remain the same B A Di Mi, here A will go and K and what will happen is K. Here a will come brother, this is a mess, I mean we have exhausted all the characters, I am ok, here a will come, meaning what has become of greater den, I have become greater de, it has become zero, okay, so now think like this also. If I give you greater or equal, it means that we do not need to do any insertion, then right there I will say, brother, it is necessary to do zero in session, so what I am saying is that you did not need the kind here, okay? There was no need for you to know further here, what did you see here that brother, whatever has come, give me greater or equal, you have become zero, here you look, just return here, there is no need to insult anything. If you go beyond this, you will get an empty string from the office because if it crosses I, then you will return zero from here. Okay, so what will you do simply from here, you will return zero. Okay, you will return zero. From here too, you will attend zero. Now come. Look at this was one thing, right, here also we had inserted plus one character, okay and from the bottom here, there is a zero, from the bottom there is a zero, so 0 + 1, this is okay. Here also + 1, this is okay. Here also + 1, this is okay. Here also zero came and if it is plus one then it is one. From this thing then which is the minimum among the two. Here if both are made then the minimum must be one. So what did it do? It sent one up, whatever was the minimum of both. If you are adding plus one to whatever result is coming then you have got the answer i.e. what did I get from this thing 2 answer i.e. what did I get from this thing 2 answer i.e. what did I get from this thing 2 Similarly the same thing will happen here also from here you will also come correct this further if you extend the tree then now these Which is the minimum among the two? It is two. Okay, so the final answer will be two. Remember, our answer was you. Our answer was you. Okay. If we look at it is very easy to understand from the tree diagram. Okay, so now this means If we look at what we have done recension, we are writing only if the character is equal, then there is nothing to be done further, and if the character is not equal, then there are two possibilities, either check I + 1 or are two possibilities, either check I + 1 or are two possibilities, either check I + 1 or I. Comma K - 1, simply check I. Comma K - 1, simply check I. Comma K - 1, simply check both the possibilities. Out of the two, the one which gets minimum will be my answer. If we look at it, then how will be our code for recognition and memorization, it will be very simple. See what I said that solve it. Whatever the function is, I will definitely send the string. What will be I, what will be zero pay and If it has already been done, then there is nothing to be done, no insertions are required, it is required, zero instruction is required, answer is zero, it has been attended, okay, what else can happen that brother S of I is equal, you are equal, so we do not need to insert anything, we will move ahead. Solve it by making SI bigger in the front and K bigger in the back because it came = What I told you brother, minimum will come out, whose text is two, we have one, solve it by inserting one character, okay and there is also a method for longest common subsequence. This question can also be made very easily, ok, but they will make it in a separate video, and a separate video will be made in which I will still teach the bottom, ok, and wait for the playlist with DP concepts, it will come, we will be there in it. Bottom up top Dr. will see all the things, okay, so first submit the lead of the recognition in the code and see this farable tu pass jo dat is cases. Okay, so let's code this. If it is okay from the technique, then first of all keep a global variable in which I will use this s = function, I will do it tomorrow, okay, now here I will do my sample function tomorrow, string and sunny, if I give you a greater number, it becomes equal to you, then there is no need to insult anything, make it zero, okay or else Even if rectangle character and win character are equal, there is no need to insult anything, further flood, make C + 1 is no need to insult anything, further flood, make C + 1 is no need to insult anything, further flood, make C + 1 and K minus one, it is clear till now, if it is not so then brother, simply return, what to do, one plus. Leave the minimum of solve I, move K, let's check to do this, two parameters are changing, what mistake are we doing, do n't send S here, okay, let's see, first submit and see all the submits. Ho Jaan Chahiye Note Equal Tu -1 Return Note Equal Tu -1 Return Note Equal Tu -1 Return T of Icon And before returning here, it was a festival day so I was not able to submit, today I have done coin and submitted, my streak has been maintained again. Okay but you don't break your streak, it's okay. 19 If there is a big compulsion, then I hope you can help, but I will tell you, this can be made in more multiple ways. Bottom up will be taught in a future video, but this can also become the longest common sub sequence. Which is very simple, this is a very simple code, I have already made a video of the longest common sub sequence, watch it and here in the next video I will tell you how the sub sequence is in the longest form. This question can be very big. Easily Okay I Hope Just Able You Help Any Doubt Is There Resident's Comment Area Tree You Help See You Can Next Video Thank You
|
Minimum Insertion Steps to Make a String Palindrome
|
count-artifacts-that-can-be-extracted
|
Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zzazz " is already palindrome we do not need any insertions.
**Example 2:**
**Input:** s = "mbadm "
**Output:** 2
**Explanation:** String can be "mbdadbm " or "mdbabdm ".
**Example 3:**
**Input:** s = "leetcode "
**Output:** 5
**Explanation:** Inserting 5 characters the string becomes "leetcodocteel ".
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
|
Array,Hash Table,Simulation
|
Medium
|
221
|
1,665 |
1665 minimum initial energy to finish tasks so let's first try to understand the problem so we are giving a tasks and inside tasks it going to be sear rate so this subar rate means tasks I means actual I and minimum I yeah so this means initially we have some energy and then for this energy if it is more than the uh minimum so for example our initial energy for example we only have one and two our initial energy is a two so it means we can finish this task so what Left Behind is 2 minus one it means we still have one energy left yeah let's just use this example try to understand the problem first and then I'm going to find a pro to solve this problem yeah so we are giving a task like this so we just imagine if we have a result like eight what we going to do so we're going to choose one by one yeah so for example if we choose the third task it is more than equal to 8 and then we can use 8 minus 4 because four is the actual and 8 is the minimum so this it means we should have a minimum energy should be more than equal to8 and then we going to execute this task and after executing the task what Left Behind is four this is our energy and then we're going to this four to check this four is more than equal to the second task it is a four so we can execute this task so after executing the task what the enery left behind it is 4 minus 2 it is a two now we're going to execute this first task it is this one and two so two is more than equal to two so 2 minus 1 it is one now we finished all the tasks and our initial energy is eight and eight is the minimum it cannot be bigger yeah but uh how can we solve the problem and which tasks should be executed first is that according to the increasing order of the uh actual value or is it the increasing order as the minimum value yeah if we check the examples it is not like that so for this kind of a problem we have to analyze yeah what kind of a strategy we can use to solve this problem yeah now let's just analyze something so for any two tasks so for example I'm going to use uh seven three and seven as my first task and five and eight as my second task I'm going to compare which task I going to execute first to get a minimum energy yeah to get a minimum initial energy so I'm going to use some generalization to represent the problem yeah so I'm going to define the first tasks as task one it going to be A1 actual one and minimum one A1 and M1 and similarly for task two I'm going to Define it as A2 and M2 So currently I can decide whether I can execute the first task or I can execute the second task first so for example if I execute the first task and then the second task I will represent it use T12 so this means I will execute the first task and then the second task so T12 should be the maximum of M1 and A1 Plus M2 why yeah so for example um so this A1 Plus M2 means for example if we execute the task one first yeah we get a result of A1 this is our initial energy for example A1 equals to M1 yeah we're going to get a A1 and after that we're going to what energy should we have to execute the task two at least we should have M2 uh energy so it is A1 Plus M2 or if this M1 if this minimum is really big so we're going to just use this M1 is enough to execute two tasks yeah let's just use the numbers as example so for example if we execute one first so for the first task uh we're going to what energy we use so we need a minimum of three h three energy right so A1 is the three and then for execute the task two we going to what energy we need 8 so 3 + 8 it is 11 so A1 Plus M2 it is 8 so 3 + 8 it is 11 so A1 Plus M2 it is 8 so 3 + 8 it is 11 so A1 Plus M2 it is 11 yeah so for 11 after executing the first task what left behind it is eight and eight is enough to execute the second task so this is A1 Plus M2 if this seven is really big it is like uh 17 so what it going to be so if it is a 17 our initial energy have to be 17 because if it is less than 17 we can never do it so if we choose the 17 after Execute the first task what left behind it is 14 and 14 is bigger than eight so it is enough to execute the second task so this 17 is enough so the final value is 17 it is the M1 so this is why we can get this kind of a formula if we execute task one first and then task two so it going to be the maximum of M1 and a1+ M2 going to be the maximum of M1 and a1+ M2 going to be the maximum of M1 and a1+ M2 yeah and S similarly if we execute T2 task uh if we execute T2 the task two first this one first and then we're going to execute the task one what it going to be we just change this formula yeah because here is M1 A1 + M2 and here yeah because here is M1 A1 + M2 and here yeah because here is M1 A1 + M2 and here should be M2 A2 + should be M2 A2 + should be M2 A2 + M1 yeah I think if it comes to mathematic formula you have to think about it carefully yeah to find a solution if t 21 if it is a t21 so this M2 can be a maximum value or this A2 should plus this M1 now we are going to guess what kind of a formula we can get to prove whether we're going to execute task one first or task two first yeah because inside here as you can see it is A1 Plus M2 and here is A2 + M1 now we A1 Plus M2 and here is A2 + M1 now we A1 Plus M2 and here is A2 + M1 now we are going to get the formula inside of the formula there will be A1 + M2 the formula there will be A1 + M2 the formula there will be A1 + M2 and how can we make it of course we can use M1 + A1 because M1 + A1 and m2+ A2 use M1 + A1 because M1 + A1 and m2+ A2 use M1 + A1 because M1 + A1 and m2+ A2 so we can check we're going to check if m1 minus A1 is more than M2 minus A2 what it going to be yeah so this example is like 7 - 3 it is four is more is like 7 - 3 it is four is more is like 7 - 3 it is four is more than 8 minus 5 three four is more than three what it going to be whether we will execute the task one first or which should execute the task two so we're going to guess if this M1 - A1 is more than M2 minus A2 so this M1 - A1 is more than M2 minus A2 so this M1 - A1 is more than M2 minus A2 so we can get a formula A1 + M2 so a A1 we can get a formula A1 + M2 so a A1 we can get a formula A1 + M2 so a A1 goes here and should less than A2 goes here plus M1 so this formula actually is what we get as you can see A1 Plus M2 is inside TK 1 2 and A2 plus M1 is inside task 2 one yeah now we get this formula now we are going to check the value to prove yeah we have to check the value if m1 more than M2 or M1 less than M2 what is the result so let's just check M1 more than M2 first so t21 should be equal to a2+ a2+ a2+ M1 so this is a t21 and t21 should be maximum of the two so here t21 I going to use A2 plus M1 so A2 + 1 M1 is more to use A2 plus M1 so A2 + 1 M1 is more to use A2 plus M1 so A2 + 1 M1 is more than from here A2 + M1 is more than A1 + than from here A2 + M1 is more than A1 + than from here A2 + M1 is more than A1 + M2 yeah and A2 + M1 is more than M1 M2 yeah and A2 + M1 is more than M1 M2 yeah and A2 + M1 is more than M1 because this is M1 and this is M1 yeah so M1 and A1 + M2 the maximum value is so M1 and A1 + M2 the maximum value is so M1 and A1 + M2 the maximum value is still T12 so this means the t21 must be more than T12 yeah here we just guess T2 + M1 would be the maximum value of t21 + M1 would be the maximum value of t21 + M1 would be the maximum value of t21 so this means t21 is more than T12 and what is other conditions so other conditions if uh is M1 minus A1 more than M2 minus A2 but what is the result is t21 more than T12 this means the t21 is a bigger value but T12 is a smaller value so this means the difference of the second value minus uh with the first value if it is bigger we going to always choose this aray first so t21 T12 is smaller we're going to always chose T12 first yeah now let's check the second condition if m1 is less than M2 2 so we're going to ATT T12 so T12 is M A1 + M2 it is T12 so T12 is M A1 + M2 it is T12 so T12 is M A1 + M2 it is here and it should be less than A2 + M1 here and it should be less than A2 + M1 here and it should be less than A2 + M1 and it is here A1 and for this formula A1 + M2 less A1 and for this formula A1 + M2 less A1 and for this formula A1 + M2 less than A2 + M1 and A1 + M2 should more than A2 + M1 and A1 + M2 should more than A2 + M1 and A1 + M2 should more than M2 because here as you can say M2 is the same yeah so this means A1 plus M2 less than A2 + M1 and more than M2 less than A2 + M1 and more than M2 less than A2 + M1 and more than M2 yeah but for the maximum value this T12 should be less than t21 because for t21 it always chooses a maximum value it is this one A2 + M1 so this is the t21 yeah this one A2 + M1 so this is the t21 yeah this one A2 + M1 so this is the t21 yeah so this means the T12 is still less than t21 and here T12 also less than t21 so this means no matter M1 more than M2 or M1 less than M2 we can always get the result so T12 going to be the minimum value so according to our provements so for any of the element inside the tasks we're going to Che the uh difference of the two uh element inside the ray if the second element minus the first element have a bigger value for example the this is four 8 - 4 it is four we're going to is four 8 - 4 it is four we're going to is four 8 - 4 it is four we're going to always choose this task first and then we're going to choose 4 minus 2 because the difference is two and then we're going to choose 2 minus one because the difference is one so according to this we can get our result yeah now let's just start coding so what we what kind of solution we going to use uh there going to be two solutions but for Simplicity I'm going to use the binary search because for binary search if I can guess a answer for example if I get the answer eight I just need to use this eight to minus every tasks and then get the result to guess if it is a true or false yeah now let me just start coding yeah so the magic function is here we need to use a sort and this sort is the provement of this areas if you can prove like that and you can just sort the tasks yeah you can use uh tasks. sort so inside of the sort uh we can use a Lambda function so we're going to use uh Lambda function X is the element so it going to be the x0 minus X1 why because we're going to Che the always be the maximum 8 minus 4 but if we want to get the maximum first we have to use the first value minus the second value it going to be a negative value if it is a negative value after sorting this minus 4 will always be the first so this means four and8 will be sorted at the first place so we're going to use x0 minus X1 yeah otherwise you have to use X1 - x0 and then reverse so have to use X1 - x0 and then reverse so have to use X1 - x0 and then reverse so here I going to use x0 minus X1 now we can use the binary search so for binary search let's prepare the template so for me I'm going to use l r and result so for L it is a zero R it is 10 the power of 9 and result is zero and this R is dependent on that because the value minimum and act 10 to the power of 4 and the length of the r and 10 to the^ of 5 the length of the r and 10 to the^ of 5 the length of the r and 10 to the^ of 5 so 10^ 5 * 10 ^ 4 it is 10 ^ of 9 it so 10^ 5 * 10 ^ 4 it is 10 ^ of 9 it so 10^ 5 * 10 ^ 4 it is 10 ^ of 9 it could be the maximum value now I'm going to use a b search template yeah so the M should be equal to l + Rus L ID 2 and if should be equal to l + Rus L ID 2 and if should be equal to l + Rus L ID 2 and if it is possible yeah if this is possible maybe there would be a smaller value I'm going to have a record of this m and this R should equal to n minus one because I'm going to guess a smaller value if it is not possible yes L should be M plus one I'm going to gu a bigger value after that I'm going to return the result yeah now I'm going to finish the check function I'm going to finish it here yeah so the Teck function inside this m I'm going to give it a threshold now I just need to Loop through the tasks array yeah because this task array has already be sorted according to my provement yeah now I just need to check it one by one so for uh yeah let me check what is the varable actual and minimum yeah so for actual and minimum in tasks if this threshold is a bigger value big enough minus M yeah maybe you're going to guess if we guess a value why it is always works because we've already sorted the tasks according to our Improvement it means it always works if find a value this binary search if we find a value eight according to other greedy Solutions it would always work because we always check this element first this element second yeah so this in this way we can use the threshold minus uh yeah here this m is just the minimum value it is not this one because it is a function inside yeah we just take a value of threshold so if threshold minus M more than equal to zero I going to update the threshold should be yeah minus this m else I going to return a false because yeah it is not possible yeah because if this threshold is too big uh this threshold is too small maybe it is a seven and but this is eight it is not possible so I going to return false yeah if I didn't return false after executing all the tasks I going to return a true yeah as you can see this is the entire code it is not so difficult and the binary sech part is easy to think about but this provement is very difficult maybe you can guess about it maybe yeah you're going to find some um yeah regular patterns for example this is 8 minus 4 uh the difference is four this difference is 2 4 2 1 oh it is a decrease it means if the difference is bigger I'm going to execute the task first yeah this is a some pattern maybe you don't need the provement you can just use the pattern to solve this problem and then you're going to attack the second one it is always decreasing 31 29 19 91 it is always decreasing so this means yeah you can do it according to uh the biggest Gap first and then the second biggest Gap as you can see and here also the same it is decreasing 22 20 17 16 12 and six according to this maybe you can also follow some pattern without the provement you can save time and make it a yeah Mak the program right maybe you can just guess and try yeah uh let me just check what is the wrong um yeah I forget the K it should have a k equal to Lambda uh the result is wrong this is so yeah I have to debug um yeah let me uh this means it is a bigger value yeah let me just print out the tasks uh yeah this means it is uh right yeah let me just explain this areas the pattern because it is always decreasing this means for the task you can always attack the uh biggest Gap first and then the second biggest Gap and like this way yeah uh yeah let me just debug about my program there something wrong I guess uh threshold uh the threshold for the yeah if it is the threshold if it is more than M so this means if the threshold is more than M so what is the result for me I should minus a not m not the threshold I should minus the actual value because this is according to the description I forgot about it yeah now let me run it as you can see it works now let me just delete the print and submit it to check if it can pass for all the testing cases yeah as you can see it passed all the testing cases the time complexity is unlog in it is about this s yeah uh let me submit it again yeah it is still the same it is a little bit slow but I think it is enough to solve this problem because the timing is just less than 1 second it should be okay um and this uh length of the tasks is 10 to the power of five so it means unlog is enough to uh solve the problem yeah thank you for watching see you next time
|
Minimum Initial Energy to Finish Tasks
|
diameter-of-n-ary-tree
|
You are given an array `tasks` where `tasks[i] = [actuali, minimumi]`:
* `actuali` is the actual amount of energy you **spend to finish** the `ith` task.
* `minimumi` is the minimum amount of energy you **require to begin** the `ith` task.
For example, if the task is `[10, 12]` and your current energy is `11`, you cannot start this task. However, if your current energy is `13`, you can complete this task, and your energy will be `3` after finishing it.
You can finish the tasks in **any order** you like.
Return _the **minimum** initial amount of energy you will need_ _to finish all the tasks_.
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[4,8\]\]
**Output:** 8
**Explanation:**
Starting with 8 energy, we finish the tasks in the following order:
- 3rd task. Now energy = 8 - 4 = 4.
- 2nd task. Now energy = 4 - 2 = 2.
- 1st task. Now energy = 2 - 1 = 1.
Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.
**Example 2:**
**Input:** tasks = \[\[1,3\],\[2,4\],\[10,11\],\[10,12\],\[8,9\]\]
**Output:** 32
**Explanation:**
Starting with 32 energy, we finish the tasks in the following order:
- 1st task. Now energy = 32 - 1 = 31.
- 2nd task. Now energy = 31 - 2 = 29.
- 3rd task. Now energy = 29 - 10 = 19.
- 4th task. Now energy = 19 - 10 = 9.
- 5th task. Now energy = 9 - 8 = 1.
**Example 3:**
**Input:** tasks = \[\[1,7\],\[2,8\],\[3,9\],\[4,10\],\[5,11\],\[6,12\]\]
**Output:** 27
**Explanation:**
Starting with 27 energy, we finish the tasks in the following order:
- 5th task. Now energy = 27 - 5 = 22.
- 2nd task. Now energy = 22 - 2 = 20.
- 3rd task. Now energy = 20 - 3 = 17.
- 1st task. Now energy = 17 - 1 = 16.
- 4th task. Now energy = 16 - 4 = 12.
- 6th task. Now energy = 12 - 6 = 6.
**Constraints:**
* `1 <= tasks.length <= 105`
* `1 <= actuali <= minimumi <= 104`
|
For the node i, calculate the height of each of its children and keep the first and second maximum heights (max1_i , max2_i). Check all nodes and return max( 2 + max1_i + max2_i ).
|
Tree,Depth-First Search
|
Medium
|
543
|
459 |
in this problem we have to check whether the given string is formed by repeating some of the substrings so let's see an example so if you look at this string aba then there is no such substring which you repeat multiple times to form this aba because if you have a then you repeat it multiple times you cannot get a b a next if you take a b again you repeat it multiple times you cannot form a b a you can form a b but not a b similarly any other character you can try will be in any other substring but if you look at this example you see that it's abc so you can form this complete string by repeating abc multiple times so clearly uh whatever is the pattern so let's say we have a string which is formed using some substring so this p is not one character but it's something like this so let's denote this with p whatever pattern is being repeated so it's like p multiple times so this is the string so you have to figure out whether the given string is of this form or not so if you have studied about uh kmp algorithm uh for which i have already added one video so there we used to find the longest prefix which is also a suffix and by prefix we mean proper prefix because the string itself is also a prefix so in that case the complete string will always be same as the suffix which is also the complete string so that's why we take proper prefix that is we cannot include everything prefix will start from beginning so if you exclude the last p then this part will be same as so this part let's write a smaller example p just like this one so we cannot include the last character so if we don't include this last character we are removing something from the last p so that cannot match this one so let's say we have this form so just ignore the last p for now then this is same as this so this prefix is same as this prefix so this will be the longest prefix suffix of n minus 1 that is last character so you know how to construct this lps look at my earlier lesson on kmp algorithm there i discussed this in detail so first watch that then come here so now let's say this is the l or the lps of n minus 1 last one now what you can say if let's say this is 0 that is there is no prefix which matches with this in that case this string will not be of this form because even if it was something like this pp then still this is same as this p is again a few characters so if it's 0 then straight away you can say that there is no such pattern if lps is not zero then what you will do l in this case l will be let us say each piece of three characters then this will be nine so if you subtract n minus l so n is this complete thing so n is some factor of p this is the definition of this string it's formed by repeating p multiple times and this denotes how many times so n is k p so what will be this k p and what is l will be some smaller k p it's also some repetition of the same pattern so if you subtract these two you will get another kp k prime p let's say or in this case you can say k minus 1 p so k prime p this is n minus l so if you take modulo uh l modulo this then it should be zero so n minus l will be in this case p so l is uh 3p and n is 4p so n minus l will be p and n is this one so l modulo n minus l should be 0 so if this is valid then you will return true so let's write the code for this and again in order to understand the code for this lps look at the kmp video so we initialize it with zero and then we start from so the for the first character lps is always zero l should not be zero and so n minus l will be p and l will be some factor times k p some k times p and the solution is accepted so what is the time complexity here so the time to build uh the lps array is of the order of n where n is the size of pattern and in this case this is string itself we are building the lps of this so time complexity will be of the order of n and we are storing this lps in this vector so this is also n so both time and space are o of n now let's write this in java and the java solution is also accepted and here also it's good finally we will write it in python 3. so and the python solution is also accepted
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.