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 |
---|---|---|---|---|---|---|---|---|
27 |
what's up guys Xavier Elan here I go over hacker ranking leak code video so check out my channel and subscribe if you haven't already and if you like this video hit that like button as well today I'm going over a remove element it's easier a problem so we just have to give it a rating ohms and value valve remove all instances of that value in place and return to new lanes so we can't create a new array we have to do it with this array we can't use extra memory the order of elements can be changed we're not going to change the elements the way I'm gonna do it okay so if they give you three we just have to remove all the threes in here just return the twos and there's a clarification why they return value is an integer but your answers in array so that was confusing because we have to return like the new length of the array but when you do that it returns the actual rate and I thought that was really weird and so they clarified that here the input array is passed in by reference so which means modification to the input array will be known to the caller as well you know it prints the first okay so this one's good to see on the whiteboard so we're going to use I and J so J's we're gonna loop through all the elements in the array oh so let's say this is our array we're gonna loop through each one and then I was gonna be like we're gonna set number by so if nums of i does not equal her numbers of J I'm sorry if gnomes of Jade is not because we're looping through with J if numbers of J does not equal vowel then numbers of I is going to be equal to numbers of j ur numbers of J sorry and then we just have to when we do that we increment I plus because that's keeping track of our length so basically if it does we just skip over it's really simple so for here it would just do one I becomes plus so we get 1 and then we add 2 plus 3 and then 3 we just don't add because that's the value so let's just code that out real quick so J's always incrementing I we only increment when it's not the when num so J is not the value so no I equals number J and then we just have to remember to increment my and so this problem we're after it's weird we have to return hi they want to start turn the length but it also returns the array as well so see there you have it I did this is the test case I did so let's submit it Smit sweet so 100% so let's submit it Smit sweet so 100% so let's submit it Smit sweet so 100% over in run time we're just looping through the array and linear or constant space complexity because we're not creating a new array we were using the same array and thanks for watching guys
|
Remove Element
|
remove-element
|
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`.
Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things:
* Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`.
* Return `k`.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int val = ...; // Value to remove
int\[\] expectedNums = \[...\]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[3,2,2,3\], val = 3
**Output:** 2, nums = \[2,2,\_,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2
**Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `0 <= nums.length <= 100`
* `0 <= nums[i] <= 50`
* `0 <= val <= 100`
|
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
|
Array,Two Pointers
|
Easy
|
26,203,283
|
1,669 |
em all of the vision vitahealth small image and speak english show factors are much for connection from the ielts test experts in fermentation entangling love you have Special English and the heaven in the recommended system or on the views of use spaces are enough that the folder pineapplechocolate folder and the other is the porefessional vasotec home now Is The brightest know our best to start in to make you and showed that optimizes the waiting for the future the sentences and the Contest what I love my friend is span internship in the mansion Speed Of Your thoughts and one thousandth man in the hospital next to endless centerfold method for anti plaque advantage number There were my face like forty Nights at seven Element Of Your fat with all my heart I started in three minutes Then my dog show cafe welcome and Have Then my dog show cafe welcome and Have Then my dog show cafe welcome and Have fun of error rate is located just want and I come back to stretch across to our Conversation and Earth and get used to the Wave of placing osprey sinh osprey single or save the other way of fun pix il be displayed fonts that you can't afford the fun of its about the act of it a special Price quicken theta latest Price little English word order to write a short jean our teeth animated my contact of the end of each date is time you Peter and is the easiest and illustrates position of parts Master notepal ergostand compared to again what hit keno malicious threats paperport cafe durability very careful and minimize to ceiling mounted Lisa cause you're right It can I telephone Mobiistar acacia Rider stateless have to Worry About education home police uel's day of work and emboss get Windows you spend The Night rod special conditions apply for determine that was the morning of as the second time here in Another power wall National lottery and complete with and It's So Hard To solve and time It's seven center with love is the weather today is my solution National Defense minister for your income For You Want To Love Like Crazy Kart S II I watched Santa I'm done You said for the season to release the numbers, don't you just get it all and then the fermentation process with Frank is washing the advancement of the future Hill tribes triquetrum and record Bye bye
|
Merge In Between Linked Lists
|
minimum-cost-to-cut-a-stick
|
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively.
Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place.
The blue edges and nodes in the following figure indicate the result:
_Build the result list and return its head._
**Example 1:**
**Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\]
**Output:** \[0,1,2,1000000,1000001,1000002,5\]
**Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
**Example 2:**
**Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\]
**Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\]
**Explanation:** The blue edges and nodes in the above figure indicate the result.
**Constraints:**
* `3 <= list1.length <= 104`
* `1 <= a <= b < list1.length - 1`
* `1 <= list2.length <= 104`
|
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
|
Array,Dynamic Programming
|
Hard
|
2251
|
4 |
Hello friends, welcome to your channel, today is our day for the Lead Code Challenge. So let's start on the screen. Here I have come on the screen. My question is open. Today's question is the four end of the lead code number. The name of the question is Median of two sorted. Okay, so we have to find the median. Two sorted. So first of all let's understand what is the median. Median in a way we say middle. Okay, so like if we have any one, 1 3 2, which is the middle. What will be the value? What will it be? 3 If this is an odd length array of odd numbers, then what will be its middle value? What will be our basically middle value? 0 1 So length by two if I do what is its length is two is 3/2 I do what is its length is two is 3/2 I do what is its length is two is 3/2 If I do, one will come, then I know if it is an odd length array, then what will be the medium value, that will be the value which will be on the one index, if in this case we have an array inside which there are values, even values are in the even values are in the even values are in the even values. What is the middle value? Now the middle value, if I consider this, then there is one element here, if there are two elements here, then middle value cannot be two. If I consider middle value three in these cases, then this will also not be middle value because There are two elements here and there is one element here then what will be the middle value. If this gives some idea then this idea can seem that the middle value here will be somewhere between this and 3. So what do we do with this? What is the middle value taken in the case, basically 2 p 3 diva bt kya aayega 5 btu t e 2.5 We also took some cases of this type 2.5 We also took some cases of this type 2.5 We also took some cases of this type like here if we merge it completely then after merging what will it become and What is the middle value in this, so what has happened to us, now the answer we return is in decimal form, so when we are returning the answer, then we have to type cast it, in which we convert it directly from integer to our double. Okay, so let us keep this thing in mind and if we see the next case in which tooth is 4, then what will be the median? Sum the two middle values and divide by two. Sum the two middle values and divide by two. Sum the two middle values and divide by two. Here we have also done divide by 2.5, so Here we have also done divide by 2.5, so Here we have also done divide by 2.5, so we get the answer. I have to return something in this form, so I hope you have understood what is Median, now let's discuss a little more about what to do in this question, basically what we have been given is two sorted arrays. V and T of size A and return the median of two sorted arrays Okay so what we have to do first is basically first we have to merge both the arrays and return the value which is in between in the form of decimal form we have to do decimal form We will see how to type cast integer. We will see that further. Now it is written that the overall run time complex should be ofl m p n. Now this question is basically a variation of binary search, ok binary. This query is done using search, but for now let's not do the brute force approach. Later we will be doing this binary search approach in separate videos when we will discuss the binary search a little more and do some more queries. Ba but now we are on the rays part, so we will merge both the rays and then do this. Okay, so let's go straight to the screen and end, so I have come here on the screen, I have come to my white board, now I have to do this thing. So, first of all my task is that I can merge both the sorted arrays, the first array is this and the second array is this, so if I merge it, what will become of it and when I have a merged array, what can I do in it? Now, let's see how to merge. To see this, first of all, I made a little bigger one. Now both the arrays are sorted. Take care of this. Array one, I have said this, I will make the next one. If I can keep it in that, then I have kept this thing, now the approach will be quite difficult, I would not say it is very difficult but it is not very easy to merge both the arrays. Now if I merge both the arrays, I want to merge both the arrays. If I do this then the first thing I will have to do is to create a new array, what should be its size? I will have to add the sizes of both, so first of all I will create an array. Now, how many elements are there in both, four char four, how much Cy will be formed, A Cy one two three four 6. From the end I would have written this T is fine, so I would have written this on cy and y, a little more and on y also I would have written this, now basically what will be the approach in this, what will be the pointer approach, both the pointers are ok, I both are all three. Hey, I am a pointer, here the pointer is p1, here the pointer is my p2 and here my pointer is p3, now what I will do is take out a value from both the arrays p1 and p2, whichever is the smaller value among the two, I will put that in my p3. I will place it in the pointer and move the pointer to the array from which I have taken out that value. So now I took out the value from both, which of the two is the smallest value which is p1? So I placed it in p3 and moved p3 forward and The pointer to the array from which I had extracted the value. Now if I look at both the values p1 and p2, which is the smaller value among the two, then I put the value of p2 in p and moved it to p3 and from where I That value was found out, its point, so I tried some approaches like this. Now let's see again Pv and P2. Which number is smaller among P1 and P2. If the number is smaller among the two, then what should I do? Will I place it in P3 and then I will move p3 forward, p3 has come in every case but I will move forward the pointer of the ray from which the number was taken, I will further check p2 again, which of p1 and p2 is small, this time p1 is small, so what did I move p1 forward? Place four in p3 and move p3 again and this time the number was taken out from array one in p1 so move p1 forward. Let's check again which of p1 and p2 is small. If p2 is small then Place p2 in p3 and now from where the number was taken, move the pointer forward and I move p3 forward every time, after this we come to this, which of the two elements is smaller, if p1 is smaller then I What to do is to place p1 in the array of p3 where the pointer was, place it at the exact position of the pointer and move forward the pointer from where the value was taken. After moving forward, I also moved p3 to the right position. What will happen now? Which is the smallest element in p1 and p2? Out of p1 and p2, p1 is smaller. Sorry, p2 is small, so I placed p2 in p3 and moved p2 forward. P2 moved forward and p3 also moved forward. Now understand carefully. The thing is that p2 has now progressed to me. p2 has progressed exactly like that. Now if I check this with a, I will go to the next iteration and check the value of p, then it will give me an error, so I have to check this case also. I have to take care that it does not give this error. If I do not give this error, then understand that if I consider it as a maximum value, which is the maximum value of an integer, how will it come out? Integer dot maximum value when p2 will go beyond the bounds of my array. Meaning it will be equal to the length of the array Now it will be equal to the length of the array because what is the last index array dat length my Now what has happened is the length of the array should be equal to the length meaning out of bounds if I go to check the array two Off p2, now this will give me an error, so when I get this error condition, that means the array will go out, the pointer from the last index to any array, then what will I take in it, a method like integer zero dot max value tp, now this max value tp This is because I wanted the minimum value among the two, so whichever pointer it is, it will always be smaller than this, the other pointer will obviously always be smaller than this, so if I compare the two, which one will be smaller e1 Wa and p1 will come here and get placed and p1 is also outside fine and from this I am getting to know one thing that when both my points p1 and p2 will go out from which array, both the points will go out of the array then what do I have to do? Then stop this loop and then my entire array will also be filled. Okay, so I hope you have understood this approach, how to merge it, so first we merge, later we take out the median, once I write the code. Then we will dry run it, then if we look further, then I will go straight to my screen and see, first I will create a function which will basically return me, one, I wrote public, I wrote the return type as inger array and I wrote merge, keep its name. Given function, it will get two arrays in array one comma int array two Now first of all what should I create as soon as I come, I have to create one answer array which is basically my array show in sorted form so let's make it int answer array equal to new int How much length will I keep inside it, its length will be basically by adding the length of both, so I wrote array dot length plus array two dot length, so I did this, I created an array, after this I will create an ev pointer which is going to be placed on the array and also with zero. Where will it start? The pointer will start from zero and P will start from our base G. Now I have to basically put a loop which will work as long as the length of both array P and P2 is greater than the minimum index. Outside, I will not write down, as long as it is smaller than which is array dot and P2, as long as it is smaller than which at dot, I have written this thing, right? I have written both of them. Now I will extract value and value one and value two from int value. One, from which array is the value derived? First, I will see that if p1 is smaller then take the array and dot. But I am going to use ton operator. Basically, I will write the terry operator first. Then tell me. Okay, so p1 if smaller, have dot lane. Then what can we take? Then what value will we take? Array and off p1 otherwise what will we take in else? In else we will take int ger dot max value. Ok and in value two also write in this manner. Let me take then let me explain to you so I wrote p2 if it is small addle then I will take the array to off ptu at off put take s what is inger max y little understand n ter nri ter just so what is in turn operator basically we are here Write a condition Y B Here we basically write the condition, after the condition we write que mark, after the que mark, if this condition is true then this part will run, after that we put a colon, after that this is the true part, our if condition. If true then this part will run. If the condition is false then this is basically the same. Ifels means version. This is a short syntax of ifels. You can say that if you want, you can also use l in it. It is quite easy to use. First of all, let me tell you again, here we write the condition, any condition like we wrote p1 here, if it is true then this part will work. If the condition p1 is smaller than what is the lens of our array, then what will happen to us, this part will work but. In this case, if it is bigger, which part will go, this one is ok, so I hope I have been able to explain it to you, I have given my base, but I have seen this thing, now what do I have to do basically, which of the two? Minimum Value Which is the minimum value among the two If I wrote Love is a lesson Latu If value one is smaller than which value two then I will place value one In which answer of p3 I will place value one in the answer of path Now which value one The value of the array is value one, which was the value of the array, it is from the first array, so I will move the pv pointer because the pv pointer is pointing to array one, in the else answer of p3, who will I place in p3? It is okay by placing my value two. I will place the value 2. After placing the value, where does the value 2 come from? p2 ps plus means pointer to ps plus and in both the cases our p3 pointer has to move forward so I have taken this thing, okay so again. Let me tell you this thing once, if my value one is smaller than which value two, it means whom I have to place, value one has to be placed in the answer of pointer, then I placed it and moved the pow pointer forward from the array from which the value is taken. We were moving that pointer forward, okay now next, if this does not happen then obviously value two is going to be bigger, okay I know this thing, in the answer of p3, I placed value two after placing value two. What did I say P2 plus Ps means value to which was coming from array two, I moved the pointer to array two to pointer at, I moved forward P2 plus and after every case the pointer th has to be plus, so I added it with this condition. I have written it outside, it is okay, so I hope you have understood this part, if I return from here, whose return is my answer, then if I return the answer from here, then let's see once whether it is correct or not. Okay, I have done this, once I drew it and understood that we are doing it right, then I took this and went straight ahead and I took this and I wrote in this way, I wrote this, now I would have made two of them, your slightly different apple. Let's take it so that you can understand the thing clearly, take the second one so that we can understand the thing clear, Nama F 7 11 and Kama 1 So I made two arrays Okay, first of all what will happen as soon as I get both the arrays then I answer array what Whose length is equal to both, then we count the length of both T 3 4 5 6 7 8 So the answer of eight size will be made, so I make nature four f 6 and 8 is ok T f 5 6 7 8 mine It is done, now what should I do by placing the pointer, do another Y to place it, I placed the P2 here, my P2 is placed here, and on Y, my P, now let's move it slowly, do the proper Pv, the small head was still there. If it is even smaller then both the conditions are true and only one condition is checked. Now what will be the value of value one? p1 is smaller. If it is smaller then the array of p1 will come, that means three will come. Which one is smaller among three and one then it is smaller among the two. Our one will go in this condition, value one will be placed in the array of p3. Sorry, value one will be placed in two place. Because right now value one is big, hence the one here will be placed. What will happen after one place is p2 + p2 from here? What will happen after one place is p2 + p2 from here? What will happen after one place is p2 + p2 from here? Will arise and p2 will go here and after that what will happen is p3 + so p3 will be here ok what will happen is p3 + so p3 will be here ok what will happen is p3 + so p3 will be here ok after that it will loop again to check the condition if p1 is still small then will proceed again value one and value two will come out of both. Which is smaller than th and which is smaller than f? If value one is small then what will happen. Value one will be placed in our p3 and after that p1 pointer will come to the left and after that when it comes out of the fruit then p3 will also be plus. If there is a plus then p3 is fine here, I hope I am able to explain it to you very well, if you are facing even a little problem then rewind the video a bit and understand that this thing is fine, checked again now. Also this condition is true, after that if both these conditions are also true then both the values will be taken which is smaller among sis and f, values will be taken which is smaller among sis and f, values will be taken which is smaller among sis and f, this time p2 is smaller then p2 will be placed in p3 and after that p2 pointer will move forward first then our Which pointer should go ahead, if p3 pointer comes, then I have taken this pointer here, now we will check again which of the two is smaller, whichever is the smaller value of p1, then the value of p1 will be placed here and this time p1. The pointer will move forward first, after that our p3 pointer will move forward. Okay, so I have understood this thing, which of the two is yours, which one is small, our se is small, then what will happen if sen is placed here? And my p2 pointer will move forward, after that my p3 pointer is fine, so the same thing is written here, but now let's see which one is smaller among the 11 and which one is smaller among the 11, so what will happen is nine here. It will be placed, after that the pv pointer will move forward. After the pv pointer, p3 will also move forward. Now we need to look carefully. Okay, first thing, p1 is now equal to the array dot length and goes out, equal to the ray dot length. If this happens then this condition is false but still what is p2 True why p p2 is smaller than the RT dot length so it is still lagging behind now what will happen now look at the value of p1 if this condition is false Gai Falls means now this is done means in value one we are taking an integer zar dot max value, for now I assume it to be plus infinity, although it is a very large value, I am assuming something like just plus infinity. It also does not happen but I just assumed that it is infinity because it is a very big number so I assumed it to be plus infinity and here which one is smaller among the two, always the second pointer left will be the smaller one. 11 what will happen is it will go to this condition and will be placed in it and p2 will move ahead and what will happen after that p2 will move ahead p3 will also come now p1 will be checked again then the condition will still return false But this condition is still true for us and if another condition with operator is also true then we will get the entry. After getting the entry again p1, so what is still ours, meaning this condition is false means plus e value one in ps infinity. In value two, 1, which of the two is smaller? 13 is smaller, then it will come in this condition and 13 will be placed in it, after that p2 p p2 this time I come out, what will happen after coming out p3 p p3 It is okay after that, check again, this time this condition is solved, this is also my condition false, so now what will happen, this entire loop will stop, what will happen after the loop stops, will it return, my answer is as follows. The first task was this question, what was that first task that I merge both the arrays, so I have merged both the arrays, now it comes to finding my median, so now let's see in what way the median can be found if I talk about this array. So first I write the index in it and then let's see how the median value is equal to zero four f 6 So I have now what is the length of its array T 3 4 5 6 7 8 What is the length of the array A, what does it mean? This is an even number. In the even case, I just told you how to find our two medians, that is, leaving this one behind and this one of ours. If we want to sum these two, then basically what we need is the index of index. One, we need this one of the array. Index and one, if I look carefully, if I divide the length, then I will get the fourth index and if I divide the length, then what will be 4 minus 3s, both of them mean that I will get the median value within the even case, how is the array of which will be the answer? Rega its ok array dot length what is its formula being created is array dot length divided by two ok plus array of array dot length divided by 2 myve this is something like this ok this is my formula being created If I look carefully at this and also divide by If I look carefully at 8 by 2 4 then the fourth value is my sen Here sen is written plus array dot length 4/2 8/2 4 - 1 3 What is the array of length 4/2 8/2 4 - 1 3 What is the array of length 4/2 8/2 4 - 1 3 What is the array of 6 7+ 6/2 7 + 6 What is 13/2 What is 6 7+ 6/2 7 + 6 What is 13/2 What is 6 7+ 6/2 7 + 6 What is 13/2 What is my 7.5 So the median of this array my 7.5 So the median of this array my 7.5 So the median of this array coming out is 7.5 So here I have seen, coming out is 7.5 So here I have seen, coming out is 7.5 So here I have seen, now if I talk about the odd case that if the array's If the length is odd, then how will we do it, so I see, here I make an odd case, I wrote 1 2 f and f, so in this I want this index, so what will I do for it, basically its length is w f and If I add the index, then in this case, if I divide the second index by 5, then what will I get? Because integer division is on y, what is my direct formula becoming in the odd case, if I talk about the odd case. In Karuda case, my formula is being created as my array of array data let by let's see how we will be able to do it and we should also see the type casting part so let me go straight to myself then we will merge. Had written the function, now what will I ask for by calling the merge function? I will get the answer in the array. I called merge. I sent it to merge. I sent two arrays first. I sent numbers one number int inger array. I gave the answer. Okay, absolutely right. It seems to be fine till now everyone seems to be right now I will check what is the length of the answer if I wrote if answer dot length if it is mud two means even number is the condition of even I wrote if mud two is its zero then that There is an even case. In the even case, what is my answer? What is the answer? It will come. Basically, I wrote answer of answer dot length divide by 2 plus answer of answer dot length divide by my. We have just seen the formula, now what do I have to do basically. We have to divide it by two but what will happen if we give this answer in points then I will have to type cast it. What will I put to cast the type? Just put double in front. Now the double data type is that it basically takes decimal numbers. So what did I do here, double it, okay, so do it in this type, now if there was an odd case in others, obviously an odd case came in the others, above, the even case has been handled, how will my answer be made in this, okay, but if my answer is made, then return also. Now again I made Asar, I wrote I Asar, now what was there in D case, what was I to take only and only, I had to take the middle value, how will I get the answer of answer dot length divide byte, so I typed it once and ran it. Everything seems to be fine, but there is some mistake, what if I take a look, tell me, I wrote sorry, where will I get the answer from, will I get it from the merge function, what will I have to send in the merge function, will I have to send two arrays, sorry Nam One. numbers one comma numbers two so I saw it like this now let's do it ori sorry what did I do here my answer is jo come in double what did I write on y did I say the answer is y in the alphabet look sorry what did I do It writes 'R', 'Weble Same' did it, look sorry what did I do It writes 'R', 'Weble Same' did it, nothing else, ok, so this was quite correct for me, there are many heads, but keep going, ok, so I also need to be very careful in this, both my answers are showing correct, so I am If I submit it is also submitted, okay, I hope I was able to explain it to you well, I gave my base, but okay, and my answer came out from this top, so I hope you must have understood it very well, so See you tomorrow in the next video where we will be solving the next question. Thank you.
|
Median of Two Sorted Arrays
|
median-of-two-sorted-arrays
|
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106`
| null |
Array,Binary Search,Divide and Conquer
|
Hard
| null |
1,869 |
hello welcome back today I'll try to solve another lead code problem 1869 longer contiguous segments of ones than zeros so this means we need to fight the longest clean settlement of ones for example this is a 2 and for zeros the longest consecutive is one so two is more than one this is why we're gonna return a true for the second example they are equal so for the longest consecutive of ones it is a 3 for the longest consecutive of the zeros it is the three so it is not modern three is not more than three so we're going to return false so for such problems we need to recognize the pattern first so first of all it is a three or a array and it is also the contiguous segment it means the pattern is list groups so we can use the list groups attempted to solve the problems now let me do some purple reasons for the template so we're going to prepare a variable ones and zeros this means the ones will record the longest consecutive of ones and zeros will record the longest consecutive of zeros then I'm going to prepare the normal template I and N i is the first index and is the length of the array so for once it will start with 0 and 0 will also start with zero for the I index it will start with zero and for the string it will be length of s now I'm going to use the while loop so for while less than n I'm going to record a start will be equal to I and then I'm going to use the while loop less than n minus 1 and I'm going to tap from here it depended on the description of the problem because I'm going to text the same value so the f i equal to s i plus 1. if they are the same value so the iporter will be updated by one and once it goes out of the loop so we need to select two conditions if it is the same values of zeros or ones so we need basically we need to tag the start value if s start equal to 0 equal to 1 let's make it a one first it doesn't matter so if it is a y we're going to have our record so the ones should be equal to the maximum of ones with I minus the start plus one similarly you've got or updated you just need to update the zeros now let me see writing updating of the zeros should be equal to the max of zeros with the same yeah pair with me it's a little bit slow let me just copy the code to try to check if the copy and paste is fast faster than typing now it's the same I minus started by one after that we're gonna update the iporter will be shifted to the right by one now we can return the result if this once is more than zeros now let me run into that if it really works as you can see it works now let me submit it to tag if it can pass all the test increases by the way the template is the same basically we use I and a and with two while and start pointer will record the first I and here will be the same and inside we just need to check this condition the only difference we need to check the consecutive of ones and zeros you can use the S dot start equal to 1 3 1 to check if the same values as one or zero you just need to record two variables once as zeros finally you just need to return a once more than zero or not because this is dependent on the description we just need to return a Boolean value thank you for watching if you think this is helpful please like And subscribe I will upload more it could problem plexus
|
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 |
458 |
hey everyone this is priya and today we will see problem number 458 that is 405 so according to lead word this one is a hard problem but i think it's kind of met's problem and if you crack the logic then you can solve it easily so let's check out the problem there are buckets full of liquids where exactly one bucket is poisonous to figure out which one is poisonous you feed some number of poor pigs to the uh the liquid okay you fit those liquid to some pegs where whether to see will they die or not unfortunately you only have some minutes to test okay you only uh you have limited number of times to test so let's check out what they have given they have also given minutes to die that is if people drink that poisonous liquid then how many minutes they will take to die okay and they have given one input number of buckets and the second uh the third is minutes to test how many minutes we have to test so we have to retain the number of weights needed to figure out which bucket is poisonous within the allotted type okay they have given some examples so let's understand this from some example the first example is number of bucket is four minutes to die a pig will take 15 minutes to die and we have 15 minutes to test okay so let's say this is the first bucket and we start with p1 so we have 15 minutes to test and one pig will die in 15 minutes okay so how many tests we can perform in those 15 minutes then one we can perform only one test but if this if 15 minutes are over and this bucket is not poisonous okay then what will happen what will we understand is if this is not poisonous then this will be poisonous because we have test for p2 also to this book if in this iteration if this is not poisonous then this will be poisonous because it exactly one bucket from this four buckets will be poisonous okay so what we have understood from this is we can one page can tell can check maximum one more bucket can check okay one pick can check this many numbers minutes to test we have available minutes in which big die plus one this many buckets one fake will able to find out so from this how many buckets will need because here minutes to die by minutes uh minutes to test five minutes to die will be one so one plus one will be two so if one pick can check two buckets then for four buckets how many picks we will need two picks okay so this will be our answer let's uh check this from the second example we have four buckets minutes to die is 15 minutes to test this book so minutes to test divided by minutes to die okay plus one is equals to three this many buckets one pic can check one picture test this many buckets so big one will check three buckets and we have uh left with one more bucket so we need the second pick also so for this the output will be two like this we have written a code in python you will understand it easily we have initialized the number of pics initially as zero then we have found out that number of minutes to test okay the time we have provided to test and the time the pig will die after drinking that poisonous drink okay this plus one okay the pig can check one extra bucket so this raised to the power of number of picks if this sum is less than the number of buckets until the sum is less than the number of buckets we will increase the fix count we will increase right because this is less than four so we have increased the pet count from one to one we have added one more so this is only that case right we have uh increase the fixed function at the end when it is greater than or equals to number of uh buckets this sum will become greater than or equal to number of buckets then we will retain the number of fixed count what we have found out okay so by this your all the test cases will get passed let's run this code let's check out okay so is 40 millisecond and it is faster than this okay so thank you
|
Poor Pigs
|
poor-pigs
|
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
1. Choose some live pigs to feed.
2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time.
4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
5. Repeat this process until you run out of time.
Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_.
**Example 1:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
At time 15, there are 4 possible outcomes:
- If only the first pig dies, then bucket 1 must be poisonous.
- If only the second pig dies, then bucket 3 must be poisonous.
- If both pigs die, then bucket 2 must be poisonous.
- If neither pig dies, then bucket 4 must be poisonous.
**Example 2:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
At time 15, there are 2 possible outcomes:
- If either pig dies, then the poisonous bucket is the one it was fed.
- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
**Constraints:**
* `1 <= buckets <= 1000`
* `1 <= minutesToDie <= minutesToTest <= 100`
|
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test. How many states can we generate with x pigs and T tests? Find minimum x such that (T+1)^x >= N
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
1,353 |
in 1,353 of vítkov they have just put him in 1,353 of vítkov they have just put him in 1,353 of vítkov they have just put him in the weekly contest 176 it seems to me and it is called maximum number well-being changes called maximum number well-being changes called maximum number well-being changes tendency this problem is one of those whose description is a little far-fetched to the world description is a little far-fetched to the world description is a little far-fetched to the world it seems sought-after that it is a it seems sought-after that it is a it seems sought-after that it is a simple problem if you have the tools to do it if it is not one of those that you have many and eve and check and all that and it is a relax then what this is for now this problem is that they are going to give us a certain list of events that is an arrangement of arrangements each arrangement It is going to be an event and it has the day on which the event begins and the day on which it ends, so for example in the example here it tells us that the first event starts first, it will be on the first day and it will end until the second day the second starts on two the three on three or four then you must know how many events you can attend well that is to say go no you don't have to stay a whole element is no you have to be able to go to the event so for example in this case well you can go to all of them because the police the first day the second day the 3rd cough and from there nothing happens on this one on the other hand the first in everything the same well you can go to all of them because these two apparent ones apparently overwrite each other but no because this can say first day and this is the second day, so if you understand a little where the complexity is, that is, you have to go this one, or that the events overlap, that does not mean that you cannot go to both and you should check All of that is then well this program can solve a very simple way using a comparator then we are going to create the buy and well first what can be done a partner in an experiential arrangement according to me no but then the first thing we are going to do is to make a list of arrangements and we're going to go through all of them before continuing to explain how I'm going to solve it with a composer I'm going to fill out a list of these events and I'm going to order them by the day they end and then I'm just going to editing them all and giving the days law is very simple but if you don't know how to implement the comparator it can get very complicated so that is why it is important to study buyers we are going to start filling out our arrangement because now here the buyer is going to go we are going to use bands when they are necessary they do what code looks and is called complicated or well it happens to me goes through the wright dance and it would be there is a very good video of buyers that will put in the comments where it explains very well how they use i and that is important that we get those by the date by the iam and that they dig high explains why and now with it lessons point in shorts then there is a way to directly make the sun for example with the rai short and I'm going to investigate these if you don't know but if you don't save the list no and we're going to sort the buy in light with our comparator what's next for a day that we all have so we're going to find out our entire list and now well and they are ordered so nothing happens and something very important is to use a set to know which days we are already busy, that is also important and I missed it with this set. Let's see which days we are already busy so as not to occupy them anymore. print equal to zero until the event ends because there are events that can last several days or a single day. For example, this event here in example 5 lasts five days, so it is important to order them by the final day because if we order it by the initial day, we are already seeing this event on the first day and for example we could no longer go to this which is only the first day so we look for the last opportunity to go to that event so we are going to use and event afternoons 0 when from the first well with the event until and is less than or equal to the day where the event ends and more and then the event we are going to see we are going to look every day to see what day it is possible that our agenda is going to put let's suppose that this 7 is our agenda where We have been putting the events as we are going to put them, so yes does not contain that day, that is, if it would be, we have it free, then it was forgotten. I will always start by creating your variable with which you are going to count the result at once and seeing the result and the pse does not contain that day so say that we can go that event is a rediscovery we are going to put in that day and if you can't we continue searching until we can put it receive nothing is missing according to me I am not missing anything and it works for scarce that's how it works It doesn't work for everyone, for this one, let's see why, then in this case they would be ordered, saying that it is ordered, if it says that it announces four things, that doesn't make sense, it's just that it's saying that we're going to go to four, ah, of course, if we find it, we're not looking for anything. more and one is the solution
|
Maximum Number of Events That Can Be Attended
|
maximum-number-of-events-that-can-be-attended
|
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`.
You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`.
Return _the maximum number of events you can attend_.
**Example 1:**
**Input:** events = \[\[1,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
**Example 2:**
**Input:** events= \[\[1,2\],\[2,3\],\[3,4\],\[1,2\]\]
**Output:** 4
**Constraints:**
* `1 <= events.length <= 105`
* `events[i].length == 2`
* `1 <= startDayi <= endDayi <= 105`
| null | null |
Medium
| null |
894 |
rit code number 894 all possible for binary trees this is medium question let's get into it uh a full binary tree is a binary tree where each note has exactly one and two children so in this case this one is for binary tree no this one no only this one yes because the children is zero and this one also true because it has two children the general list of all possible binary trees with n nodes each element of answer is the root note of one possible tree each node of each tree in the answer must leave node value is zero you may return final list of tree in any order so no need to sorry okay let's check with the example one input is seven so in this case uh okay first we can make the left side is one right and then this one is the most five and then one five is same right in this let's think about this one five also either serve to one and then one three and then in this case three are there only one case to generate okay let's think about the five maybe there are the three case one is here another is this one going to here same as this one let's compare it this one now this one is moved to here and if seven also the two cases because this one here or another is this one here and then or notice this one is not here so one two three four five is the final how are you gonna do okay i initially i was going to use the equation to generate all of permutation of tree and each tree i will show you one technique that is return used return array through using equation uh i think that we have you have experience using the return value is one integer or string or object and then maybe some other people use the little values tuple but is there are not much person to use the written value is only so but if you master this kind of the technique maybe you can you're able to serve to more question like this okay first i will implementation first and then i will explain later first okay let's try first i will make the question name is build and then insert the name according to the number and then okay let's check okay let's make the base case first if and if n is zero we need to return if theory right because we return only we use array and then if n is one so there are only way right so there are mid return one three node and argument maybe no because if we did another input it automatically input the so use it and let's think about that if n is 2 and this 2 min is decimal we cannot generate the 4 binomial 3. so at this time we return so we can also combine you do this and or okay next we needed to output to return and then let's generate first reality creation and iteration to the one two summer three to sum of ninety five summer right and then make the left in where the slide build i so because this one will return so we will be able to use this one and then we also have to field n minus 1 that is the largest number 2 to the n at the range n and then minus n minus i and this one going to i to 0 to i and then this one going to n minus 1 2 i okay and now we have for the fan generate a new 3 node the value is 0 and then left and right and then and finish it we turn off and we just call build and put the initial vertices okay looks good awesome okay wow it's quite slow okay uh let's check time complexity we need the seven input maybe i think the time complexity is exposure because we need to uh um take time to make for final three almost around uh two to the m so and space complex here so uh the 2 to the n the same amount of the node so can you make it better that's right we can use what memorization so let's add memorization this one okay no need to put one to the memo to set then i will put here if n in memo just let it reuse it otherwise i needed to calculate generator output then i have to finish generally type 4 and reuse it okay let's check it out again ah a little faster than before okay let's check time complexity again at this time we make the one pattern this one make the one you want and then we just in this fight we just have to reuse when we generate this one we also do use this one and then when you generate this one we actually use and there many generates this one we actually use so we just make only one pattern only one so i think time complexity is if the seven is inputted i think that is almost the linear time and space complexity are also linear because we able to reuse any duplication thank you
|
All Possible Full Binary Trees
|
random-pick-with-blacklist
|
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tree where each node has exactly `0` or `2` children.
**Example 1:**
**Input:** n = 7
**Output:** \[\[0,0,0,null,null,0,0,null,null,0,0\],\[0,0,0,null,null,0,0,0,0\],\[0,0,0,0,0,0,0\],\[0,0,0,0,0,null,null,null,null,0,0\],\[0,0,0,0,0,null,null,0,0\]\]
**Example 2:**
**Input:** n = 3
**Output:** \[\[0,0,0\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Hash Table,Math,Binary Search,Sorting,Randomized
|
Hard
|
398,912,2107
|
454 |
hello everyone hope you all are doing well so i am back with another lit call daily challenge and it is lit called number 454 for some two it is a middle medium level question and i also feel the same so here the question is you are given for integer array uh it is one number two number three and norms for of length n return the tuple uh tuple i j k l such that is from zero to less than n and nums when i plus numbers to j numbers three k plus nums for l is equals to zero okay so so i think you understood that we have to find all the combinations which give us zero okay from so if you see the example one numbs one is one two nums two is minus two minus one num stress minus one two and numser is zero two so if you choose minus two one and minus one and two it will give you 0 as you see here and similarly if you take 1 minus 1 here again minus 1 and here 0 means this 2 minus 1 and 0 it again give you 0 so there are only two possible solutions so the answer is 2 example 2 here all are 0 so only one combination is possible 0 so answer will be 0 and the constant is uh number two numbers three numbers per can go to n which means 200 and all the value in nums one uh in the errors are from minus two to the power twenty two plus two to the power twenty eight so let's begin with an example okay so the first thing okay so the brute force one is uh you can do a n to the power four some uh for solution okay means you can i you can use for loop and you can iterate through all the element and try out all the possible combination okay but uh this method will give you tle okay because it's it is given that uh 200 is the value of n so it will be 200 raised to 4 okay so it is 200 to the power 4 so it will give you tle then one another approach is to make the complexity a bit low like you can try it out with n cube also uh here you can what you can do you can choose one of this adam and store it in inside a map okay let's i choose the nums for and i will store it to a inside a map or a set whatever you want so let's say take a map okay so that two i take two and i do take over zero and i insert this in inside it okay now you can apply three loop and keep solution so you can apply three loop and try to find out a possible way to uh to do the calculation like you can here 0 is presented and 2 is presented so if you are able to find a sum of minus 2 then minus 2 and plus 2 give you 0 so your you get one answer okay similarly if you manage to find zero from this three so it will be zero and again zero is inside so zero plus zero you will uh get our answer okay so this is 200 uh cube uh this is the complexity is 200 cube i think it will work fine okay so it should be eight one two three four five six okay maybe it worked fine but there is one more uh efficient way uh like you can also do it in n square also okay so n square is all similar to n cube solution okay so here you can see that if a plus b plus c plus d is equal to equals to zero it means that a plus b is equals to zero minus c plus d okay so it is equivalent to a plus b is equals to minus of c plus d okay so now you can so i think you can get an approach like what you have to do okay so what we will do we will try to make one combination for suppose we can make a plus b combination and we will try to find out minus c plus d okay so i will take two uh num let's i will take num1 and num2 you can take any of them and i add them and put them into our map okay so here it is one oh we have to take all the combination okay so it is one minus two it is minus one then it is one minus one it is 0 2 minus 2 it is again 0 and it is 2 minus 1 it is 1 okay and we are we try to find out its opposite version opposite means is opposite sign version okay from these two so whatever we get the combination from these two array okay we just simply multiply with a minus one okay so if it is if we get a negative value then we change it into positive and if it is if we get a positive value we will change this in negative okay so that it's negative positive after converting it will pair up with this elements and try to find out a zero okay for example uh if i try all the combinations it is minus 1 then it is minus 3 then it is 2 0 is 2 and 2 is 4 okay and then minus version is 1 3 minus 2 and minus 4 okay so now you can try to find these elements inside okay so i hope i copied the all the correct numbers yeah then whenever you find a number which is a present inside okay you just increment the count okay so this is the code i have taken a map and i uh take an account variable then i trade through nums1 and num2 and find all its pair okay i just add them all the element together okay means one by one and uh put it into our uh map okay so what we will do we just find out again i trade to the other two map and i just take out the sum and i just multiply it with minus one because we need to do zero so if my ab is in positive so it is required that my bc will be negative okay then only they can make a zero so after that uh i just find out if that number is present inside our map or not okay if it is present then we just add its frequency okay like if a number let's say one is present fourth time okay in the map so i will increase my account by four okay because there is four possible uh combination available and then i just simply return the count so hope you understand the code uh let me run it is very easy code just you need to think the intuition okay so it is solved and i will provide the code and uh the question link in the description so check it out and keep coding see you tomorrow bye
|
4Sum II
|
4sum-ii
|
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
* `0 <= i, j, k, l < n`
* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\]
**Output:** 2
**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0
**Example 2:**
**Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\]
**Output:** 1
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `n == nums3.length`
* `n == nums4.length`
* `1 <= n <= 200`
* `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
| null |
Array,Hash Table
|
Medium
|
18
|
29 |
What is given in the unit Welcome back to my channel and you are going to solve divide by individuals switch problem statement that you have been given two integers to divide and adventure. Here it is said to divide two numbers without using multiplication. Division and Mode Operator OK and here it has also been said that the text with decimals in the voucher should be ignored and it should not be given. But here if you get 135 then point is free. Play PowerPoint 345, bloody people have come on imo, okay, all you have to do is edit, okay, and here I have also given a note, don't kiss Jeev Vihar, Delhi, will and environment, very stolen integers, win32, after signing in, teenagers reign - to the win32, after signing in, teenagers reign - to the win32, after signing in, teenagers reign - to the Power 31.2 Deepawati one minus one for this Power 31.2 Deepawati one minus one for this Power 31.2 Deepawati one minus one for this problem everyone in this affair is a joke the creator for brain research in the written 2531 - 1st question test click list bank - - 1st question test click list bank - - 1st question test click list bank - 2014 0 - - - 251 ok taste ever have to keep this in mind and also you have to multiply division Don't use end mode operator. In the name of work heaven, you will see that the time of divider has been given and Teeja has been given by cheating, then see what should happen with it, something can happen through this report, here you can cook number state, it can be uncountable. Okay, so this point is so many points that we have to ignore it, so let's get the answer here, so how can we solve this problem, now we come to our approach, we have this problem. We can use Addition, we can use Subtraction, but we cannot do Division A Multiplication Science, so here we did an example, let us understand our approaches, what to ask, what is going to happen to them, okay, what do we do? Let's take a department, okay, what is yours, the division is 128 and what is your division, okay, that is pizza bread, 100, now let's come, how will we normalize it, what will we do, we will take one in which we will kill the division, okay, we will add depression. And one of our control which will always be what will happen from the butt okay all ours which is first pre quarter okay this season is the sequel account Malvan equal okay then what will we do we will double this six double this also then we will check how less What time will we move forward, it will become sixty, it will go to you, then it will be less, we will move forward from that, it will become cool and yours will be added, okay, this is also less, we will move forward, inverted 6 is also less, we will move forward, 96 and this is thirty-two. We will move ahead, this will be your 192, this is thirty-two. We will move ahead, this will be your 192, this is thirty-two. We will move ahead, this will be your 192, okay and this first shift, now you will see whether it is more than 120, we will not consider this point, now what are we going to do in our result, this three to someone will add it here 30dec This is our answer, what will be found in it, here I will get the burst and let's see, it will burst in the final result till now, whatever is yours, now you have come till the add here, you will get the award of 1962 from 120 - do that, you will award of 1962 from 120 - do that, you will award of 1962 from 120 - do that, you will subscribe. So here you will get the 20th floor, okay, got it, now what are we going to do, again we will take the thing, start the end account, we took it, okay, double it, 6, cut it to two, double it, 12:00 from this. If it is double it, 12:00 from this. If it is double it, 12:00 from this. If it is less then let's move ahead to see who has reached 100. This phrase is equal. Moving ahead, peel the egg in the fastest way. Is it possible to seat it? If this part is not your consideration, then you will do art in this egg yolks result. Now 2474 tell you this. Explain - If you do then what is this, it will be tell you this. Explain - If you do then what is this, it will be tell you this. Explain - If you do then what is this, it will be 50, when you have nothing left in division in difference, then you will not move forward and this is the final result, okay, this is going to make you very hot, now let's come to the part of breaking it. But look at the web, this is yours which is given to you, this is the demand for this here, as soon as your inch means OK and division - one, so what will we do in that condition, we will OK and division - one, so what will we do in that condition, we will OK and division - one, so what will we do in that condition, we will do internet stunt on divide, whenever your interest is there. If there is Milan and TV Sharma Pawan, then we will do this condition comment and what is here, we have converted the wall and divisional into login things, first we have taken a result that we are going to add the option to eight in the details. It is okay for us that the marine commando was killed, it is okay and how long will we do this as long as our division is there, which will be the least daily commodity dividend divide and rule will be the least, will take a front, Samadhi will be on 6th and 121 start of Okay, then what will you do, this will be done till you understand, okay, if you think equals to electronic items daughter, this event - Samosa, what I this event - Samosa, what I this event - Samosa, what I told here is going to happen, okay then you will do this and from time to time You will take it, rape will keep happening, ok, you will unite it, OnePlus One Two will become two plus two or not, by the way, do this here, keep reading, here you have to keep adding the account as well, double here, you will keep becoming the leader, ok then you When it meets your accident, what will we do in that condition, this volume will be the return form of the answer, if it will not go inside then I will contact you about its result and now the turtle is divided, it will attend the final back time, we will do that. Here we were doing right dynasty do yaad gems we were doing dhamaka accident so 96 this is our final we were doing fati ke amazon r and 1962 ka karte 137 ab - color hai to aap country for mil raha tha ab - color hai to aap country for mil raha tha ab - color hai to aap country for mil raha tha 2014 you are watching You will do the same here and see Marwar. Till the time you get back to Gionee, you will remain subscribed till this point. Till then you will do it rate wise and go out from here. Okay, you will get the final result. You will then check that the divided end is there. Is there anyone of yours in the division, for the policy developed, if you both of them are negative, one of them is negative, then the answer is said, but I will be the plate, now - you will get the result, otherwise will be the plate, now - you will get the result, otherwise will be the plate, now - you will get the result, otherwise positive result will be tented here, okay then code branch. Here we submit something Renuka, okay, it has been included, thank you.
|
Divide Two Integers
|
divide-two-integers
|
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`.
Return _the **quotient** after dividing_ `dividend` _by_ `divisor`.
**Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`.
**Example 1:**
**Input:** dividend = 10, divisor = 3
**Output:** 3
**Explanation:** 10/3 = 3.33333.. which is truncated to 3.
**Example 2:**
**Input:** dividend = 7, divisor = -3
**Output:** -2
**Explanation:** 7/-3 = -2.33333.. which is truncated to -2.
**Constraints:**
* `-231 <= dividend, divisor <= 231 - 1`
* `divisor != 0`
| null |
Math,Bit Manipulation
|
Medium
| null |
65 |
Hello Hi Everyone Let's All The Facebook Interview Problem Ballot Number 100 This Problem Is Survey Number Can Be Split Up To In This Complex In Order To Decimal Number And Interior Optional Access Point Peeth Mauli And Capital In The Following And Jo After Explain This Must Where Integral Part And With Food Habits Can Wear Decimal And Integral Parts And Even To Access Point Is Option So Lets Blood Group In This Possible For The Candidates Will Not Represent Deposit K Invented Number Valve Vocational Experiment And Capital Fuel Surcharge November-December Mid-Day -Mill Number 91 Split Up Into Mid-Day -Mill Number 91 Split Up Into Mid-Day -Mill Number 91 Split Up Into Complaints In Software Can We Channel Spine Character Plus And Minus Interesting Facts Of We Informative And It's At Least One Digit For A Don't Sudhir Vid Flirts With Water Reservoir Of Water Can We Do It Only If You Liked The Video then subscribe to The Amazing Can We Subscribe Number 90 Number Freud And Side Par Duniya Be Lit Decimal Number Date For Entries Mode Jayenge To In Tips Can Be Split Up To In This Complex In Order To Be In Individual Can Be Option Plus Minus And 1000 subscribe numbers and invalids number to do subscribe number invalid subscribe characters more than 1000 plus minus sign in hindi in this and different characters like this is my number digit slider from the last digit of integral part of this rule six digit number and similar subscribe this Video not here a video plz mode on play list 3 quiz hindi spring and 1006 and its minus plus se zoom invalid notifications of students in the water can be simple number loop withdrawal decimal number one side and off side subscribe Service for restaurant virva left 56.15 Service for restaurant virva left 56.15 Service for restaurant virva left 56.15 integral negative integral notice of valid after explain is plus sign label light in this birth of birth numbers payrolls they can have sign this only your character s well s just after also access point character moral banner important point to 9 text Listen this air base scent of characters which can be found rules to solve this problem should avoid from and plus and minus election will define rule subscribe this channel first number will return falls over it's al-sudais is hider no like subscribe and al-sudais is hider no like subscribe and al-sudais is hider no like subscribe and share And subscribe tours subscribe our Channel subscribe number 90 number to solve this problem solving problems subscribe number track andher on google also create another explain to bring the real x porn in the present weather they have seen in this experiment not only and others and third Arrangement Don't Know No For This Subscribe Digit Numbers Peru End Of The Number Very Positive Or Negative Can Only After Which Will Be The Result Of This Benefit River From This Satisfy Him In Return For Liking Validates Chilli One Indexes Current Index Is Not Zero And Character add this is not spoil the delegation will return more that they will see effigy in witch acid number to subscribe The Channel this sub dot bihar dot bigby politician dot fluid informs and this BRC doctor d explain in details of life in these days After 10 Minutes Subscribe Now Star Gold Live With All Rules Will Declare Variables And Subscribe Withdraw From Where Is Lad To Know What Is Loot Quality Cassie Character Medical Sciences Cotton Mostly Acted In Witch Acid Tractor-Trolley To Seervi Subscribe Behavior C Is Capital Of But subscribe and subscribe the Channel subscribe for Live Listen a text message nov21 number five years unseen that to tech and wealth and number of another scam and daughter to check if I am already subscribe egg white subscribe positive eye is 98100 - He is this 98100 - He is this 98100 - He is this Robert D Two Different Dot One Plus One Hai Ki Vishwa Not Valid Dot Wave China And Arrow Is Video Channel Dot Wave Plus One Another Lord Vishnu But subscribe Video subscribe and subscribe the Channel Please subscribe and subscribe button subscribe To My Channel and Share in your Circles for this will help your friends and sisters where is my channel thank you
|
Valid Number
|
valid-number
|
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the following formats:
1. One or more digits, followed by a dot `'.'`.
2. One or more digits, followed by a dot `'.'`, followed by one or more digits.
3. A dot `'.'`, followed by one or more digits.
An **integer** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One or more digits.
For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.
Given a string `s`, return `true` _if_ `s` _is a **valid number**_.
**Example 1:**
**Input:** s = "0 "
**Output:** true
**Example 2:**
**Input:** s = "e "
**Output:** false
**Example 3:**
**Input:** s = ". "
**Output:** false
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
| null |
String
|
Hard
|
8
|
347 |
Hello friends today I'm going to solve liquid problem number 347 top K frequent elements in this problem we have been given an integer array knobs and we are also given an integer value K and we need to return the K most frequent elements from our integer area norms and we could just return the answer in any order so here in this example we are given the error numbers and the value equals to 2 for K so the output here is equals to 1 and 2 and Y is output 1 and 2 let's see since the value of K is equals to 2 we need to return the two most frequent elements right so that means which are the two most frequent elements the first most frequent element is equals to 1 here the second most frequent element is equals to two so basically we found our two most frequent elements right so that is what we return those keys only the value of that element in the form of our array as output in this case we have just one number and the value of K is equals to 1. so the output here is also equals to 1. now let's look at the constraints so the length of the nums array varies from 1 to 10 to the power 5 the value varies from this range and the value of K is in the range 1 to the number of unique elements in the array which means that the value of K will not exceed more than the number of unique elements in the nums Arab suppose like in this example we just have one element here but if the value of K was equals to 2 that would be an invalid question so here in this case the value of K cannot be more than equals to 1. similarly in this case the value of K could be at most 3 because there are three unique elements that is one two and three but the value of K cannot be more than 3. so that's what this problem is about and this algorithm asks us to solve it within of n log of n time complexity and let's see how we could solve this problem so here we are given um this Norms array right so let's look at this problem with this given example and the value of k equals to 2. so how do we identify the most frequent elements for that we need to know the frequency of each of the unique elements in this area right so we need to create a map for that map to store the frequencies of each unique in tunic element right now in this map let's just create the values so what will be the value for one the frequency will be close to three four two the frequency will be equals to 2 for 3 the frequency will be equals to 1. so now we have the frequencies how do we calculate the frequency well to calculate the frequency we will start from the first element in this array and then um the initially the value of frequency for each of the element will be equals to zero so now we found that element one time the frequency will be increased to one the next time it will be increased by 1 to 2 the third time it will be equals to 3 and so on for other elements as well now once we have the frequency um in this case we just know that the first two elements in the map are and the first uh like the most frequent elements right the two most frequent elements so how do we actually get these two values what if in case we had this value 3 at the top so in that case um we cannot take the first two elements right so what we are going to do is we are going to um sort the value uh the elements by the values that is sort the keys by the value so what we will do is um sorting Hood be performed um using the values right we I already told that we sort the keys by the values so what is the value of three it's one the value of 1 is 3 value of 2 is 2. so while we sort we are actually forming an array so we sort um and then the most highest frequency will be in the first and the list will be in the last so now we get the sorted keys it by their frequencies now we only need the for most two most frequent elements right so we only need the first two elements because the first two elements are the one with the highest frequencies then the rest of the elements so we are actually going to slice this array from 0 to the value of K which is 2 equals to here so this will result in an array which only has the first two elements and this is our final answer right here as you could see here so that is how we are actually going to solve this problem we create a map to store the frequencies of each unique elements once we have the map from the map we are going to create an array which is sorted um based on the frequencies of the keys and the array is actually the key is not the frequencies it's those are the keys so now these keys are sorted in descending order we'll take the first K elements from the array and that will be our result so now let's write our code so we need a map so let's create a map empty map and then fill the map with the values key and values so here our key will be the nums if our map has if the map doesn't have the key then we are going to create that key which is initially equals to zero and then um we will increment the value of key every time we encounter it since we encountered this for the first time um the value is equals to 0 and then the count at that first time is equals to 1 right 0 plus is equals to 1. so that is how we find our frequency now once we have found our frequency we create we sort these map uh the key is based on the values so how are we going to do that so let me just create a variable and then our map we are going to convert it into an array so first we're going to convert it into an array of keys and then those keys will then be sorted based on the values so sort those based on the values of those keys so we are since we will be sorting it in a descending order um what we'll do is we take the value of B minus value of a so we are going to use this Lambda function here to sort it in the descending order based on the values right map B will give the value of the key B and this key B and key a are the will be the values of this um array and then once we have sorted what we need is we just need the first K elements right so now we will slice it for the first K elements so this array actually is our final result so we return our final result that is array and instead of doing this what we could do is we could just directly return this and remove these extra variable that we created so now let's try to run our code and look for any errors okay oh so this would be keys all right let's try to submit it now awesome so let's look at the time complexity um for the for function this iterative function since we are iterating over each of the element in our Norms array and if the length of the nums array is equals to n then this would be of n-time equals to n then this would be of n-time equals to n then this would be of n-time complexity and here in this case forming a map is of end time complexity and once we have formed the map we then sort that map right so sorting is n log of n so that would be a total of n plus and log of N and then we slice it over K elements so this whole will be n plus n log of n Plus K but we are just going to take um the maximum out of all those um cons those variables right so that would be total of n log of n time complexity here so the time complexity e becomes n log of N and the space complexity is O of n because we are storing each of the elements in our map and if someone doesn't understand what I have done here so since our map here is a literal object it's not a JavaScript map object here so we need to uh we need the keys of that map object right so we that is why we do object dot keys if we wanted the values of this map then we would have done object dot values and if we wanted both uh keys and values that we would do object Dot um entries and map within the parenthesis and this triple dot is um it's called as um what's called spread um sprayed it's called spread uh yeah it's called spread something I just forgot that I'll uh um write down in the description below once I remember it or you could just uh comment it on the comment down below okay so hope you like this solution um let me know in the comments down below and thank you so much for watching this video so far
|
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,790 |
hey everybody this is larry this is me going over q1 of the weekly contest 232 um i think there's a lot of ways to do it given that n is equal to 100 i am i feel a little bit sad that i actually took almost two minutes uh on this one to be honest because usually i'm really fast on this but i think i was just very not confident about it uh but yeah but the idea here is just implemented thing and there's a couple ways to do it i'll show you how i did it um but just and the way that i did is actually linear but it's really not necessary you could just do n square um just pick two end points swap and see if they come equal and that's actually n cube even for the equal but it's fine because this n is equal to 100 but the way that i did it is linear and i did it this way during the contest it's still but it's still yucky a little bit awkward so i don't know how i feel about that this is linear time linear space um you know uh you could also say that this is actually technically constant space or at least uh of alpha where alpha is the size of the alphabet because this will have at most 26 entries given that it's lowercase english so maybe it is an event spaces or one space or alpha space but it is all of n time um but basically what this is saying is okay if the frequency map is not the same then we return force because that means that uh letters exist in one word that does not exist in the other word um here if the strings are equal then we just return true because well the ego returns true otherwise we look at the number of places where they differ if it's exactly two then this is good because then you know that's how you know it's one swap away that's the definition of one swap away is that the two places that are different um the definitely cleaner ways of doing it i was i don't know what i was thinking this contest a little bit tired maybe but yeah uh let me know what you think linear time constant space or of alpha space yeah watch me sub it live in the contest next um hmm you oh uh yeah thanks for watching uh let me know what you think about this prom set uh it seems like it's been it's slightly easier than usual but uh yeah hit the like button to subscribe on drama and discord and you know you take care of yourself uh and yeah to good health to good mental health i'll see you next week bye
|
Check if One String Swap Can Make Strings Equal
|
lowest-common-ancestor-of-a-binary-tree-iii
|
You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`.
**Example 1:**
**Input:** s1 = "bank ", s2 = "kanb "
**Output:** true
**Explanation:** For example, swap the first character with the last character of s2 to make "bank ".
**Example 2:**
**Input:** s1 = "attack ", s2 = "defend "
**Output:** false
**Explanation:** It is impossible to make them equal with one string swap.
**Example 3:**
**Input:** s1 = "kelb ", s2 = "kelb "
**Output:** true
**Explanation:** The two strings are already equal, so no string swap operation is required.
**Constraints:**
* `1 <= s1.length, s2.length <= 100`
* `s1.length == s2.length`
* `s1` and `s2` consist of only lowercase English letters.
|
Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA.
|
Hash Table,Tree,Binary Tree
|
Medium
|
235,236,1780,1816
|
223 |
Hello my dear friend so today we are going to solve rectangle area problem so this is lead code challenge so what will be given to us ok so coordinates will be given to us ok so bottom left co-ordinate will be bottom left co-ordinate will be bottom left co-ordinate will be denoted key ax1 A1 And top right corner will be denoted by ax2 ay2 so this is ax1 a/1 this is ax2 a/2 for second d this is ax1 a/1 this is ax2 a/2 for second d this is ax1 a/1 this is ax2 a/2 for second d bottom left will be x1 b / bx2 dy2 and we need to bottom left will be x1 b / bx2 dy2 and we need to bottom left will be x1 b / bx2 dy2 and we need to calculate d total area covered by d tu rectangle ok so What C Need You Do C Need You Calculate D Total Area Date Is Covered By Two Rectangles Ok Suppose D Area Covered By First Rectangle Is Let's Say 50 Area Covered By Second Rectangle Is 40 So Total Area Covered Will Be 90 But Every There Is Same Area Which is coming common so this is counted tis so what you need to do if you are trying if the rectangles are overlapping then you need to find the common area which is being calculated so and then you need to subtract that common area and then you will get Our final solution so c are going to c if you are going to find d length of this what will be d length so it is 3 + 36 and if you are going to find 3 + 36 and if you are going to find 3 + 36 and if you are going to find height of this is 24 so 24 is d area of d height of this is 24 so 24 is d area of d height of this is 24 so 24 is d area of d first a Rectangle Similarly for d second rectangle length is 9 and breath is 3 so 27 but d a date is same area which is coming common so in d figure you can see date it is like zero tu three so this is d length which is coming common And from zero tu vich is coming common okay so for d first let me generate I will show you for d first rectangle what is d area it is 6 * 4 = 24 perfect let me erase all of this 6 * 4 = 24 perfect let me erase all of this 6 * 4 = 24 perfect let me erase all of this and for d second world what is D area it is 9 * 3 27 perfect so let me area it is 9 * 3 27 perfect so let me area it is 9 * 3 27 perfect so let me write every I hope it is clearly visible to you so area van will be 6 * 4 date is 24 area van will be 6 * 4 date is 24 area van will be 6 * 4 date is 24 area you will be 9 * 3 27 and nine if you see d you will be 9 * 3 27 and nine if you see d you will be 9 * 3 27 and nine if you see d common area it This is from zero you three in you six so common area is six 3 * 2 date is six so total area will be 3 * 2 date is six so total area will be 3 * 2 date is six so total area will be 24 plus 27 minus six so if you are going to solve this what you are going to get so if you are going to solve Both of them you are going to get 21 and if you are going to add both of them you are going to get 45 so in output you have go d values 45 ok so in output you have go d values 45 ok so in output you have go d values 45 ok so situation can be anything ok are not sir date are not sir About d position of d rectangle it is not sir date a van will come every b1 will come every after meet b possibility of this also date d van come every a van come every meet b possibility of this also ok a1 is this b1 is this so If you are going to find D total area covered which will be equals to D area triangle is b1 and smaller is A1 ok give me also other situation since both are completely separate out so each is no common area so total area will be area of first And total area will be area of first And total area will be area of first And area of second ok rate can be multiple area of second ok rate can be multiple area of second ok rate can be multiple cases and c need you hand all of date cases and then c need you write d solution for d se and c are going to get coordinates like this ok and you have already seen d diagram perfect so i Hope you have go d question exactly what they are asking now you can pause d video for un minute and a tu and you can try to write d solution for d say ok so I hope you have go d solution not only because you have trade d Solution if you have go it well and good adervise I will explain you solution approach ok so this is d diagram date I will be making so let me see this is something like this ok so d coordinates R - 3 x - 3 x - 3 x 1 a van Area ok this length and what is it height b area let's say b van so it is again b x tu - bx1 * other van can fight d in task is tu find d common area so final answer will be equals tu A1 + b1 - common area tu A1 + b1 - common area tu A1 + b1 - common area Okay so I give you completely separate out d value of c will be zero okay so ho c are going to solve this c are going to show you d concept of projection okay so let me zomatout and I will tell you how it is projection suppose this is D line nine if you want to find projection in x coordinates C are fine so this is ax1 coordinates this will be can be on d right hand side ok and if you want i can take d ander cases also dat a and b are both separately ok so it will be a x van x tu dx1 dx for ab and c can interchange this case ok they will Deal with all this d three okay so first of all we were finding d common area okay so let us take d example of this so every what you need to do is subtracting ax2-bx1 so this is this common area every common ax2-bx1 so this is this common area every common ax2-bx1 so this is this common area every common area is bx2- aky hair common area is zero area is bx2- aky hair common area is zero area is bx2- aky hair common area is zero perfect nine see need tu check if you are getting ax2 and bx2 mains ho see will get tu no date which term will come first ok try tu observe d pattern bx2 so date is something which is going on in these terms Coming on D left hand side in this scenario In D second scenario B Are doing so if you are going to c d diagram ok let me change d color of d pen ok it will be it every for you identify perfect so every c are all acting it is bx1 and ax1 so what is bx1 and x1 they are On d left hand side nine tel me van thing dx1 is coming on d right hand side ok if c take this scenario this is d maximum value ok and in this case this is coming on d right hand side so what c are taking Maximum of ax1 and bx1 and this is our I am going to increase d size so date you will be able to see it correctly or not so minimum of ax2 what is ax2 this is -3 and is -3 and is -3 and maximum are going to see in d diagram also d common length is threely from 0 you three it is 3 Only it men our code is giving as d correct value nine van must have d doubt tha what see will get in this in arriya ok you should have this doubt suppose this is d coordinates zero come zero this is d coordinates four come four this is d coordinates you get this d coordinates let's say 6 ok let's say this d example what is ax2 and bx2 what is d value 6 so what is minimum is you minus maximum of ax1 and bx1 so maximum force 2 - 4 will be Means you are saying date 2 - 4 will be Means you are saying date 2 - 4 will be Means you are saying date common length is -2 which is not correct means if someone is common length is -2 which is not correct means if someone is common length is -2 which is not correct means if someone is saying date there is no common length and date is in negative it means date is incorrect it means if x < 0 it means common length is zero it Mins d < 0 it means common length is zero it Mins d < 0 it means common length is zero it Mins d c will become zero ok so from c can right for d a also a will be again minimum of a /2 b/2 - maximum of a y1 b1 ok so this is /2 b/2 - maximum of a y1 b1 ok so this is /2 b/2 - maximum of a y1 b1 ok so this is d approach date c are going to solve this problem Okay so first of all I am going to write for d area van so aaj c have already seen what is area van it is text tu mines a x1 x2 - bx1 - bx1 - bx1 * find d common x common so x will be minimum of ax2 bx2 dx2 Okay say thing what do you need to find in d because of area calculation a and what will do if Not Basically Common Area Something Common Give C Will Be Updated OK Respect Vice C Will Not Be Updated And What C Will Do C Will Return Area One Plus Area Too Mines Common Area Solution OK Give I Have Go A Lot Of If Condition But D Main Approach Was this ok projection approach icon say so whenever you see subscribe minimum so you have written minimum let you have seen after practicing what are the digits are using and let you try you observe d pattern weather it is maximum minimum something like This and let you calculate dx you go date Have approach this problem ok if you have not go this problem come at van time it's ok I also try seven to at time give after taking sam hints I go this solution ok narmade sam possibility date you not and get this solution come de van Go ok so I hope d approach is very clear to you if you like this solution you can let me know in d comment section it will make me completely happy if I will get you know date it is helping you and you can share this video with Your friends and all ad members are learning python ok thank you
|
Rectangle Area
|
rectangle-area
|
Given the coordinates of two **rectilinear** rectangles in a 2D plane, return _the total area covered by the two rectangles_.
The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`.
The second rectangle is defined by its **bottom-left** corner `(bx1, by1)` and its **top-right** corner `(bx2, by2)`.
**Example 1:**
**Input:** ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
**Output:** 45
**Example 2:**
**Input:** ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
**Output:** 16
**Constraints:**
* `-104 <= ax1 <= ax2 <= 104`
* `-104 <= ay1 <= ay2 <= 104`
* `-104 <= bx1 <= bx2 <= 104`
* `-104 <= by1 <= by2 <= 104`
| null |
Math,Geometry
|
Medium
|
866
|
1,897 |
Hello everyone Welcome to my channel Here I solve problems Lead code today task number 1897 rearrangement of letters to make a string of strings equal we are given an array of strings Words in one operation you can select two indices in each of the two strings and swap characters We need to return True if possible so rearrange the letters in the words so that the lines will be equal like this Let's try to solve this what we can do like this also we need the lines to be not empty final equal lines like this Apparently one of the options that should work is we need to count how many we have of each from the letters in all the lines taken together and see if this number is a multiple of the number of words, then we can rearrange the letters so that these lines will be equal, if some letter is not enough for all the lines, then we cannot make them equal under any condition let's do this, what we need for this, first of all, we need to know the number of our lines N for this function the Word parameter Next, we create a dictionary in which we will count the number of each letter in the Def dict function with the int parameter, a useful function it returns zero if a key is passed that does not exist in the dictionary So now let's go through two cycles First through the words and now inside each word by letter and increase the number of each letter plus equals one Now we have a dictionary in which the keys are letters and the value is the number of letters that are in the dictionary Now we can go through all the letters and check So we don’t need the letters themselves, check So we don’t need the letters themselves, check So we don’t need the letters themselves, we need their number, so we can call the function then it won’t be the function then it won’t be the function then it won’t be the same, what matters to us is that if division by the number of words is not equal to zero, in this case we return if all the letters, their number is divisible by the number of words, which means we return this whole solution, quite elegant. Let's check the tests like this. Let's see what's wrong with the work being returned, but yeah, there's an error in the inner loop, not Char in, that is, every letter in every word, we check the tests again, yes the tests passed, we check the solution, it's quite effective That's all for today, thanks for your attention. See you tomorrow
|
Redistribute Characters to Make All Strings Equal
|
maximize-palindrome-length-from-subsequences
|
You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_.
**Example 1:**
**Input:** words = \[ "abc ", "aabc ", "bc "\]
**Output:** true
**Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ".
All the strings are now equal to "abc ", so return `true`.
**Example 2:**
**Input:** words = \[ "ab ", "a "\]
**Output:** false
**Explanation:** It is impossible to make all the strings equal using the operation.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters.
|
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
|
String,Dynamic Programming
|
Hard
|
516
|
225 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem implement a stack using cues i think this is a really good problem for beginners to kind of get familiar with stacks and cues and the relationship between both of them so a stack is a lifo data structure last in is the first value out so basically if we add a value here and then we add a value here right we add values in this spot but we also remove values from the same direction because the last value that we just added three needs to be the first value that we remove so we remove the three then the next value that we want to remove is the next most recently added value which is a two so we remove it and these operations adding which is called pushing and popping which is removing are both done in big o of one time and constant time now there's other operations like top and empty but those are pretty trivial and really easy to code up so we're not going to focus on those and in this case we are told to implement this data structure with a queue and actually we can we're allowed to use two cues and the follow-up is to use just a single queue follow-up is to use just a single queue follow-up is to use just a single queue but i'm just gonna start with the follow-up which is using a single queue follow-up which is using a single queue follow-up which is using a single queue i don't think it even makes sense to do this with two cues the thing i will mention too is don't get hung up on implementing these stack operations in big o of one time because it's actually not even possible we can push values in big o of one time but we can't pop we have to pop values in big o of end time if we try to implement a stack with queues so let's try this out well what exactly is a queue well a queue is the data structure at least is similar to how cues work in real life it's like a line right a line of people if we add a value adding it is pretty similar to how we did with a stack right we add a one now we add a two now we add a three right we add values to the right side but the difference is instead of removing values from the right side we're going to remove values from the beginning from the left side right which is the opposite of lifo data structures it's fifo first in first out so if we're removing a value first we remove a one now we next we'd remove the next value which is two then the three etcetera so you're probably wondering how can we use a queue to efficiently implement a stack and the answer is it's not really possible to do it super efficiently but it is possible to do it and i'm going to show you how so suppose we added some values right we add a one you know this is what it would look like in our queue and then we add a two this is what it would look like in our queue right adding values is the same and let's say we wanted to know okay what's the top value of our stack the top is the most recently added so from the right side we just get the value it's a two now getting that from our queue is also just as easy we just look at the right most value right we're not removing it we're just looking at it which is easy to do you know doing the empty operation is also pretty easy we just take the length of the queue it's non-zero therefore it's non-empty non-zero therefore it's non-empty non-zero therefore it's non-empty pushing we just kind of showed how we can push values but what about popping that's the hard operation for us popping it's going to have to be implemented in big o of n time where n is the size of the current q because remember we want to at least in our stack we want to pop from the top we want to pop from the right we want to remove this to value but we can't do that with a q we can't remove from the right we can only remove from the left so we still have to remove it though so this is our only option so we're going to start removing from the left first we're gonna remove the one value it's the first value but we know it's not the right most value that we were looking for we're not done yet but at the same time we weren't looking to remove the one should stay in the queue so what we're gonna do is actually just add that one back to the right side of the queue because that's the only way we can insert values into the queue next we're gonna pop the next value and we know this is the value we were looking for because there were two values originally in the queue this is the second value that's the value we were looking for we pop it and then we return the true not the true the two value right uh and you can see that this is what the q ends up looking like after we're done right it just has a single one value and when you compare it to what the stack would look like it's exactly the same right so the only downside to the queue is it takes o of n to remove a value if we're implementing it as if it were a stack so that's the idea now let's actually go ahead and code it up let's code it up so in the initializer or the constructor we're just going to use a single data structure aq in python it's implemented with a deck which is a double ended cue but we won't use any of those advanced features the double ended queue features we'll just stick to using it as if it were just a regular cue so pushing is one of the easy operations we know that to push we can just go ahead and append it to the right side of the queue right so the x value the input value is just going to be added to the queue that's really easy we're going to save pop for last so let's do top is returning the top value the most recently added value so we can just get the rightmost index in python it's really easy we can just take negative one and that'll return the rightmost value of the queue or we could just take the length of it minus one either one works but we're going to return this and that's all we need to do for empty we're just going to return we want to return true if it is empty so basically if the length of self.q is basically if the length of self.q is basically if the length of self.q is equal to 0 then we return true if it's not equal to 0 then we return false it's not empty now for the last one pop it's also not too bad though because remember we want to create a loop basically we want to loop while you know we haven't reached the last element so while uh so how many times are we gonna iterate how many elements are we gonna pop basically the length of our q minus one we wanna pop every value except the last one so what we're gonna do here is say self.q dot pop do here is say self.q dot pop do here is say self.q dot pop left from the left is where we're allowed to pop from in our queue and this is the method for it in python and we're going to take that pop value and just go ahead and now add it to the right side right so we can say self.q.append self.q.append self.q.append or we can just say self.push because or we can just say self.push because or we can just say self.push because remember we created a method up above which will add the value to the rightmost side and self.push is a little rightmost side and self.push is a little rightmost side and self.push is a little bit shorter than writing out this whole line so that's what we're going to stick to right we're going through every element popping it from the left adding it to the right except for the last element right the last element is going to be the one that's not added back to the queue so we're going to say self.q the queue so we're going to say self.q the queue so we're going to say self.q dot pop left after we went through every value except for the last value and then we're actually going to pop the last value and end up returning it as well so now that's the entire solution let's run it to make sure that it works and as you can see on the left yes it does work i don't know why it looks like it's not efficient this is about as efficient as we can get so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Implement Stack using Queues
|
implement-stack-using-queues
|
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
* `void push(int x)` Pushes element x to the top of the stack.
* `int pop()` Removes the element on the top of the stack and returns it.
* `int top()` Returns the element on the top of the stack.
* `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
* Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
**Example 1:**
**Input**
\[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]
**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
* All the calls to `pop` and `top` are valid.
**Follow-up:** Can you implement the stack using only one queue?
| null |
Stack,Design,Queue
|
Easy
|
232
|
216 |
so today we're looking at lead code number 216. it's a question called combination sum three and i would actually start with this if you tried combination sum or combination sum two i would start with this question first if you had trouble with those previous ones and once we solve this one the other two will make much more sense so here we have uh all valid combinations of k numbers that sum up to end such that the following conditions are true only numbers 1 through 9 are used and each number is used at most once and we want to return a list of all possible combinations the list must not contain the same combination twice and combinations may be returned in any order so we can see here k is three that means that the length of the combination result the sub result is going to be three and n is seven so that's the target so the sum of our sub result has to equal n so four plus two plus one equals seven okay and then there's no other valid combinations between one through nine that equals seven where the length is three okay here we have uh k is three so the length again is three of our sub result and then the target is nine and so these are the three numbers one through nine that equal 9. okay so the thing is we want to look at this question using recursion and really visualizing recursion as a tree and we're going to use a template to solve this and it's in the solutions in combination one if you look in the lead code solutions it's this backtracking template it's very powerful because once you understand how to use this template for any combination subsets or permutation problems they're very easily you can solve them very quickly and easily okay so the idea here is that we're gonna have a slate okay that we're going to put in our recursive algorithm and we're going to also pass in the target uh sorry the size of our sub result which is going to be our slate and then we're going to have a target that we're going to subtract from as we traverse down the tree and hit our leaf level okay we're going to also have a global result i'll just write it here in the bottom that'll be in the scope of the main function so it'll be a global result so our recursive depth first search helper no matter how many levels it goes down we can pass whatever sub result we have that's in the slate into this global result and then in our main function we'll call our dep first search recursive helper and then we'll return at the end our global result okay so here we have i we're going to start at zero and so if our slate is empty and i is at zero what are the combinations that we can have on that first level what can we put in the slate well we can just put everything that's in the array okay so we can just put one two three four and so on and so forth okay all the way to nine and what we wanna do at the next level is if i is going to equal well we can say j as we iterate through this first level is going to start at i okay then what we want to do is as we call our debt first search recursive function we can just increment j okay so we can pass in into our function here j plus one so what does that mean so if j if i is zero then j is going to equal zero when we pass in j plus one j is going to equal one so when we get into this next level we're gonna have one and two because um this is a little confusing but just uh follow me here j is going to be j plus 1 which is going to be what i is going to equal when we pass it into our depth first search recursive function okay so j is going to equal i which is 1 okay so we'll just say i equals one j equals one it's going to start at one at index one so now here when we move to index one whoops let me just do this so i can grab this ith variable here i'll move this here let me erase this okay so now i is gonna move here to two and then we're passing we're pushing that onto the slate okay so now we're gonna have one two on the slate one three one four so on and so forth okay until we get to one nine and now we're going to do the same thing on the next level we're going to go ahead and uh pass in j plus 1 into our depth first search recursive helper so we're going to get one two three and now we're at the leaf level because the length of this is now going to equal k right so that's how we're going to determine that we're at a leaf level now we have to check is the sum of this equal n okay so 3 plus 2 plus 1 is does not equal 1 it equals 6 so we're not going to pass this into our global result then we're going to do 1 2 4 does this equal n this does okay so when we hit that base case we know that we do have um something that we can pass into our global results we'll just go ahead and pass this into our global result okay now when we get to this one two five we can see that this is greater than this right here is greater than uh n and because it's greater than n we don't want to go anything further but we don't need to go any further down the tree okay so anytime we can have a backtracking case where if the sum at any point is greater than n then we just backtrack we just return out of that recursive case if the sum is equal to n and the length is three then we can go ahead and push into the global result but at any point if it's greater than n it doesn't matter how far we go down the tree if we get to you know the size of k it's still not going to equal n because it's greater than n it can't go any further so for example like nine we can just backtrack right from there eight we can also just backtrack we don't need to go further down this tree until um the slate is equal to k we don't need to do that because we know that number uh when we get to this level is already bigger than n okay so we're gonna now jump into the code and i highly recommend checking out the other videos in this playlist um i go step by step using this back tracking algorithm i'm not gonna go over it in this video step like step by step but i'll go through the code and try to show you how it works there but if it still doesn't make sense like i say in the other videos get a pen and paper draw out the recursion trees really try to understand what's happening at each level and how the code is relating to the concept okay so here first thing we're going to do is we go ahead and create our global result and we'll set that to an empty array now we don't get an input for the numbers one through nine so i'm just going to go ahead and create an array so i'll just say um i'll just say nums i'll set it to an empty array i'll create a little for loop here so i'll say let i equal one i is less than or equal to oops i is less than or equal to nine i plus and then nums dot push i so all i'm doing here is creating that uh that array here with the numbers one through nine okay so now that we have that set we have our global result set and we have our numbers array set we want to go ahead and um we want to create our depth first search helper okay that first search recursive helper okay so let's do depth first search and then what do we want to do here we want to set in an i variable our nums we're going to have a k that's our size and then our target which is n and then we'll have a slate okay so now what is our back tracking case there's three components to this template there's the back tracking case there is the base case and then there is the depth first search recursive case okay so we have three cases here that we need to fill in so let's take a look here what is our backtracking case well if any point if the if n is uh if the sum is greater than n then we can go ahead and backtrack right and the way we're going to do this is we're going to subtract uh the number that's in um the ith variable from n so this will make more sense once i write out the code but just follow me on this so we're going to say if n is less than 0 we're going to return okay so that's our back tracking case if n is less than 0 then we just go ahead and return our base case is if first we got to check is the slate the same length as k so if slate dot length equals k okay then we have to check if target or i'm sorry if n equals 0 then what do we want to push whatever is in that slate into our global result slate dot slice we want to make a copy of that slate okay and then after that we want to return outside of the scope of this if statement because we want to return either way whether we push it in there and if it doesn't meet this condition we still want to return out of this base case okay and now we're going to have our depth first search recursive case and i'll you know it'll make more sense why n is equal to 0 and how that lets us know that the sum is greater than it's greater than the target so we're going to do 4 let j equals i where j is less than nums.length where j is less than nums.length where j is less than nums.length and we're going to increment j okay and so now what do we want to do let me just have some more room up here what do we want to do we have our uh our iteration across one through nine so we want to add push nums at j into our slate okay we wanna push that nums into the slate then we want to call our depth first search recursive helper by incrementing j we have our nums we have our k and then n we're going to multiply or we're going to subtract whatever is at nums j and then we'll pass in our slate and then of course we want to pop off the slate okay so what are we doing here we're coming down here and we are j is going to equal i so j is going to equal 0 in this instance and then we're going to pass this into our depth first recursive function and we're going to set whatever i is at to j plus 1. okay so now i will equal 2 or i will equal index 1 the value 2 and then we push that onto there okay and i believe that's it so now if we call depth first search and we have zero nums k n and slate as our empty array we just return result okay let's go ahead and run that and we're good okay run it one more time and we are good i'm trying to figure out why our time complexity is so much slower let's see here there we go so i you know this lead code you never really know right like we hit submit the first time and it was at 11 and now it's at 99.33 so it's really inconsistent 99.33 so it's really inconsistent 99.33 so it's really inconsistent on how this works i wouldn't go by that now figuring out the time and space complexity is actually really complicated uh for this particular question typically you're looking at 2n times n when you're doing a binary tree but because here we're going from 1 through 9 and then for each one of those we're going and creating a combination of that um it's going to be some huge pretty large number okay so um i would say if you're still confused about the time and space complexity check out the solution they kind of go through over it uh you know with timing space complexity you can see here that it gets pretty complicated you know um so yeah that's a good idea if you want to get really detailed on the time and space complexity so it's kind of hard to figure this out but you know i think if you can explain how it's a tree and kind of come up with some approximation then that should be sufficient okay so that is leak code number 216 combination sum three highly recommend if you're confused on this or this didn't make sense go back and look at the other videos in this playlist all the other videos in this playlist we're just using this general pattern this template here and so it's just a matter of repetition the more you do this the more you get a pen and paper write the tree out the more it will start to click and it'll make sense and once it makes sense you can solve these types of problems any variations of them in like 5-10 minutes i mean it's really easy 5-10 minutes i mean it's really easy 5-10 minutes i mean it's really easy once this pat once his template is kind of ingrained but it takes a little bit of time to make that connection so keep at it if it still doesn't make sense okay i'll see you all on the next one
|
Combination Sum III
|
combination-sum-iii
|
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true:
* Only numbers `1` through `9` are used.
* Each number is used **at most once**.
Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order.
**Example 1:**
**Input:** k = 3, n = 7
**Output:** \[\[1,2,4\]\]
**Explanation:**
1 + 2 + 4 = 7
There are no other valid combinations.
**Example 2:**
**Input:** k = 3, n = 9
**Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\]
**Explanation:**
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
**Example 3:**
**Input:** k = 4, n = 1
**Output:** \[\]
**Explanation:** There are no valid combinations.
Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.
**Constraints:**
* `2 <= k <= 9`
* `1 <= n <= 60`
| null |
Array,Backtracking
|
Medium
|
39
|
9 |
in this video we'll be going over palindrome number so we determine whether an integer is a palindrome when it reads the same forwards as backwards to solve the uh and the follow-up is could you solve uh and the follow-up is could you solve uh and the follow-up is could you solve it without converting this integer to a string so for the first example we have x is one two one so if we read it backwards it's also one two one so let's go let's first go over dots before coding so a palindrome is a string that can be read the same way forwards and backwards this means if we reverse x the reverse version of x will be equal to x we will implement the approach that does not require us to convert the integer to a string that does not require us to convert integer to a string now how can we reverse x we can create a variable reverse to keep track of the reverse form of x we will need to process the rightmost digits of x first so going from right to left to process the digits of x from right to the left in order to retrieve the rightmost digit we can use the modulus operator so digits is equal to or we should say rightmost digit is equal to x modulus 10. then in order to append this digit to our reverse variable we have to multiply reverse by 10 first so we have multiply reverse by 10 then increment by digit basically the rightmost digit now we can remove the rightmost digit of x remove using the division operator this will allow us to process the next rightmost character so we can say x divided by 10. after we have processed all the character digits of x after we process all of the digits of x we will then compare x with the reverse form let's first go over a pseudo code before we jump into the code so we have an answer so let's validate the input parameter if x is negative then it is not a palindrome number so we can return false so create two variables so we want them to be a copy which basically is a copy of x we do not want to modify x because we still need to compare x with the reverse form later and then we have a reverse which keeps track of the reverse form f of x now we can say now we'll process each digit of copy instead of x so while copy is greater than zero so that means we still have digits to process retrieve the rightmost digit so we're going to say digits is equal to copy modulus 10 and then we'll append this digit to our reverse so multiply reverse by 10 and then increment by digit and then remove the rightmost digit from copy so remove rightmost digit we have copy is go to copy divided by 10 and then we can return true if reverse is equal to x else return false now let's go over the time and space complexity so time complexity is equal to o of log of x where x is the input value is log of x because we process each of the digits of the of x so then when our space complexity is go to of one now we can jump into the code so we validate the input parameter if x is less than zero then we can return false then we can create two variables we'll start from zero and copy will be equal to x and while copy is greater than zero retrieve the rightmost digit copy modulus 10 and then append digits to uh to reverse so reverse let's go through reverse times 10 plus digit now we can remove the right most digit so copy is going to copy divided by 10. so return true if reverse is equal to copy move to foremost digits oh reverse let's go to x and i go to copy let me know if you have any questions in the comment section below you
|
Palindrome Number
|
palindrome-number
|
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
**Example 3:**
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
**Constraints:**
* `-231 <= x <= 231 - 1`
**Follow up:** Could you solve it without converting the integer to a string?
|
Beware of overflow when you reverse the integer.
|
Math
|
Easy
|
234,1375
|
1,022 |
hello everyone this is today we are discussing this problem that is sum of root to leaf binary numbers um this is a very simple yet interesting problem uh the problem says that you are given with the root of binary tree and the only values that this binary tree is containing is zeros in one and each root uh i mean each uh path from this uh root to the leaf node of this binary tree represents a binary number starting from its most significant bit and what you have to do is you have to return sum of all such numbers i mean suppose this represents a number x this path represents number y this represents something x and all so what you have to do is you have to return sum of all these numbers so far so uh if things are not clear let me explain you with an example and let's see what we can do with this problem so here is one such example uh that is uh demonstrated in the example uh so let's uh discuss what i am trying to say in this question so it says that first of all let's make clear that what is a leaf node let's take another pen so leaf node in a binary tray is simply a node which is the last node of any tree i mean it does not have any further children's in a tree so you can see that this is a leaf node this and this is a leaf node in a mandatory and the possible parts from root to this leaf nodes are i mean very obvious that this could be a path this could also be a part and this could be a path of uh path from root to the leaf nodes now uh if you look closely this path will represent a binary representation i mean this path will let's write these numbers or these paths here this will be 0 oh sorry 1 0 this will be 1 0 1 this will be 1 0 one zero this will be one right and uh this is a one a representation of four uh this is four five this is for six and this is for seven right uh now these all are the uh these all represent some number now what you have to represent or what you have to return is you have to return the sum of all these values so formed by taking the path from root till the path uh till the root uh leaf to the least note sorry so um this if you uh think of a brute force solution uh it is very obvious that you will first of all travel from the root to the path uh to the leaf node and you will start uh collecting this path in any area array or string and once you have completed this you will then convert this array or string into its binary represent sorry into its decimal representation and you will do this for all the path that you get from root till the leaf nerve and after that you convert them correspondingly and you then sum them up to get the final answer this but will be a very hectic solution because you anyways have to travel all of these and then you have to convert these things and you have to traverse these strings and you have to then proceed with this answer so we are not going to do this much lengthy process what we are trying to uh i mean how we are trying to solve this problem is by running some method so in this method what we will do is we will uh at each step let's take another pen for that so at each step what we will be doing is uh we will be uh maintaining a sum this sum will hold the representation i mean the sum value till that node in the tree so what i'm trying to say here is suppose at this index we are at this index so we will be having a value uh in the sum variable which will represent the sum till here and suppose we are at this position we will again be having a sum variable which will hold the value for sum till this position so uh how are we going to convert or how are we going to get the sum for here it's pretty simple you have to just keep this in mind that will be at this point right the uh the sum at any node is the two times the sum at previous node plus the value at that node right in the i mean uh initially this value will be zero because when we are starting we don't have any much sum so uh suppose let's dry run this situation and let's see if we can find out or if we can get this answer or not so initially as we have to sum as 0 so at this node what we will be having is we will be having 2 times 0 plus 1 so at this node sum will be one i'm writing this in boxes these boxes value represents the sum at that note uh similarly when we uh reach at this spot we will be having is uh two times of initial value two times of one plus zero so that will be 2 right similarly when we reach at this part initially the sum would be 2 so 2 times of 2 is 4 plus 0 is 4 right similarly at this point we can i mean we don't have to travel from the start because this is the extension from this node so we can consider this two so two times of two plus one is five right similarly uh when we reach at this spot two times of one plus one that is three right similarly at this spot uh you can see that we have to uh do two times of three that is six plus zero that i mean at that spot six will be our sum similarly at this spot we will do is two times of three plus one that is seven right so if you look closely uh at each path we have the correct value this is five by the way yeah so we have this correct uh corresponding value uh allocated at this sum variable so now just what we have to do is we simply have to add all of these value to get our final answer that is 22 in this case right so this was the uh step or this was the logic that we have to do and the rest of this things are very uh i mean very simple and if you have done previous questions with trees and recursion so you might know what i am talking about or how is this achievable so uh which kind of traversal are we using i mean obviously we are using recursion for that so in this traversal we are using the pre-order traversal we are using the pre-order traversal we are using the pre-order traversal pre-auto traversal and uh for those who pre-auto traversal and uh for those who pre-auto traversal and uh for those who don't know what pre-order traversal is don't know what pre-order traversal is don't know what pre-order traversal is pre-order traversal is simply uh wherein pre-order traversal is simply uh wherein pre-order traversal is simply uh wherein first of all we target the node then we hit its left side and then we uh go at its right side right so this is simply the pre-order traversal so we are using the pre-order traversal so we are using the pre-order traversal so we are using this pre-order reversal so uh i am not this pre-order reversal so uh i am not this pre-order reversal so uh i am not going into i mean how this recursive call is working or how we are shifting to this uh after calculating this value how we are shifting to its backward node uh all of this i am not covering because this is very simple or basic stuff regarding trees so let's quickly jump into our code and let's see what we have coded and uh if it submits our test cases or not so um clearly we in the given function we were not given any some value and we want our sum value to pass at every function call so we have made a helper function for that and initially we have passed 0 as the sum and the base case would be we will check that if our root is null so we will return 0 for that situation and additionally one thing we will also be checking is that if we are on the current uh i mean uh if at the current root or at the current node if it is a leaf node or not i mean what do you mean by a leaf node is that it has no further children so at each step we will check that if roots left and roots right both are null we will simply return our existing sum i mean the sum that we have in this variable right and i mean once we have checked all of this uh additionally one more step that we will do at each node is we will uh use this uh running some thing right we will do this i mean we will multiply this current sum with it uh with two and we will add this current value that's uh that i've already discussed that uh how should we proceed further right uh sorry yeah after doing that i mean uh once we have uh maintained i mean once we have performed all these functions for the current node what we have to do is i mean it's simple recursion stuff that we call for its left node we call for its right node and we'll simply combine these two answer and we'll return our final answer right in this situation you can see that we have made a call on its left subtree and we have call made a call in its right subtree and suppose this is a sample node so this will be its left node this will be its right node so we will um at this step we will make call on its left tree we will make on right tree uh we will make a call on right tree and we will add these answer and we will return this thing right so this was the simple stuff let's run this answer and let's see that if it passes our basic test cases or not so it does passes our basic test cases let's submit this great um the our code gets submitted so this was the explanation for this code so if you like this solution you can like this video and you can consider subscribing to the channel as well so this is for this video that's all bye everyone
|
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
|
978 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem longest turbulent subarray we're given an integer subarray and we want to return the length of the maximum size turbulent subarray from the given input array now what exactly is a turbulent array well it's best understood with an example so let me first draw it out using this example that they gave us and I'll show you how simple this problem really is so let's say that this is our input sub array for every adjacent pair of values there's some equality between them either this one is going to be greater which is true in this case or we could have the opposite case where the right value is greater or we could even have a third case where adjacent values are equal to each other every pair of values every adjacent pair of values is going to have some equality between them I'll quickly draw them out here we can see 4 is greater than 2 10 is greater than 7 8 is greater than seven eight is greater than one and nine is greater than one all we want to do is return the longest subarray well not the actual sub array itself but the length of the sub Ray such that we have the longest alternating streak between equality signs what I mean by that is no matter how we start for example here we start with a greater than sign then for the rest of the sequence the sign has to be alternating like the equality has to be alternating first it was greater than now it's going to be less than then it's going to be greater than and then it's going to be less than now for equal we don't count that so a turbulent array as defined by this problem is alternating between greater than or less than signs one more point of clarification here we have four signs but we're not counting the signs themselves these signs form this array where we have one two three four five values and we return five you can see that down here so why couldn't we also include the first value over here well take a look at the signs we started with greater than that's fine but then we had a second greater than in a row that's not what we were looking for at that point we can't include this anymore this is the longest turbulent sub array well these first two values where we can start at this value so thinking about it this way the problem becomes pretty simple we're just looking at this array we want to find that optimal longest turbulent array which is this one in this case we can't extend it further over here now technically this is also a turbulent array it has three values in it but that's not what we're looking for we have a longer one which is five over here so how can we solve this problem efficiently because when we're talking about sub-arrays we know we're talking about sub-arrays we know we're talking about sub-arrays we know we can Brute Force this by just checking every single sub array and do that in N squared time because that's how many sub arrays there are going to be so how do we do even better well when we get here the first two values we are good so far it's sort of like a sliding window technique or you could say this is pretty similar to cadane's algorithm I kind of think of them as overlapping because they're very similar but yeah sliding window we're gonna try to grow our window as much as we can but when we can't grow it anymore let's see if there's any patterns we can identify to eliminate any repeated work starting at these two guys there's some equality between them the only problem would be as if there was an equal between them at that point we would be able to say this is not even of length two but since there is equality between them this is a valid turbulent subarray of length two but now when we introduce another value at this point we wouldn't initialize our pointers like this by the way we'd have a left pointer and a right pointer for our sliding window and then we would shift the right pointer over here now we're comparing these two values we're always going to compare the value at Index right with Index right minus 1 which is over here so now we look at this and we see that the problem here is that our previous one was a greater than and right now again we have a greater than sign that's not what we wanted we can't say that this is a turbulent sub array so what do we say we found the longest one starting at this position but now we have to start over we're going to now start at the next position over here at this left index and our right pointer which was over here is now going to be shifted to the right by one so now our right pointer is going to be over here so now we keep track that the previous sign that we saw was a greater than sign and now we compare are right with Index right minus one so we look at this equality sign now it's less than well I don't even know I think this one is called greater than this one is called less than but the point is that they're different this is a valid turbulent subarray now we go one more time over here we see again that they are opposites so this is also a valid turbulent subarray we go one more time our right pointer is over here compare these two see the sign it's the opposite which is good so these are continuing to be turbulent sub arrays finally here though and this is going to be interesting we get the equality so not only is it different than the previous one but it is an equality sign which we are going to handle in a special way I'll show you how the first thing is that this is not a turbulent subarray so now what should we do should we now try to find the longest turbulent sub array starting at this position we already found the longest one starting at this position that's this guy of length five so now should we start over here well definitely not because if this whole thing is a turbulent subarray then we know for sure and we're not including like this a rightmost value but if this whole thing is a turbulent subarray then for sure this is going to be a turbulent subarray because if all of these are alternating then of course a subset of them are also going to be alternating we're basically saying that for a turbulent subarray any sub-array of that turbulent subarray any sub-array of that turbulent subarray any sub-array of that turbulent subarray is also going to be turbulent so that's why we can use the sliding window at this point I would take the left pointer and not just shift it by one but I would shift it all the way over here now our right pointer is already here I'm going to move the left pointer over here as well and we're also going to shift the right pointer by one over here so we would have this subarray and it is turbulent because it's different than the previous value which was well the previous equality which was equals this one is greater than and at that point our algorithm would continue as normal now the one thing I want to say that's different about the equality here what if instead of this being an equals we just had another less than sign well in that case our right pointer is already over here but we would actually want our left pointer from over here not to be shifted all the way over here because then our left pointer would be here and then we'd increment the right pointer to be over here and then we would check this but that would be a problem because in that case we would have missed this subarray we would have just skipped all the way to here so when there's an actual greater than or less than in that case we don't want to skip all the way to the right index we don't want to take our left pointer and then shift it to the right index we want to stop at right minus one so we would normally stop here if this is not an equal sign but if this is an equal sign then we don't shift the left pointer over here and the right pointer over here because this is not even like a valid turbulent Subaru even though it's just two values it's not valid so we would just want to skip this one all together but that's the main idea it's basically a sliding window problem at its core so the time complexity is Big O of n it's a linear time algorithm and the space complexity is O of one because we don't need any additional data structures so now let's code this up so as I said I'm going to first initialize my pointers a left pointer to zero and a right pointer to one I'm gonna also initialize our result and the previous sign so initially I'm going to set the result which is the length of the maximum size turbulent subarray to B1 B because we're guaranteed that the input array is going to be non-empty and a array is going to be non-empty and a array is going to be non-empty and a single value does count as a turbulent subarray so I think one is a good initial value and I'm going to set the previous sign equal to the empty string it can also end up being the greater than sine or the less than sign or just empty as well I'll show you how that's going to be used in a bit we're also going to take our right pointer and just iterate it through the entire length of the array there's a couple cases if array at index R is greater than the array at the previous index or actually I'm going to write it the other way I'm going to write the smaller or the previous value to the left because this is how we're going to use our equality signs but if the previous value is greater and the previous sign was not equal to the greater sign meaning that it was either empty meaning that we basically started at the beginning of the array or that it was the less than sign this is good because that means our array is turbulent so at that point what we would do is possibly update our results so we would set it to the max of itself and the length of the current sub array which would be right minus left plus one we would also want to increment the right pointer by one and we should update the previous character now to be equal to greater than because that is what we have here so this is just one of the cases with my solution there is going to be some code duplication I could write it a more concise way but I think the way I'm going to write it now is going to be very clear on what the solution is because we have these equalities I think this code is going to be really easy to read and it's going to be pretty easy to write as well because this was one of the cases now I'm going to just copy and paste this and get the other case else if we had the opposite of this meaning if the current value is greater and the previous sign was not the greater sign or you know whatever you call this then we would basically do the same thing here the only difference is we would change the previous character to be the opposite one and the third case here is either we had consecutive signs or we saw an equal sign in either case we want to set the previous to be something else we could set it to be equal or we could just set it to be like an empty string it doesn't really make a difference because the way we're actually using it here is we're only checking if it's not equal to this or not equal to this so we can just keep it simple here the other case is remember the right pointer if they were equal signs that we saw or if the two adjacent values were equal then we want to increment our right pointer so if a array of at write indexes equal to array at right minus one then we want to set right to right plus one else we leave it as it is and regardless of how we update these we always want the left pointer to be equal to right minus one if we are updating our sliding window if you know this condition executed this part I admit is probably the most confusing about this solution but it has to do with how we want to handle equal signs basically we want to skip them all together this is the entire code you can see all we really have to do is keep track of the previous character that's giving us all the information we need the rest of it is pretty much just duplication we're just updating previous three times we are updating the result a few times and just incrementing our pointers a few times as well after that's done all we have to do is return the result and let's run this to make sure that it works and as you can see yes it does it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a interviews check out neatco.io it has a interviews check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Longest Turbulent Subarray
|
valid-mountain-array
|
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if:
* For `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is odd, and
* `arr[k] < arr[k + 1]` when `k` is even.
* Or, for `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is even, and
* `arr[k] < arr[k + 1]` when `k` is odd.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109`
|
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
|
Array
|
Easy
|
1766
|
1,716 |
hello guys and welcome to today's daily lead code challenge today we'll be solving question 1,76 calculate money in the lead code 1,76 calculate money in the lead code 1,76 calculate money in the lead code Bank let's get straight to the question um heresy wants to save money in for his new first car he puts money in a leite code Bank every single day he starts putting $1 on Monday the first day every putting $1 on Monday the first day every putting $1 on Monday the first day every day from Tuesday to Sunday he will put one more than the day before so if I was to draw this out the week starts with $1 and then it goes 2 three 4 five 6 7 8 $1 and then it goes 2 three 4 five 6 7 8 $1 and then it goes 2 three 4 five 6 7 8 right Monday Tuesday Wednesday Thursday Friday Saturday Sunday oops s uh let's see then what happens uh on every subsequent Monday he will put one more than the previous Monday so this is week one uh what does week two look like well week two doesn't continue from 8 right it starts from Two and goes up to three four five 6 7 and eight so this is week two you can see the pattern here um there are little spikes of um there's increases in the amount that he puts down throughout the week but it's resets to a smaller amount each subsequent week and uh the question here says that if given that n which is just the number of days return the total amount of money he will have in lead code bank at the end of the nth day so we're not given a specific week where uh we're not given this term in weeks we're given it in days meaning that um the uh investment time period can end maybe the fourth day or the fifth day of the second week and we would have to take into account the whole previous week and a portion of the second week all right well um to kind of start thinking about this it's important to recognize what the sequence here looks like and what it really is an arithmetic progression these arithmetic progressions are very common uh in lead code questions you see them pretty much well not everywhere but a commonly uh you would see something like what is the uh what is an example of a well I mean just 1 2 3 4 five six and so on until like the um until some nth day and uh a very common way to um write out a geometric progression the formula is this um plus xn where you have two S is = = = to uh X1 + to uh X1 + to uh X1 + xn * uh n number of times and so you xn * uh n number of times and so you xn * uh n number of times and so you would get something like the sequence is equal to uh the sum of the this times n uh so you would call that I don't know X sum * n / X sum * n / X sum * n / 2 um it's commonly written like this also N - 1 n / 2 you might have this also N - 1 n / 2 you might have this also N - 1 n / 2 you might have seen this before uh here uh we're given a little bit of a different scenario we don't start from one each time let's write out what the arithmetic progression for a week would look like uh well we would uh have an X we would have an X start oh let me write this out in Blue uh X start uh and then on the first week it would just be one then we would have X something else X this x this and these are all additions until we get to uh xn or XF let me call this XF which is the final day of the week uh in this case it's going to be seven so what if I wanted to figure out what the arithmetic progression for a or this arithmetic sum for a week is I would say that the sum is equal to this but then I want to say 2 s is equal to say XS + XF XS + XF XS + XF uh times uh actually XF minus X XF minus XS because XF minus XX is the amount of times that X appears here uh plus one actually because if this is seven six it appears seven times um and then we would say that s is equal to just Xs plus uh XF uh just say this two um so there we go that is our sum for a week let me code this up real quick and see if that's actually correct uh def we week sum and I want some parameters in here I want to uh XS which is just the start and then I want the number of days uh days in the week that we have they're always going to be seven days so what is going to be XF that we want XF is just XS plus days minus one what is this y why is XF just XS plus days minus one well one + plus days minus one well one + plus days minus one well one + 7 minus 1 which is the first day + 7 the 7 minus 1 which is the first day + 7 the 7 minus 1 which is the first day + 7 the seven days minus one gives us s so 1 and seven XS is s is one XF is 7 uh and now we just need to return this formula that we have deviced here this is going to be XS plus XF uh times the number of times that this value occurs which is just going to be XF minus XS + XS + XS + 1 I believe right and all of this divided by two let's check if this is correct by running the first week through it uh print one and we have seven days and if we have one and seven days then that is equivalent of this which gives us 28 let's see if 28 gets printed when we have one and seven oops 28 we're looking for 28 perfect and what if only four days are included first day then we should get a total of 10 awesome so there we go we have just computed basically what it's going to take to uh how much value accumulates in the in either a week or some number of days given that we have x given that we have the starting day so now all that's left is we have the uh full weeks the count of full weeks and that is just the N uh divided by 7 and the left over days is just going to be uh n modulo 7 now for let's say week in a Range full weeks I'm going to say that I need this value here s is equal to this is my R Val return value um it's going to be right oops R plus equals week starting with week zero but plus one and always seven because we're completing the week here uh and then finally we need to do this one more time except the week is going to be the full week's + week's + week's + one I believe right because it's the week that didn't get captured fly and the number of days is this uh and that's it we can return Red yes this is an easy level question I'm sure that there was probably a less math intense solution but this one is very clear and intuitive and so decided to use it yep definitely not the fastest let's look at what these guys are proposing uh these guys are proposing that we have a count which is just the amount of money accumulated the number of weeks is just going to be the if the week is not full if the N if n isn't fullly divided divisible by seven then it's going to show an extra week if it is however it's going to show an extra week and then for a week in range of weeks if week is equal to week minus one weeks - one uhhuh the this is so I see what they're doing here they're going through and iterating through all the possible um all the days that actually accumulate but how is that faster how's that faster because we're doing it mathematically they're doing it through an iteration they're saying that for all the full weeks that there are which they're claiming is uh in weeks it's going to be week uh go through 1 2 N modulo 7 + one yeah there's just no way that this is faster because and it's harder to read o my solution here avoids having to do any um any Loops that aren't necessary so I don't understand why let me try rearranging something in hopes of uh in hopes of making this simpler let's remove this left over days we don't need that it's just n modulo 7 I should be getting a faster solution because or are less iterations that I'm doing but it just doesn't want to do it I don't know I like my solution if you understand this fully uh I suggest you use it's probably more pretty I would say uh the others are definitely easier and they somehow get away with it being faster but I don't understand why uh cool I guess with that let's end today's video thanks for watching please like And subscribe catch you later bye
|
Calculate Money in Leetcode Bank
|
maximum-non-negative-product-in-a-matrix
|
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000`
|
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
4 |
Hello everyone welcome to my channel codestorywithMIK but it is quite easy but very popular question this is ok lead code number four medium of you sorted ok this is part one of this video so it is known that I will make it with two approaches ok One will be Brat Force which will be a very simple approach and the other will be a little bit of its butter version. Okay, in the part you will come to the best version and it will come today only. Don't take tension. Okay, first do these two approaches and then you will do the part. Will come in a separate video, okay, so let's see, many companies have asked this, I have mentioned only three here, Google, Microsoft, Apple and many other companies who have asked this question, the question is simple, already means whose size is right and see here the words. Diya's overall time complexity should be of people M plus I will tell you, it is ok, it will come today itself, don't take tension, this video will come today only, but it is important for you to know more, all this is also beautiful, you should know us right directly, I have told you a little in the interview. Have you seen this one made with the approach? Do you use the approach? Right, this part will come to you. Okay, so let's see how we can make brat with four and how we can butter it a little. First of all, understand this. So understand what is the meaning of medium. Median is also called middle number. If you look in Wikipedia then you will know what is the meaning of meeting. There are some numbers or you can also call them data points, you sort them, okay mother. Let's take from the data point you have, you are five three 17, so first sort it, write the order wise 123 57, you have shortened it, look at its size, how much is it, one, two, three, five, then what will be the middle number, look at it will be the middle, right? The size of the number is five, isn't it 5/2, so the index on the second index, first index, second index, third index, the total number helmet was five, divide it by two, you will get the same element of the index, it will be my middle index, this is called median, middle. The number will be called the median, but you will say that if we take the number 1, 2, 3, 5, 7 and 8, then what is its size. Let us write down the index of zero, one, three, four, five. From how many numbers, there are total six numbers. N = If it is 6 this time then it is ok then how much will be obtained by doing N/2, three A means it is saying that it is the third number when it is not there, see how it is, there are two numbers on the right side, if there is three on the left hand then there is no middle number. So let us know how the medium is defined. If there are number of and number of elements, then take the number between the middle, that is, take an index of n/2 i.e. the third index and the second index of n/2 - 1. Take the element of both of them. Take the sum of three and five and send it by doing 5 3 8/2 date this 4 i.e. this input will be medium tax, okay you will know this but I just told you here so let's see the input here. It is very simple, the answer can be found in every hard double, see, it is a flat value, okay, we have to send the answer in double, so see, here it is very simple, there is one and three and second is tu, so first we have to sort it, okay? The worst man can be is that you took 13 in it, added 13 to it and then added it to you, then if its size is M, if its size is N, then what will be its size, M plus N, then what did you do with it? It is sorted, what will happen if it is shortened to 123, ok, sorted, what is its size, brother, what is the total size, let me write its size, how many elements are there in total, m+n, that is, if there are three elements, then it is odd. The number is three , if it is divided then how much will be 3/2? One i.e. the element with first index will be my answer. Look here you are my answer. If you want to send it in double, then you will send it in double. 2.0 00 is a very poor approach here because look at your one. So, we took O of n space, took a space named m plus n, and sorted it as well, then how much space will be required in sorting, m + n log of m plus n. This is what is compressed in shorting, and log is if the size of the container. Here, m plus n is the size, so the impressions are m+n, so this is a very poor product. Okay, so let's see what we can do with this. Okay, we will see, now let 's solve it with different approaches. If you do then you will understand the example, what will happen, see here 1 is 2, here three comma is four, so let's shorten it and write 1 2 3 4 total 2, how much will it be 2 second index, we will send the medium of these two 2.5 see 2.5 answer Okay, what I am saying is that how will it be solved, so see, before Bluetooth, I had told you that there is a very poor approach, that is, I have taken a tamper and inserted Blindly Names One in it first and then sort it again If it is okay then it is very bad, I am also going to make a little butter version, okay, you are making it, right, you know its size, because if its size is M, then its Correct it will be M+N. Okay, so I have made it as a tamper, so what am I saying, why are you putting it blindly, direct, put it here in such a way that it is in sorted order, okay, then take two painters. If I take one red here , then what will I do? First let's see which one is smaller among the two, first I will put it in the temp and what else, see who is smaller, forest and you, if forest is small then put forest here and further flood will come. went If we write the smaller of the two then the smaller one has been written here 2 Now if this is further flooded then K is out then it is bounded G is auto bounded so what will we do like now i.e. any other element A It is not possible because there is no element. Okay, so we know what we will do. We will put all the number of element children in number one. The number of element children in the name Suman will be given. How many element children are there. There is only one element child. Let's give pulse and move ahead to I is also out of bounds, okay till now it is clear, we have given pulse in 10th, look, it has come here in already sorted order, it is very simple, okay and if you can also see such example. Yes, if we take mother, it is something like this, okay, and Namas tu is here, 8910, okay, 7 is small, I have written seven, it has gone ahead, look, the rectangle has become off-bounded, okay, so what will we do, as many remaining elements as there are GK, okay. 9 10 11 Our size is finished, return it, its size is in the tempo, it is the middle element, see, there are three on the right side, three on the left side, so this is a sure medal, so take my answer. Okay and we will add to that tempo size by you minus one and we will send the average of both by you ok but science we have to send which in double if we want to send it then divide by point zero it will convert itself into double write 0 It is okay to give here in 2.0 and it is okay to return it and returning it here is simple today Sir, it is a very simple approach, already many people must have done it is okay but I did not see any problem in it that we O of M+N taking one space is gone, my biggest sorrow is this, but style will also be accepted, so first let's try this, if it is accepted then it is good, after that we know what we will do, after that we will go to butter approach. Ok butter, we will go in the best approach, after that video butter will come, you know what I am saying, I can do it even in off one space and show you, ok, how will they see further, but first code it. Let's finish it automatically, the root approach is fine, let's start the recording size is fine, after this see what I said that I will take a vector but will put it in a sorted fashion, so I told a cool way to put it in a sorted fashion, this equal . You will point to zero and J = 0, which one will it point to, this number will point to one by name, it is clear till now, okay, and which will point to the index and K, keep it there, the elements that are going in the temp, I am fine, so I told you that as long as I < M is N K < N then I will keep adding the elements by comparing them, meaning if Naam's I Tha element is smaller than your brother-in-law's element by name, then we will include it first, right in 10th. To whom did Namas of One be added on the index of Temp Off ? And on the same pretext we will also make I Plus and K + B. Okay till now I Plus both are the same thing. To do it in a little shortcut, I have written it in one line here. It is clear here that if NMPS one i is not <= k then it will go in else, what does it mean that first we will write nas tu k then it is ok in how so here what I will do is 10 k + +2 and k. I will put 'K', it is clear till now, it is simple but I told you that it is also possible that all the elements of NMPS One have been exhausted and all the elements of 'K' have not been exhausted yet, which means that if I is out of bounds, then this is If the look of the cut will be finished then I will check in the last that if there is such a child then what to do with the plus of tempo and if it was just the opposite that the jet element is not finished yet then keep putting in < which both How can this be one of these, isn't it great? Either it is possible that both the elements will be destroyed, here only, how will both of them not come, okay, so we have done this, now remember. Remember what was the size in last? M plus N was the size of our temp. Okay, if the size percentage is equal to this is equal to one. That is, if there is more size and there is size, then how will the middle element be removed in a simple way. Remember the temp of. Whatever element is there in the index of size by tu will be my middle element dates it and if it is not so then what I said that add the element which is in temp of size by tu to which temp of size by tu minus one. Find out the sum of both and divide it by 2.0. Why did you do it by 2.0 so that it gets converted into double? We will not have any tension then ok then let us see the late example testis and then after that we will submit it and see. Hopefully they should be. Able you pass which D test cases should also be submitted. Now after this we will go and check that brother we can make green in oven space. Solve this question. This temp is not that off m+n space. This is giving great pain. Right M+N, I have to make it off one of the ghat and let's see how we will do it by modifying the code, see, now I understand you well, so see let's come to the butter approach in which I will solve this in the off one space. Then I will show you what the meaning of off one space is that I don't want to take the temperature that I was taking. What else is right? 0123456 I don't have to take this, I won't take it, I'll keep it aside for now. Okay, I have kept it aside here, now look, reduce one here, no, I reduce one here, I have already calculated the size, I am late, what will be the size of my temper, if I am late on time, it will be m+n/sorry, m+n. So how much will M plus N become? Brother, it will become 7 because its M is three, what is its size. Okay, so you know that if we put it in the temp, then how will my medium come out ? The middle element is right. Now how do you get the middle element? If you take the element which is in size baytu , then I will make it 12 right now, so what do we do here, make it this, make it 8 size and what do we do here? Now look, pay attention, if these two need to be equal then mine will become less. So, we have worked out which of our two elements which we will pick up will be on which index. So, I have removed the temp. Now definitely. There is no index, we just had to find out, now pay attention, what will happen, it will become very easy, remember our problem, you used to take I here and K used here, okay till now it is clear, remember which one was smaller among the two. Earlier you used to take that right, the lie was smaller among the two, meaning you would pick the element from there, right by name, so right, now see which index is I, mine was 0 and this is 03 index. You saw that the rectangle is on the element. The element which is there is one and on the birth anniversary of Jalog, this is fine, you people are fine, but this too, so see which index is this, which index is running now, which index of cake is running because till now it is at k0, isn't it? I am zero's, okay, we have not yet reached this index, then we will store which elements will come, no problem, okay, we have just made the cake one, we have not taken any element yet, just made it one. Okay, so I was small, so what did I do? I made I bigger. Okay, great. Now let's see what is mine. Let's move ahead here. Who is smaller? Okay, three is smaller. But let's see what is the value of K. The value of K is the index of K. The index of K is 1. We need index 3 and 4. They are not there yet. We do not have the right. What do we mean by index 3 and 4? So we have not reached yet, it is okay, so there is no problem, we will take two of them in the hotel, no three, if we had to take them, then it would be okay, then it is an obvious thing, we will move ahead because it was small, okay ? It will definitely increase. Okay, great, now which one is my I am mine, you have gone to me, it is still zero, which element of the index number is seven, it has 8, so it is still small, so two. If we need three or tax then we have not reached it yet in the index. No matter the key value move forward and science i was small then we will move i forward ok can't do anything story is over ok now auto there forward . Let's move on okay let's move on there what's < what is win index zero to zero okay now let's see brother and we only had three in index one okay so and what element are we looking at right now we are looking at 8 meaning my index The element that was going to come in one was 8, so here I stored 8, I told it that this is going to be my element one, it is clear till here, okay nine , so what did I do element here? Which element was inserted in you ? Okay , now look, pay attention. Now pay attention. So, what size percentile is equal, you are one, is it like this, is our size not order, our size is even, so if it was odd, if whom did I return, size bye. What did I tell you in approach 1 that if it was odd, it was okay, we would return whatever element was in the index. Right, size by, you see, here you are my index, you were which element in index 2? You are leaving the is element. Okay, so if it was odd, what would I have done? You would have returned the element and if it was not so, if this is how I am, look at the size, if my size is at, then you would have to store two elements, size by you, minus one side, remove it . Remember, earlier it used to move here, we already know that this will be my middle element with index or these two elements in between, if middle or this will be the middle index, then we can already know because I know . If the size of the table is going to be M + N, then I can already know which elements are there, so this time I did not take the temp, I just kept increasing the cake and as soon as I caught the index I have stored it, ok till now it is clear and just returned it, finally after checking like this, ok, so we just have to change the existing code, we just have to remove the tempo, ok, just handle both of them, ok It is clear till now, you will not have to think separately, we will enter the approach here, we will see whether G is pointing to the index, is it the index we want, now we will assign it in it, I will also check it for you and if it is not so. Look, you used to pick up the elements from the terms, okay, so here I am small, the name will be picked up from the studio, so salt only, look, the name will be picked up in the morning, this is small, but here I will check that if k = id is equal to x1, look here. That if the id is equal to This is the small one, right, where will the butt go, so here also it will be the same, Namas tu will be assigned to element one, when we will make this equal to tu , here we will do k plus, okay, then we will do the se thing here and what else to do. Brother, look, I have to do it, but then the same check will be done that if the ID is equal to x1, then it will be in element one, okay, time has been removed, it is just turning off the game, let's go ahead and record it quickly, modify the existing code only. Will do this and it will be solved quite simply, first of all remove the thing which was giving pain brother, remove the space, first of all ok and now I have come up with the size that my size will be M+N, till now it is clear and the size. I can also calculate that on the basis of ID x1, what will happen to me ID Remove it completely, remember what we used to do here that if Namas one of I is smaller than Namas tu of K, then we know that the one which is smaller will be the one assigned, right, it will be the same, so its Let's look inside, if k = ID It's okay, the code will be from, it is clear till now and yes, what will happen in this case that i will move forward i + and what will happen in this place is put in plus because the one which is smaller, we will acquire the same element, right, and both In this way, K will increase, it will increase, so I have made K outside plus like this, take this one clear, it must be clear to you, okay, I will minimize this loop, here it is clear, now we have done it. Now remember I < M, for this, pick this one from I <, we mean this one will work, now the name one will work because the one element from the name I is not finished yet, so I copied this, I simply copied this. Look element one number one i because i is not finished yet so the number will not move forward, only the name will move forward. Okay, similarly, if K is not finished, then I have pasted the logic of K here. Look, it is clear till now. If you have seen these, then the code is absolutely correct. Now, we had already calculated the size. Now look at this equal . Tu one means odd, its size used to return the right element, see what size it was, the element was right, the right element was, so here I do not remove it, I will return the element, it is clear till now and if it is not so. Had it been there, we would have added element one, element tu plus element tu and 111 and made it 2.0, let's run and see. We need a little butter approach. Okay, where have we missed line number 30? We were doing it here too, let's run and see. We have missed one thing here and yes remember it is ok we will make it with best approach ok we will see this approach in it
|
Median of Two Sorted Arrays
|
median-of-two-sorted-arrays
|
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106`
| null |
Array,Binary Search,Divide and Conquer
|
Hard
| null |
120 |
hey guys this is a lead good questions 120 the triangle right so the question is given a triangle array return the minimum number minimum path from top to bottom for each step you may move to an adjacent number of the row below move formally if you are on index i or any index right to cut it right you may move to i or i plus 1 on the next row so let's see first example is you know first we have triangle which in which it is 2d array that contains different values 2 3 4 6 5 7 like that right so at index 0 it is 2 index again we have 3 2 4 3 4 like that so how we calculate so first index at 0 will come to this row right and the second will come the next row right similarly we will do four other indexes that will do the next to next row right as we have here now you have to return the minimum path sum from top to bottom so how will calculate from 2 will start 2 is along in the row so we will start from 2 then we will move to next row 3 to four and in three and four three is new in the next row we have six five seven in which five is minimum and the last row we have four one eight three in which one is minimum so when will calculate 2 3 5 and 1 which is equal to 11 right 2 3 and 5 we will do sum and is it is equal to 11 so we have to return this element as a value right so this way we have to calculate the value the logic graphically so now let's understand how we are going to do the coding so already you have the skeleton given in the link class and the method that contains is a list of listite because we have already given right in this class right list contain a list as a argument okay at each index of list of integer this is called triangle right like you can see uh a triangle we have here two three four six five seven four one eight three like this we have that is a list of list in this way what we have to do we have to take the first size of the array right and then we will take a new path some value that will uh contain uh the max integer value right now we are taking db because this is a db based question right and dp array will contains the calculated value that we have already gone through like if we are going from two to three or two to four right so if we have to check the value then it should be somewhere that is the dp right so generally people used to use gpu only to store the value so that it is called memorization right we do not need to recalculate the value that's why we used to take wp here okay now focus on the thing right so easily we have to fill the dp all the columns or all the elements value as a minus one means we are not have calculated this index value you can say particular uh element will not calculated right then we will try to and this you can say this dp will fill automatically by using array dot phase method right now we have to move each element right how we will use g equal to 0 to j is less than n and j plus in which we have a method memorization solution here triangle n minus 1 j and dp so this method will give you and you have to check the new value like we have the max value and if the calculator value will come from the memorization solution method so we have to check right the path some selecting element last row that will contain a element right so in that we will check which is menu that will be the math that will calculate the math and it will written mean path sum and that we have to return so this method that we have written memorization solution is basically contains the logic right so nice like a triangle we have added i j we have n minus 1 and j and dp we have the to store the value right so we have here multiple conditions right we have here multiple conditions based on different examples right that we will see now and this dp will con we will store the value now the first logic we have i equal to 0 and j equal to zero because there may be only one element like example two have only one element right so the dp zero will contains this value right and it would get i and get j will be the return sum value because there is only one element i 0 g 0 correct because i is annoying n minus 1 right and j is the index of inside of the triangle right so example 2 we have triangle minus 10 and we're determining minus 10 as the value whatever so this case will get satisfied and it will return the sum no it will not go forward right now we have two we have three uh other logic right like if we have i is less than zero or j is greater than equal to i dot get i dot size this the sign j value is greater than the size of what and the size right so in that case we have to divide the max integer value by 2 and we will return the value right which is i think in this case that is not possible right so we will move to the next if condition and we will check if the error value is not present right means if dp doesn't have value right it is not calculated right it's already calculated sorry it's already calculated not equal to means it's already calculated then we will return we have i and j we do not need to calculate in the last we will check if it is not minus 1 means we have to calculate then we have to check very simple thing right to store in the dp the first main path by moving up mean path by moving up left this will calculate exact value right like in the memorization solution we are calling internally this one right to get this value from like uh top to bottom like that right two three five type so we are doing so the first moving up we will take i minus one j and dp right you can see here i minus one j and dp plus this will the other value will be also there don't get i go to j right and then up left we will take i minus one j minus one and similarly i don't hate i get over there now we have to check up is b1 yeah off left is v1 in that case what we have to do we have to check which one is minimum and that will store in mean path at i j at index like this okay like this and then whatever the value will come you from moving up and moving up left right that will come into the this variable right uh mean path at i j index and finally we will check math dot mean and moving up and moving left right and we will google the value and we will store this value in dp right so here we already know if db doesn't have an already has been calculated then we will return if not then we will move to here this position correct so i think uh you are understood all these logics but if you have any doubt right please ping me in the comment box or you can approach me to resolve your doubt and be in touch we continue the programming shift as well as our export funder thank you so much please subscribe
|
Triangle
|
triangle
|
Given a `triangle` array, return _the minimum path sum from top to bottom_.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.
**Example 1:**
**Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\]
**Output:** 11
**Explanation:** The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
**Example 2:**
**Input:** triangle = \[\[-10\]\]
**Output:** -10
**Constraints:**
* `1 <= triangle.length <= 200`
* `triangle[0].length == 1`
* `triangle[i].length == triangle[i - 1].length + 1`
* `-104 <= triangle[i][j] <= 104`
**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
| null |
Array,Dynamic Programming
|
Medium
| null |
1,012 |
hey everybody this is Larry this is me doing uh a second bonus question man I don't know just figure out I uh put it on YouTube so maybe people can figure something out from this um this is not gonna be my usual video in the sense that I am going to stop alive but I know what the answer is kind of but I am out of practice with um with this poem um so it's August 15 or 14 or 13 whatever uh August 14 2022 and to earlier today we did a contest where this was the Q4 right the Q4 was count special integers and I kind of did it this way you could watch the video I'll put a link below um on the original video but I knew that I could have done digit DP but I was way I was so out of shaping it that I just was I was trying to figure out another way but I think if I had just been more practice even though I know how to do it um I work in you know just want to see how that goes by just practice more right um and someone told me that there's another problem that's almost the same but this time so I mean so yeah um so the idea is going to be very similar but uh um I am going to try to solve it with digit DP um I don't know how much explaining I'm gonna do so maybe this is just experimental this is additional Library practice and you're watching me just practicing even though I knew the answer kind of um because this is just implementation and also with I think that's the one thing that for me um is that for digit DP specifically and this is this probably what is true for a lot of things but for me specifically is that I do know the concepts but I am often um I'm often like they're off by I you know these things have to be very careful and I'm often just getting off by once in the past so that's why I'm a little bit shying away from in the past at least in terms of contests so um but these things do get more familiar and more um you know easier as you practice like everything that we do on this server and Channel or whatever uh terminology we use so yeah so hopefully that makes sense um hit the like button hit the Subscribe button join me on Discord uh if I didn't explain it that well in this video and you only came on you know if you Google this uh problem and led you to this video and I didn't explain that well I apologize uh but this was kind of for me maybe and then uh you know if you want to watch it fine if not watching 2x do whatever you and then see how we think about it okay so here uh there is a little bit difference um so between this one which I haven't done yet actually so um yeah so the difference between this one is that the on a contest and I guess this part I am explaining a little bit on the contest it gives you that or the number or the digits are unique where for the problem I'm solving right now it's the opposite of that right it has at least one repeated digit now you know one obviously if they you combine them you get n right so that means that n minus this uh if I do n minus this uh problem like if I just copy and paste this and I vote n minus that would be the answer and of course I can write a digit DP specifically for this problem and then n minus that to get the answer right so there are two there are already two things you can do and doing a contest um whatever is easier for you to visualize and get quicker and you know fewer mistakes just do a little bit right there's no right way sometimes there is a more optimal way so I don't know um so that's it for this one I don't want I guess I'm just setting my goals for myself um adding constraints because I don't want you know like it's not practice if I'm just doing things that I know how to do right so I'm deliberately I'm setting constraints on myself so that I could write it in a different way right I don't I'm not here to memorize I'm here to figure out how you know especially in math a lot of things uh you know if a plus b is equal to C and C minus B is equal to a then you know um it's up to you to figure out you want to you know calculate A or B or C or and then you know combine them in interesting ways and of course they all have different implementations but it also means that you have to now that you define the problem you have to write the code very specifically for it right and so here in you know I'm not going to do the n minus uh uniqueness frame I'm gonna do at least one repeated digit range so let's think about what that would look like um so okay so digit DPM I'm gonna not be that creative of the naming um and of course I'm just gonna do um uh what you might call it funk toast cash uh if you want to read up on it you know that's from here um the idea is that it does memory station for you we'll go over maybe how it works later but for me just you know I'm focusing on implementation right now um and also because um and why I can do that is that you know we'll think about their thing um but for digit DP the complexity n is not the input n the complexity n is often um uh this the length of the input right so and the length of the input is 10 to the nine so it's going to be like 10. so you know even 10 to the fifth is fast enough as long as that with that really sloppy or something so that's why for now I'm not really thinking about that um so yeah um first of all let's create a cache let's just call it s so we want to convert this to a string and then we change it to a list so that is a list of characters and then yeah and then we map into it so that now is a number and then we convert it back to a list um I know that you don't have to write out list but I'm old school python 2 I guess I don't know yeah um okay and let's just say the real end of big n is link of s right so here you know we're going to calculate one um we're going to improve four as calculating all the digits one at a time right so we have an index that's just you know which index of the number that we're calculating on um let's see I think in this case uh okay one is let's just say it's prefix maybe uh we'll go over this in a little bit but this is very common um the idea here is kind of similar to um how to explain it I am explaining it instead of just implementing it I know but for example if you have um uh you know a random number let's say one you know something like this well the idea here is that you wanna um the idea here is that when you do a Brute Force elevation well let's say you have zero and then it's the first digit right and then that means that I put XXX but the idea behind X is that X can be any number from zero to nine right and here one while we cannot be an X here because it can only go up to two so then now it can only be zero or one right double XX previously so then now and one two uh you know this cannot be true so then now we have five but before that you have one two zero x one two one x one two x dot right so this is prefix just means that do we go I mean that's the way that's my notation maybe it's a little bit off I often um with these things I remember the concept from when I first learned these things maybe like 20 years ago now I know I your reactions may be that Larry looks young and you're probably right but still I learned it that long ago and so my terminology and notations may be a little bit off because I'm of what's you know standards these days because people have done amazing things to kind of clean up code uh to write like really tight code which is actually kind of and then everyone just copy off each other which is kind of uh cool in an Innovative way because everyone's trying to like optimize it almost right but for me I'm you know I'm here for the way that I find myself learning is just to create things from first principles uh as much or maybe not the first principles but like you know my own principles and then and so my terminology may be really offer um but yeah so yeah it's prefix to calculate that so that in this case if this is the prefix it only goes up to the digit that we're looking at so that's kind of the idea there um and then the other one is that we don't want to count leading zeros so here for example you know uh remember leading zero is technically a three digit but and a couple of ways you can handle it depending on how you want to do it um one way you can do it is just like having an outside for Loop that handle is like okay let's do it for every three uh yeah you can do it with like hey let's do it for every uh zero digit uh one minute that's probably uh try for every one digit number two digit number three number then there you don't have to worry about leading zeros um but this is the way that I'm doing it uh is that I do have these zeros but it's rather whether that I mean the two ways of doing maybe I'll practice the other way another time uh but here for me it's just about having okay now that you know let's just say we do assume you know uh oh in this case it's actually um yeah okay this is a little bit awkward because this should be a one maybe but you know this is just explanation uh or visualization so it doesn't have to be precise per se maybe but maybe that's not true but anyway so then um the idea here is that um yeah this is just our way of skipping digits really um but only at the beginning of zeros so let's just say maybe it's leading uh or lead maybe like we already had a digit uh or something like that and then just a mask this is just a lazy way of or maybe and also um so this is It's prefix and then I have one more which is that uh repeated right that means that has any digit already repeated it changes some state of things but uh but yeah uh and the bit mask is just you can think of it as um that's a bit as a vector map uh or a bullion Rector or a bullion list that basically let us know whether any number from zero to nine uh that was in the nine but from zero to nine I used any digit right so for example um yeah I'm not going to go over a bit Mastermind I would also say that digit DP is a little bit of a advanced DP topic um so I'm not gonna go over some of the DP Principle as much as I would normally definitely if you are struggling with basic DP principles check out my other videos are you uh depending on the day I usually do feel like I try enough uh to explain it pretty well but this is a bonus video so anyway uh so okay so index is equal to n then we're done but we don't automatically return a one right we return a one if repeated is true because if there's no repeated digits we return zero um yeah and then now we just do a for Loop okay so if it's prefix what does that mean if this is the prefix then then we have to keep track of you know the first one right um yeah so basically we want to go up to a limit so let's just call it limit maybe uh if you go to 10 from 0 to 9 you know non-inclusive so if it is prefix then non-inclusive so if it is prefix then non-inclusive so if it is prefix then limit is equal to uh s of index and then now we do uh you know our current digit in range to the Limit because we don't include the number if this is the limit we go under it because then you know we'll add another thing later maybe okay so that means that um like maybe I have to do a better job separating out the zeros so let's do that okay let's just say this goes to one pass for now and then let's handle the zeros okay if uh lead is such a terrible name uh let's just say uh is sled that's this is terrible okay I don't know how to name things but okay so if we already had a leading zero this is this part is going to be handle zero let's just add a comment here um so if we ever had no sale if we already had a leading zero then we can just use zero right so that means that and I've got to add a total that means that total we could just increment it by go we index by one because now we're going to the next number we use zero is prefix um is it prefix no uh well I think I have to do another if statement here maybe that's a little bit sloppy hmm um because the idea here is that if 0 is less than limit right uh basically if the limit is zero meaning that this is prefix and the limit and the number is zero we do not you know do this Free Loop thing right but I yeah because then we'll handle it later with the s prefix so yeah so if there was a good limit less than limit then we could put a zero down and what happens when you put a zero down well when we put a zero down the prefix is no longer true in this case uh by definition so we have force is Led uh yeah I mean it already is a sled so it's true and then mask we just use the silver um yeah but I also made a mistake again so this is just equal to one so let's just say one I also made a mistake because I have to check that um and mask the one is zero to zero don't forget to prevent basically it's the thing that we haven't used yet then we do this else if it's not leading zero um then we can actually just do this to go to a smaller digit is the idea uh as prefix still no it's not because it has fewer digits um and we do not use this yet right I'm missing a parameter yeah okay so here oh I guess we don't I forgot that this we don't need this to be zero because I'm thinking of the other problem even though I know that I told him I said I shouldn't but um so yeah so here we do magic over one but then the repeated we want mask and one I as you go to um one something like that so if this is already used we make the repeater true um I know this is not complete hang on I'm just typing really slowly um it's repeated or this Frame right because basically this means that if it's already repeated then we always satisfy this condition otherwise we check to see whether this makes it repeated if this already exists then this means that we already use it so that's fine otherwise you know um here we also just passed along repeated and masked because this is just skipping to a smaller number or smaller or a smaller fewer digit number okay so zero has a weird case because you know we have to handle the leading zeros and stuff like that but now we have to handle the uh for digit one at a time right so Toto we added to go index plus one assuming that this I think this is fine um is prefix in this case it would always be first because by the definition of limit right because if it is prefixes with you know um is Led yeah this is true because we by just putting this down we already have a leading zero um repeat it so we have BP we could actually use this thing that we had earlier but and one to two d is not equal to zero and then the other one is masked and right I'm not going to go sorry if uh this looks a little bit whatever I'm not going to go over bid master um you know I'm not going to consider that in scope just because you know this is uh something that I'm just practicing for myself but also it's a little bit Trend so like you know you should practice it elsewhere I did a lot of bitmask problems so yeah uh okay and then I think that's it oh no uh if it's prefixed then we add in a thing as well I guess we can move this up because um then we can do let's add in the digit let's use this one uh which is that is prefix is still true because we kept the prefix digit and then we it's LED also true I guess because uh a Nestor Now by definition it should be true because you're just taking a number and there are no leading zeros in the input so that should be true repeat it is um repeated should be the same thing I guess repeated or mask and one limit uh is not equal to zero and then mask and one to two limit right um and then at the end we just return total I think this is okay uh well we have to kick it off first but we start with index 0 is prefix is true because we wanted the first digit to be bound by that prefix is Led is boss because we haven't done it yet no repeat and the mass is zero that's how that goes I think that should be at least it um and maybe some complicated numbers but I think just to kind of see how that runs okay so that looks good I'm pretty happy about it let's give it a submit cool uh yeah so like all dynamic programming problems we can think of the complexity real quick basically total time complexity is going to be just number of test cases or not test cases input cases or input yeah times time per input and total number of input is equal to oh I didn't do this I did them in the weird way and that is 0 to n hopefully that makes sense is prefix is binary uh is lead it's also binary repeated is also binary and mask is 2 to the 10 so in total the number of inputs is going to be all of n times a times 2 to the 10 which depending how you want to say it but um is I don't know I'll leave it up to you this is technically all and I mean I know how to figure that but maybe it's more like um two to the alpha where our first number of digits um of course in base 10 it's going to be 10 but I don't know maybe that I just might find it uh annoying to kind of give it up that way so that's the number of inputs and the input each do about um so one more thing I would say uh well I mean okay so the way that this is that um each input takes all of uh Alpha time right the way that I wrote it um so total time is you go to O of n times two to the alpha times Alpha roughly speaking I'm a little bit later on this one because you could have a tighter bound but one thing I would say is that you can you know this complexity comes from here right um and as it turns out um you can I mean it's a very complicated optimization or not complicated like in terms of tough to understand I think the understanding is easy but it's just a lot of work to get it right which is that you can um I think you can in all of one count like and yeah I'm not going to go over the details here but no one can count how many numbers you have used in this mask um and then do the multiplication that way right meaning that you know maybe like for example let's say mask has seven uh The Mask has seven digit used then and the limit is I don't know five you can look you know you could it's just as a hint you could create some kind of data structure that you could create some sort of data structure that allows you to um figure out how many of those five are used and not and then let's say you have three used and two unused in this within the one and the limit then you can just do you know three times whatever plus two times whatever right on the repeat it and now repeat it um I think maybe that's one way you can do it although maybe not because of the way that we did this mask thing so maybe I'm lying here um I don't know if that's true I don't know but something these are things that I would think about optimizing if it if I had to so yeah um that's pretty much all I have and in terms of space it's just input the number of inputs because it's all one per space um I actually I mean I note that I spent a lot of time talking this video so I don't I kind of failed in my task to kind of see how long it would take for me to implement this from scratch um because I mean I can't even blame it on talking right because talking a fool makes it easier for me to implement um and for me I would like to get an honest assessment on how long it would have taken but you know at the end of the day it's just about learning and I think just the way that I did it was a really good way to learn um I know that there may be some details about digital DP um it'll have to wait for another time but for now that's pretty much all I have so yeah let me know what you think let me know if you try to solve this problem as well how did you do and did you do it just did your DP uh technology anyway have a great night stay good stay healthy take your mental health I'll see y'all later and take care bye
|
Numbers With Repeated Digits
|
equal-rational-numbers
|
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
**Example 3:**
**Input:** n = 1000
**Output:** 262
**Constraints:**
* `1 <= n <= 109`
| null |
Math,String
|
Hard
| null |
938 |
hello I will be doing all nine three eight one little which is called rate some of my research tree so given a root note of binary search tree return the sum of values of all nodes between L are the binary search tree is guaranteed to have unique values so in this example well we're given this binary search tree and the left of 7 and our 14 so it's key is shown as an array because you can also infinite binary search tree as an array in that the first node would be 10 will be the root node and then 5 and 15 would be the children of 10 and 3 and 7 will be the children of 5 and next to it would be the children of 15 so given that this is a binary search tree versus your tree I don't think that really helps us with the problem I think we'll still have to look at all the nodes in order to we can skip off on some notes I guess yeah we can start out with looking at all the notes and let's see how we can make that a bit better later so I'll start with writing a poem called Grangetown PSD so this in the root element and this will be a recursive question so the we will want to call this function on the left and right note but let's see what this function would return who's talking to return the some deranged some of the subtree so subtree would include itself so let's have a result equal to 0 and let's say if the roof is in between an R then we should add the value to the root cellar if roots that value is greater than or equal to L and we've got value is less able to are that we want to add the grid of value to be the results and now we want to find the sub we want to do the farm personally and other results when you walk and write if they ageless so if you've got left then reads out plus equal do it that left the personal part of the Bella which is this Ellen R say the same because they're in constant between the whole function so if we've got right exists and you want to also call a recursive function and we want to then return the results of the three values combine it with fur node will let the results of the left node and themself up right now great so let's see if this works so it looks like it's working on this exemplar here I think there's one optimization that we can do in that if the let's see so if the current note is so look if the left node is yeah so if the current note is less than if the car knows less than left are you then there's no point in looking at the left sub-tree because all those bodies left sub-tree because all those bodies left sub-tree because all those bodies are all going to be less than the less that by yourself you want to ensure that the current node is greater than the left value if we want to continue looking at the left no so and we've got Bao greater than the left by you I'm the same could be applied to the right side so what works let's try submitting it and seems to be fine
|
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 |
712 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge minimum as key delete some for the string so basically what we are asking here is that we get two strings S1 and S2 and we want to return the lowest as key sum of the deleted characters so that we can make the two strings equal so for example let's see here for these two what should we do well we should definitely delete this s because it's not in S2 and delete this T okay and so if we count the sum of the ASCII values of these two uh for S it's 115 and 40 it's 116 so the sum of that is 231 so that's the idea um strings are not too long they can be up to 1000 and we have only lowercase English letters uh so let's see how we can tackle it um okay so how do we how to tackle this well the problem asks us for the lowest ASCII sum we could for what we can remove okay and this is like sort of asking for a Min okay so it's sort of an optimization problem here and whenever you have an optimization for a problem the approaches you should try are definitely um either greedy or DP okay but if you think about this problem there is no real like greedy any greedy heuristics that comes to mind um so we should think about using dynamic programming and dynamic programming of course there are different ways there is recursive solution and then you can apply memorization and then there is the other tabular dynamic programming where you have the Barb up and then you have the top down okay so but it's always easier to do this one first so let's try it and so for the recursive function what should be our state well we have two strings we have S1 and S2 okay so what could be the sub problems well when you have a string let's say like I don't know like seat and eat that we had earlier like see indeed okay these two so once a problem is we already solved it for suppose we already solve it for a prefix like this one okay then now it's just a matter of solving it for the remaining elements this one and this one so with these strings usually even just as a something to keep in mind it's usually when you have them you should think about okay can I do a prefix can I do a sub problem with the prefix or can I do a sub problem with the suffix so like this or can I do a sub problem for a range is less covered but the prefix and suffix are more common okay what do I mean by prefix in suffix by prefix and suffix so let's take the prefix so by prefix we mean let's consider that we have the solution for I up to I and up to J for S1 and S2 which basically means let's consider we know the lowest ASCII value the minimum ask is something that we need to delete to make S1 up to I the prefix S1 up to I and the prefix um S2 up to I up to J sorry okay if we do that then how can we solve it for uh how can we solve it for up to I plus 1 or up to J plus 1 or let's say let's consider we know it for up to I minus 1 and J minus 1 and see how we can solve it for I and J so that's the prefix part suffix is pretty similar you could say let's consider that we have it for up to let's say I here so how do we I plus 1 so how do we find it for I let's consider we have it for I plus 1 and J plus 1 and how do we solve it for I and J uh prefix is sometimes less intuitive but um then prefix so let's try the prefix version first okay so then we definitely know that our states needs to be I and j i is the prefix is the index for S1 J is the index for S2 and so for our let's call our function Min sum okay so mid sum then the state is going to be I and J so let's think about what are what is the recursive function and what are the base cases Okay so since we are doing the prefix right then if both are equal so if the character at S1 is equal to the character of at S2 like for example in this case a is equal to a then what's the costs what's the minimum of some original the buildup sum for these two the derivative of sum for this string and this string we don't need to add anything because it's they are already equal so there is no cost so in that case that means we should just return the mid sum for I minus 1 and J minus 1 right the mid sum for the prefix up to I minus 1 and up to J minus 1 and now we have the result for I and J because they are already equal okay now otherwise what they are different let's take an example maybe let's take delete and delete okay uh let's for example assume we already did this one and we already did let's assume what I did zero one uh zero what okay let's assume we are looking at I equal to 2 and J equal to 2. okay so two so they are different L is different than e so what are the solutions we can do well we can recurse on we can recurse or this portion so we can either decide to delete this one L or decide to delete e okay so we can decide to delete one of them and try both right here it happens that deleting L is better but we don't know so we try both okay so what does that mean for both well we could just return the bid sum for the Min for trying both so either we try to delete the element at I so that means we uh let me actually put it here so that it's easier to see so we can either try to delete the element at um position I all right so that means we have now I minus 1 and J plus the cost for deleting at I so that would be S1 I okay or we can delete at J and so that would be the mid sum for since we are deleting at J we are going to do J minus 1 to get the prefix for the prefix up to J minus 1 and then the cost for J is just going to be the alt for S2 of J okay this is the overall bid that's pretty much it right so we try both now you may say okay why not delete both and try one this will amount to delete this recursive function if in the first call we call this one and then the second call will call this one then that would be the same as deleting both so it's redundant here okay now what is the base case for our recursive function well the base case should be just when uh we reach the end and since we are going backwards with I minus 1 here it's when we reach with it's less than zero so if both are less than zero then we are done right so if both are less than zero then we can just return 0 because we are done now when one of them is zero and the other is not let's say for example if I is equal to zero then we should just add the cost for deleting these because to match an empty string we need to delete them if J is 0 and I let's say maybe is here we need to just delete everything remaining in I in S1 right so we can fill this up when we are quoting but that's sort of the idea here so this is the recursive solution now what's the time complexity for this solution well uh Wicked cache so first we will cache so that we don't do it at that computation and so here we just need to look at what is the space for this what is the number of values I and J can take well I can go from 0 to n minus 1 to N1 be in the length of S1 J can go from zero to N2 and since this is cached we will not have more than these uh values and so since it's a combination it's a product so the time complexity is going to be uh of N1 multiplied by N2 okay and that's pretty much it um okay so now that we did the recursive solution let's implement it and then from there we can look at the tabular solution um okay so let's code this up so we need um to have our function let's call it Min sum uh that takes the state here so we have I and J um and since we already seen the two variants let's just copy them over so if they are equal we just keep both um so we are not deleting anything and so we get the result for the prefix and here uh we have only two choices so we delete one or the other so let's delete first from S1 at position I and then delete at position J for from S2 and see which one is the Min and now here we can do our base cases where we already chatted about those so for if both are negative that means we are done we just return zero no costs if I is negative that means we need to delete um we need to delete J and then we can recurse to delete 40 minus one so basically we'll the other way of doing this is to do something like um like this okay where we just take the sum of all the values up to J right or we can do it recursively this J and then go to J minus one then delete J minus 1 and go to J minus two just to be consistent with the recursive approach I prefer to do this so let's just keep that um and then we do a small thing for J um if J is less than zero then we just delete the remaining elements from S1 um so we can do it like this or we can do it like the one we have here where we um where we just do something like this okay so we can remove the sum so we delete at I and then go back to I minus 1 and then after that we go to I minus 2 until both are negative okay but that's sort of the idea here now we just call our recursive function so we're going to call it with since this is the prefix we want to start from the end right and so we start from -1 here and then two so we start from -1 here and then two so we start from -1 here and then two minus one okay so that we can go backwards until we reach the end um I realized that it may not be clear whether it's prefix or suffix it doesn't really matter you should think of it maybe as better a better way to think about it maybe is going forward or backwards and here we are going backwards okay so here we just need to Define N1 and N2 so length of S1 and length of S2 okay uh this passes now we just need to Cache now in pi you can of course use a hash map with the IJ as the key but I prefer to just use Python cache uh annotation because it's quicker um so looks like it passed okay so now let's try to do the tabular approach okay so for the tabular approach pretty similar we just need to find our state which is going to of course be depending on these two values so I and J this is going to be uh basically lowest ASCII for up to I and up to J well basically the prefix up to I in the prefix up to J let's call it prefix in S1 and then prefix in S2 okay so now for the transition function here this is going to be pretty easy it's just going to be if both are equal then we do I minus 1 then we do like this I minus one DP of I minus 1 J minus 1. if they are not equal then we try DP of I minus 1 J and DP of i j minus 1. okay there's just one thing we will need to do with the prefixes to avoid because this is a table to avoid like if we do I minus 1 and J and I is equal to zero this is bad because we'll get minus one here right and so we're gonna do in a way avoid that and so how do I avoid that well let's just have our DP table have a size plus one have n one plus one elements that way uh for i j here what would be really what we mean really is that we are examining I minus 1 up to I minus 1. and up to J minus one just so that if we do I minus 1 here right it's going to be not I equal to zero it's going to be I equal to 1 right and so um but we are actually looking at S1 up to I minus 1 and up to J minus one just to handle the prefixes but you will get used to this once you do more programming problems so here we need both like that let's actually just keep the function because it's easier to change it uh so we have this let's just put them up and do our tabular our table here for DP so it's just going to be since it's a DP of I and J we need the rows to be a zero to n minus one the two and one sorry zero to N1 so that's what we do here and then the inner column are for J so it's a zero to N2 and here we'll do this in Python just with that we stop at N2 and here we stop at N1 because remember to get up to N1 minus one we need to go all the way to N1 here okay so now we what's the order of operation what the order of our Loop well the order of our Loop needs to be increasing because when we reach I we need to already have calculated I minus 1. so we need both to be like this we need the order of computations to be uh to be forward not backwards um so now what we need to do is just sort of do this but do it in a way that um that it uses the table so here of course this needs to be DP of inj and this is needs to be just DP of I minus one so same indexes just using a table now to store them and here let's go let's do else it's going to be DP of still like this I and J is going to be equal to either the Min now remember we said here that this is going to represent I minus 1. uh two chain minus one and so to do that means this is S1 I minus 1 and this is estua J minus 1 similarly here okay this way also this up to n by N1 will actually calculate all of the States including four zero okay because for zero we'll just check S1 0 and S two zero uh but it will be represented by DP of one okay I hope that made sense now what we need is the base cases what are the base cases well the base cases are when just similar to what we did here where the base cases are when smaller than zero we can do the base cases here with equal to zero because we are not able to do DP of minus one and so it's DP of 0 and J and DP of 0 I and zero with the column is zero so for this one we can just go for I in all of the uh possible range for I and what should it be well should be just I minus 1 0 Plus we are deleting at position um I okay and so to delete that we just get the art um and we get I minus one because remember again this here means at position I minus 1. for S1 okay and so that's where we delete here um and so let's do this base case and similar base case for we need the solar base case for um for J so the base case for zero it will allow us to have some State when we are Computing these a previous state for the values of zero so here J 2 this is going to be 0 with j and similarly it's going to be the prefix staying at 0 for S1 but removing the element at position J so that would be S2 J minus 1. okay um and that should be it really and you can see really how it maps to the other recursive solution so we can delete this because we just did it's just the base cases here instead of doing them here you do it up like this and then this Loop here instead of doing the recursive call you just do a loop to calculate all of them and that's what we are doing here because we are caching anyway right and so here we can just remove this is going to be just DP of M however here since remember I J here is sort of uh one step in advance and so to get actually for S1 up to N1 minus 1 and up to N2 minus one we actually need to do and one and two okay um so now we just need oh this is not miss sum this needs to be DP of course because now everything is in the table and similarly this needs to be DP of I and J minus 1. okay so if I run this uh looks like we need to close the bid function looks good let's submit and it passed okay now in terms of time complexity the solution here we this is of N1 this is of N2 so far we have of N1 plus N2 time and then this is N1 multiplied by N2 so this is actually a bigger the bigger portion so we can delete this here so this is the time complexity the size of S1 multiplied by the size of S2 uh in terms of space we are also using this DP array which has the same size um the same N1 by 8 and 2 and so the space complexity is also going to be uh off N1 by 2. um yeah that's pretty much it for this problem uh please like And subscribe and see you on the next one bye
|
Minimum ASCII Delete Sum for Two Strings
|
minimum-ascii-delete-sum-for-two-strings
|
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum.
Deleting "t " from "eat " adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
**Example 2:**
**Input:** s1 = "delete ", s2 = "leet "
**Output:** 403
**Explanation:** Deleting "dee " from "delete " to turn the string into "let ",
adds 100\[d\] + 101\[e\] + 101\[e\] to the sum.
Deleting "e " from "leet " adds 101\[e\] to the sum.
At the end, both strings are equal to "let ", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee " or "eet ", we would get answers of 433 or 417, which are higher.
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1` and `s2` consist of lowercase English letters.
|
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
|
String,Dynamic Programming
|
Medium
|
72,300,583
|
368 |
hi guys today I'm going to solve lead code question number 368 that is largest divisible subset so let us try understanding the question says that given a set of distinct positive integers nums return the largest subset answer such that every pair present in that particular subset of elements satisfies the following condition and the condition is that all the elements should be divisible by each other so let us try understanding the first example so the first example says that over here we are giving 1 2 and three so in this case the possible outputs are either 1 2 or 1 3 and this is because one and two are divisible to each other and similarly one and three are also divisible to each other however the largest subset over here was actually one two and three and this is not an accepted or a valid case because two and three are not divisible by each other so let us try understanding this question with the help of a bigger example so let me take the number or the set as 1 4 8 7 16 so this is my set over here my correct solution or subset should be 1 4 8 16 this is because all the elements present inside the subset are divisible to each other my largest subset possible in this case would have been the entire array however 7even over here is present which is not divisible by 16 4 or 8 because of which this will not be a valid case what I can do first is that I can sort all the elements present over here in the array so let me sort this so my sorted array would be 1 4 7 8 16 this is going to be easier for me because I will be taking care of my previous element let us call this as PR element and then I'll be checking if my current element is divisible by my previous element or not so in the resulted answer my answer is going to be 1 4 8 16 correct now let us see how I can check so my previous element initially is going to be minus one this is for uh the code purpose however let us start with one over here let's consider one to be my previous element and my current element to be four since my four is divisible by 1 this is going to be a valid case and I get this subset next I have got eight and in case of eight I'm going to check if 8 is divisible by four or not since it is also a valid case I will be appending eight into my array and similarly for the 16th case now again in this case I'm going to follow the simple recursive take not take logic I'm going to either take or not take the element if my previous and the current element are divisible then I will be taking it else I will not be taking them and at the same time I will also have a subset but I will not be taking the element so let us try understanding this with the help of the code and this is going to be slightly complicated so please tag along while I try to code now let us start so initially I'm going to take a previous element let us take in prev is equals to minus one as I just mentioned while explaining now I'm going to take a 3D Vector over here because I have to store my Vector in my DP as well so let us do vector in I hope I made no mistake one second so this is my 3D Vector I'll name it as DP and this will have the size of my array so nums do size and inside this I will be passing my vector let me copy paste it so that it becomes easier so vector this will be having the size again so nums do size + size + size + one and again a vector and okay now Vector with this I'm ready with my 3D DP then I'm going to sort my array it has been given to me sort nums do begin till nums do end once I'm done with the Sorting I will be simply returning whatever the function I create let's call it fun I'll send my starting index indd then my PR which is initialized at minus one my nums array and my D now we come to the main part the main logic of our code so this will be returning a vector of type in let's call it fun I start with my index IND and my element brief then I will be having to pass my Vector nums which was already present over here and my 3D DP I'll just copy paste it again contr C and I'll pass it with the erson because I want to store them correct now I have to check my first base case is going to be that if my index reaches the end nums do size then I will be simply returning a empty Vector okay and my second condition is that if my DP of in comma one second I and PR + comma one second I and PR + comma one second I and PR + one size if the dp's size is not equal to zero that means it is already having something then I will be returning that so return DP of i d ref + d ref + d ref + 1 cool then I'm going to do my take not take logic so I will initially have a vector let's call it Vector take and initialize it to an empty Vector now if now I'll check my condition if my priv is equals to minus1 that is it is my starting element or my nums of index is divisible by nums of priv in both in this case I will be taking it so my take is going to be function of I + I + I + one then my PR will become my in and I'm left with my nums and my DP then I'll do take do insert take. begin nums do I and then after that I have my not take Vector so what's my not take Vector going to be I'll create my Vector of type int not take and I will be calling the same function then me just simply copy paste it this will be moving going ahead but I have to make sure that my index is not changed so I will keep it as priv now that I'm done with this I will be returning my DP of this should also be stored is equals to now I have to check whichever is having a bigger size if take is having a bigger size I will be inserting my take else I will be inserting my not take let's do not take dot size so here I'm comparing the size whichever is having a larger size gets stored take or not take now let us try running this the test cases do gets passed now I'll try submitting it and here we go I hope I was able to explain it thanks for watching
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
5 |
given a input string we need to find its longest periodomic substring for example investing b a d a b and a b a will be the longest paranormic substrings let's solve this problem first using Brute Force approach in Big O of n Cube using two pointers I and J we can check whether the substring from I to J is a palindrome or not and keep on updating the resultant string and Max synth as specified in the mentioned steps using two pointers let's define the a spironol function and keep on checking the substring from I to J inside the nested Loop for the output foreign foreign foreign with the difference between ing is greater than maximum and a substitution I to J is a palindrome and its length is greater than current max length foreign programming in big go of n Square initialize n as string length left and right variables as 0 Max variable as integer dot main underscore value initialize 2D Boolean DP array and shown in the image please have a look at the steps I will explain them in next slide as we can see in the shown image we will covers I from n minus 1 to 0 and J from I to n for each eye we will Traverse J from I to n let's say if I is 2 we will consider J as 2 and 3 since n is 4 dpij represents whether substring from I to J is palindrome or not there are following three h cases if I is equal to j d p i j will be true since a single character will be a substring of itself hence we can mark the rectangle values with true as shown else if s i equals SJ we have two conditions if J minus I is equal to 1 DP i j we need 2 since string of length 2 will be parandoid L shift J minus I greater than equal to 2 we can rewrite it as J minus 1 greater than equal to I Plus 1. need to check whether DP I plus 1 J minus 1 is pandomic or not hence we will equal this to dpij for each iteration we will update I and J if DP i j is 2 and J minus I is greater than equal to current Max DP I plus 1 J minus 1 means Nest cell in the right diagonal hence I highlighted the cells during each iteration with red and sky blue colors as you can see the image for first iteration will consider one cell in the bottom then 2 3 and 4 in subsequent iterations in bottom of manner we can memorize the blue highlighted left to right or rotated histogram pattern formed for framing the logic less code using the logic we have discussed foreign foreign we can solve the problem in Big O of n it uses palindromic sync properties we can use previous results during computation we will use a LPS array for computation as you can see in the image 1 C is centered in the parent room and LPS array values of characters to the right of C can be filled out right away using the inverted mirror formed because of palindromic nature in example 2 palindrome around a pointed by the arrow cannot be assigned LPS area values stateable since mirror a fine room exceeds the range covered by palindromic substain CAC we transform our string by placing slash in between the characters so the palindromic Center can easily be obtained using the sting of all length let's say C is and R is range LPS is the array we were using to count the number of matching characters around their Center here are the steps wrap input string with Slash character initialize in Array of length n comma c as 0 and R as 0. it take from I to n for each I set inverted mirror variable as 2C minus I update LPS using minimum of inverted LPS value and difference between range and point index if range is greater than fan index and set LPS I as 0. check palindrome around I using while loop and increment LPS I with 1 as long as a current mirror forms and the current character I plus 1 plus LPS I and I minus 1 minus LPS I represents right and left characters of the fine public mirror at last of each iteration update C and R if I plus lpsi is greater than the current range returns substring from C minus r to C plus r excluding slash characters foreign foreign foreign thank you foreign thank you thanks for watching have a nice day happy Ganesh chaturthi please like comment share and subscribe to my channel and feel free to follow me on various social media platforms using the links specified in the video description people working anywhere in the world born anywhere in the world can create a product and make it available to anyone in the world the most used messaging app in Southeast Asia was built by a young man born in Ukraine who moved to the U.S Ukraine who moved to the U.S Ukraine who moved to the U.S and the three most popular viral games in the US in recent years came from entrepreneurs in Finland Ireland and Vietnam you're the ones building the next Google the next 45 the next Tesla the next well we don't even know but what I know is it's the idea that matters it didn't matter where you come from or what your background is one revolutionary idea one Brilliant Invention can unleash other entrepreneurs to revolutionize Industries in ways you can never cut
|
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,518 |
yeahyeah yeah Hello everyone, I'm a programmer, I'm going to make this video to introduce to you a problem about water bottles, a problem called Water Bottles in Lacoste that I just I also find it quite interesting to solve the problem. First, we need to look at the requirements of the problem as we can see that it will give us the number A and a number for a bottle full of water and a number. That second number is the number that I can make. I will use a vase to support the vase without water. This mt, take an empty vase so that I can exchange it for a full water vase. That means now the water vase is I have two statuses, I have a status on the water side, it's full of water and its water tank has water in it, so now the second information tree thing that it gives us is that it will have a the behavior that if we drink what you called drinking water, all the jars that are full of water will turn into empty jars, and that's it, everyone. I see now we have two windbreakers. With that information, let's find the amount that the water bottle has and we can drink the maximum amount of the water bottle and we can drink it, okay. Now let's go. Let's see the example first. It's easier to understand when in pumpkin 1, it says I'm the main one for the water bottle. This is me. The water is full of water. We have something black in this water, which means it's in the bottle. If we have water, then after we have filled ourselves with this water, what do we do? We will perform the act of drinking, so we don't need to drink as we said earlier. When we need to drink , we We have to drink all of ourselves , we We have to drink all of ourselves , we We have to drink all of ourselves , now we drink all of , now we drink all of , now we drink all of ourselves, this system of ourselves. Now there's no one in it whose name is this hammock. Well, now it's this empty self, so I don't want it anymore. okay where but we have a second possibility we need to change Maybe we can exchange this then here it gives me the number we can exchange is three which means we We can take at least three of these clear water bottles and change them into a full water bottle. So here we have the main water bottle and divide it by 3 then we will have three full water bottles. Here we take the main water bottle and change it to 3 cakes of water are full and then continue to drink, but when you drink, all kinds of diseases like this, now you have three bottles of this sauce, three bottles of it, two of them, and continue to exchange for a full bottle of water. If we continue to drink this water bottle, we now only have water left. Well, we can't replace it with water alone, so consider the program ending here, so in total, we have How many bottles can we drink? From the main plus 3 plus 1 to 13, let's continue with example 2 to make the problem clearer. Well, with this example 2, in the beginning we will have ten bottles of water. I'm full, then we'll do it. We'll have 15 bottles of water to drink. Well, it's the same thing. We have to change the water here. Now the water value is four, which means four bottles of water. If we change it to a push-pull water bottle divided by 15 change it to a push-pull water bottle divided by 15 change it to a push-pull water bottle divided by 15 divided by 4, we have 3 full water bags to make three water bottles. Ok, but now we have up to 15 water bottles, but we still have 3 bags that can't be converted to 13 large water bottles. Hey, now we're constantly drinking cakes and tea. Drinking water is all bad, and the water here is bad. The water up here won't change. I'm full, right. Now I only have water. This plus two equals warm water and drink it one more time, but there are three dipping sauces, three bottles of water, less than 4 me, which means I can't change it, then I have water full of love song, the return value is 15 plus 3 plus 1 is 19 Yes Then in general, we see that the problem is easy to grasp, right? After that, now we will go to the next part to think about how the algorithm explains me. Well, if your head is like that, we can The idea is that we will have a circulating filter, in which we will perform two main actions in these circulating filters: we will perform two main actions in these circulating filters: we will perform two main actions in these circulating filters: we will drink water and we will exchange water after drinking. When we drink water or wear water, we remember that we must record the values. For example, we must recalculate the values of how many full water bottles are, how many empty water bottles and is how many bottles of water can we drink? Listen to the lesson about the circulation filter telling us when it will end when we have a number of water bottles that are less than the number of water bottles we can exchange in this case. is that Ba must be smaller than the capital A, so it's quite simple. We will proceed with the installation. Yes, this math department will learn this solution. We will use the New Line language to proceed with the installation. For those of you who violate this card, we will start. We will first have a value. We declare the value is due to the Tiger print type to keep. This is the value we will keep. gives us the total number of bottles of water we drank, then we return this value and then we will start declaring more. We already have a topic. This article provides us with two things. The first parameter is the number of full water bottles here and the number of water bottles that can be exchanged. We must declare an additional value that is the live water bottle and call it mt Portal which is also interior style. Okay, so what we declare here, we will call this value, we will do it first, we will do that first step, we will drink water, then here we will call This is the first I drink, you just mean that I have to do the first drink, then when that's enough, first, how many values will we have? how many values will we have? how many values will we have? How many full water bottles do we have then we label ourselves. If we like it, we drink it all when we have sex. Yes, we remember that we have to hold back and pay for this result. It's equal to the amount that our water bottle drank. Yes, after that, we will to start our loop, we will use a for loop and our forest condition is a water tank. Are we going to do when we will continue The filter powder When will we continue the loop Loc , the number of water bottles to support it must be , the number of water bottles to support it must be , the number of water bottles to support it must be greater than or equal to the number of water bottles we can exchange to go out in Vung Tau, but that's not possible, so we will continue to set up. Yes, now, after we We've drank water and the water bottle is empty and the water bottle is full. Now we have to move on to the next steps we do. We have to wade through the water. The next steps are for you to change to which country in Switzerland? If the water floats, how will we pour it? We have to update it. We have to update the values of We have to update the values of We have to update the values of how much the water tank is and how much water it is. Let's see. We will update right away. My sister swallowed the spicy food before me. It's full. Let's create a variable called Lam 3 auto a number. I see. Now, how do I calculate this? We will have to take the current number of water tanks and divide them by the number of water tanks that can be exchanged to get the number of tanks. The current tank water is em pro. We divide it by the number of water bottles. Please note that if we divide by this division, it will be in Co Lan, it only takes the whole part. For example, in the cases of Example 2 Hey, we have 12 water bottles, then we divide 12 by the quantity. This is 4, then 12 is divided by 42. It will come out as Three, right ? In Co Lan, this division will ? In Co Lan, this division will ? In Co Lan, this division will take the integer part. Well, then we are Declare that Nga, you made Tiger when it comes out that we just get the idea after finishing, we can paste 3 into it to make it full, then we will continue with the next step which is we have to update Update the number of waterproof water tanks. Well, you can see that the number of water tanks here will be equal. Given the function of the number of water tanks is 12 divided by 4 to get the remainder, right when we take the integer part? 12/4 of the when we take the integer part? 12/4 of the when we take the integer part? 12/4 of the whole town, the amount of water remaining is 12/4, and taking the remainder, we get the number of jars of 12/4, and taking the remainder, we get the number of jars of 12/4, and taking the remainder, we get the number of jars of this sauce, which is the amount of water that the jar of water comes out with, but we can't exchange it so we can pour the water. level is the same again then we will be in La then we will use the sign just lotus which is this sign percent Okay That's it we have finished changing the water Hello let me finish pouring the water then Let 's continue to drink water. Now when we drink this water, we will update the values like the first time we the values like the first time we the values like the first time we drink this water, we also have to update the price. The treatment is a waste of time. Now, what is the value of the tia-portal? tia-portal? tia-portal? You go to the Bottle, it must definitely be equal to that quantity, but all the water bottles are talented here. Yes, but you remember that right now it is the The MCs gave me this waterproof water bottle. Now it's not the same value as it was in the beginning. In the beginning, when we first created it, we only had two reports and the first time I drank water, it was certain. But for the second time onwards, it's this waterproof water bottle. You see, after you spill the water, there's a chance that you can use this waterproof water bottle again. it will hold some value so we remember that we have to add up. Well, the result of our update will be exactly something like that, we also have to update the variables. The most important thing is how much water we can bring down. Well, it's clear that in this incomparable situation, if you pass me this step, I'll drink it. No, I can't use assignment. Well, here I'll have to use Cong Dung. I see the effect is equal to the number of full water bottles. Ok, so if you take a break from your schedule, it can be done. Our algorithm is That's it. Now I'll try the person who is at fault. Let's test and see here that it runs the example one. You can see that it runs the first one is main and 3. Yes, it asks to shoot out the number of people. Well, if I can output the number 13, then I'm probably right. There was no mistake while calling you haha. Now I try, I'm about to find out. Yes, let it run some more for Tet . Now I see that it can . Now I see that it can . Now I see that it can run all the other testkeys on the clip with DHA and it runs very well with my part being 100 Part 100 percent one hundred percent completed making the game Play Math practice of I had to run faster than all the other competitions Hey there were some other guys who took pictures and shouted but I told you it's relative to me sometimes I find it's not very accurate oh yeah So that's it We have installed that unit. Well, before ending the video here, I talk a little about the complexity of the algorithm here. You see, suppose we call N the number of When the water tank is initially full, we see that the circle is repeating with us. It cannot go larger or go more or go equal to the value n, it can only go a distance less than n. Then it will escape this loop and get the result, in the case where the resolution and complexity do not exceed this listening level we often use, which is rock and I A and Yes, the so-called Open and the complexity of Yes, the so-called Open and the complexity of Yes, the so-called Open and the complexity of the storage space, we can see here we only use, we only declare two more inter values 1ez strawberry or the one to more inter values 1ez strawberry or the one to more inter values 1ez strawberry or the one to store the data. The value of the vase is quick. Then it will make a number row and the number row is strange. We will use the number 1. What is Ho Ngoc Nhu's grand prize? When finishing the problem, solve the problem of the problem. Here, if you feel it is good, please give me a like, share and subscribe. If you have any comments or questions, please leave a comment below and thank you for watching. follow Bye bye yeahyeah yeah
|
Water Bottles
|
total-sales-amount-by-year
|
There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximum** number of water bottles you can drink_.
**Example 1:**
**Input:** numBottles = 9, numExchange = 3
**Output:** 13
**Explanation:** You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.
**Example 2:**
**Input:** numBottles = 15, numExchange = 4
**Output:** 19
**Explanation:** You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.
**Constraints:**
* `1 <= numBottles <= 100`
* `2 <= numExchange <= 100`
| null |
Database
|
Hard
| null |
1,448 |
Hello guys welcome back to take admission in this video also see the direct account notes in three problem questions from record number 108 and desist from the angry topic and they will see the solution using requirement so let's posted the problem statement in this problem given up under root No Taxes In That Is Name Good Friend Apart From Route 2 Must Subscribe To That Nav Let's Look At This Not One What Is The From And Root To This Current 98100 In Sequence Brother Who Frill Cut This Question Is Not The Three Letters From This Is Not Withdrawn It's Not Know What Is The Tarzan Then Subscribe The Video Then Subscribe To The Page That 1460 Trading Sequence That Is Not From Route To Current Mode Switch Greater Undercurrent Note 6 Patience 148 Loop Subscribe To Route 238 Gives Node To Greater Noida And Greater Than 600 800 Se 900 Good Night Elsewhere Not Forget Not 614 988 Iodine Vs Was Not A Good Night Tata Good Night Sir 123 456 Good Night Subscribe Saudi Se Bihar A Piya Solve The Problem Na Ok No Problem You Must Avoid Giving It's Just Want To See The From the route from this 66 will not be no problem Maximum Kar Do Pims Whenever I Do Not Wish To Start From The Route Of Birth From This Nautanki Climbing Of Intent Emergency And The Maximum Stop This Point Compare With Which Cannot Be Disposed As They Move In The Letter This Is The Rupa Always Being Only Not Great Indian Middle Download Website Baikunth Civil Defense Andar Leaf How To Check Iss Good-Good I Will Not Only Be Good-Good I Will Not Only Be Good-Good I Will Not Only Be Greater Than Or Equal To The Notes From Silicon Is Subscribe Must Will Not Wrong Doing What We Can Do It Maximum From Root to the Maximum Volume Maximum This Will Not Be Able to Compete with All Notes in Just 120 Days Half Greater Than Equal to Cigarettes Daily and in the Morning And Think They Should Stop Comparing with Values and a Stop Comparing with Values and a Stop Comparing with Values and a Maximum After mercy doo chief of the Chinese 2012 Maintain the maximum of all the states to find the cone is gold Subscribe to the channel Start with Me to the Maximum Very-Very-Very-Very - Infinity and Video Subscribe to Maximum Volume Maximum Do Maximum When Previously Unknown Maximum Problem of But I Don't See the Will with Whip Will Compete with Maximum and subscribe the Video then subscribe to the Will Be Updated to a maximum of already in that person subscribe and subscribe the Channel Vriddha Din They Can Find The Number Of Vinod Din Joint Video then subscribe to the Page if you liked The Video then subscribe to the Ki Vinod How to find good care of account receiver This question is how many states are there in the mystery Solve this can be answered No one will account for this channel Subscribe our channel Subscribe thank you All the best notes Notes in laptop plus the number of Good morning decide f3 plus one is the current notice definitely 9 a Video plz like this Video plz subscribe this Video not 9999999999999999999999 Idhar General Case Dargah General Kaise Is Number of Good Notes Routine Dheriya Recipe Share and Subscribe Screen Do not a good night subscribe must the automatic in what is max value the exclusive - Infinity Spirit and Lips exclusive - Infinity Spirit and Lips exclusive - Infinity Spirit and Lips Ki Tak Counter So They Will Keep Account An Account 2000 3499 Will Be Making Left From Channel Subscribe To Posters Post-Processing Process In Latest Current subscribe to the Page if you liked The Video then subscribe to the Page if you Yudh Max Value Cigarette Also Recite Least One Note Special Greater In Roots Current Note 500 This is not good night ok no latest subscribe to the Page if you liked The Video then subscribe to the Page Kuch Der Is Nod In The Road To Front Part Which Greater Than Distant In Solid Pure Account Value Will Give They Are Not Able To Make Birthday Know It Will Not Be Able To Get To Know What You Will Not Be Able To 100 Number Notes From 200 To 300 Novels Written With Subscribe The Channel 90 Subscribe Button 1234 Problem Doosri Will Make A doll so let's make great soul will make a call to the 400 time spent and control 2009 from its first person 4000 999999999 person great andheri east 999 9999 off account it is equal to zero from left zero from right and current notice also not good 9000 ok so let's check the color returns from this point to 9 0 share0 tweet0 0 4 9 from route to subscribe channel now to the calling function which did not call from 8102 discount of good quality 048 college one and no david Jacobs 12th Over 128 Bits To Do The Best Job Listing One From Left To Right The Number Of The Number Notes From Left Side Subscribe Button - - - Subscribe Button - - - Subscribe Button - - - 31-12-12 OnePlus One Subscribe Remedy Tera Four Good Night So This Is The Writer Off The Center Logic And Vivid Colors Subscribe To Channel And Will Give You Will See Root Accidental 999999999999999999999 Chapter Adding A To The Counter Guddu's Member Function Will Return Account Good Night So Let's Tree Witch Will Return Tata Good By The Right Sabari Brothers And Passing Root Left in the first and right in the second tomorrow doctor getting here veer kunwar singh dhindsa total number of every year will not enter 999999999 they will update you all the note 5 devils vote current not ignore this will update Content Notice Edison Not Well Wishes So And Avoid Doing Things Will Give Me The Number Of The Year With Free Water Traversal Preorder subscribe for you liked The Video then subscribe to the Page if you liked The Video then possible like share more videos and subscribe to our Channel In Order To Achieve This Program In Videos 0 Zinda Next Video Thank You
|
Count Good Nodes in Binary Tree
|
maximum-69-number
|
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X.
Return the number of **good** nodes in the binary tree.
**Example 1:**
**Input:** root = \[3,1,4,3,null,1,5\]
**Output:** 4
**Explanation:** Nodes in blue are **good**.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
**Example 2:**
**Input:** root = \[3,3,null,4,2\]
**Output:** 3
**Explanation:** Node 2 -> (3, 3, 2) is not good, because "3 " is higher than it.
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Explanation:** Root is considered as **good**.
**Constraints:**
* The number of nodes in the binary tree is in the range `[1, 10^5]`.
* Each node's value is between `[-10^4, 10^4]`.
|
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
|
Math,Greedy
|
Easy
| null |
1,696 |
hey everybody this is larry this is day nine of the july league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's bomb jump game six okay yeah i hope everyone's having a beginning a good beginning of the weekend hopefully all right the two contests tomorrow is for me is tomorrow but you know two contests on the weekend for leapco so hope y'all enjoy it hope y'all do well and all this good stuff anyway let's get started on today's problem okay so you're given neutral weight numbs and you're starting at zero in one move you could jump k4 without going outside the boundary okay yeah okay so you could jump k step forward okay you want to reach the last index n minus one your score is the sum of all num sub j for each okay so okay um i mean this is going to be dynamic programming so actually i think this is a good example that i want to demonstrate a little bit um because i think not gonna lie when i was younger i think i struggled with this problem a bit or not this specific problem um because this one is very basic in the way that they represent it but more that they um you know they disguise in some ways and i'm thinking about the naive dynamic programming i'm unable to make that additional optimization but this one it should be okay so the key part and i'm going to write this out with first enough before sorry but the more naive dynamic programming and then we will kind of talk about it right and then kind of make the optimization um of course i think for today this is friday so i'm going to make an assumption that people are familiar with dynamic programming we've done you know four or five problems if you do struggle with today's and especially with this explanation maybe go back the last couple of days and um yeah maybe go wait why is it zero the maximum score is that actually just zero or hm that's sweet is that actually right so from two to four to seven wait would i miss that okay so maybe this is negative four this is zero three okay so maybe it is just zero okay um yeah okay so maybe i'm gonna i'm just gonna write the naive solution okay now let me we say it one more time so i was just checking the farm to make sure i didn't miss anything dumb and have to redo it uh long-term viewers have to redo it uh long-term viewers have to redo it uh long-term viewers know that i sometimes do that from time to time okay so yeah so for these kind of problems uh you know like i said if you do struggle with dynamic programming work on the past week my videos are here uh so check that out and then maybe come back to this but for now i'm going to assume that we know and the way that we write the naive quote naive dynamic programming is like this right so we have a like a dp array from and here we have the max score and we want it to be negative infinity because they're negative numbers so it can get very bad so okay so infinity is equal to 10 to the 20 is what i like to do because this is bigger than long as y because i made that mistake before uh so it's this times say n plus one um yeah and n is equal to length of nums right and then dp of zero is equal to zero because we're starting from zero um and then now here dp of i is equal to and this is just notation sorry maybe i mean it's equal to the best score coming from zero actually maybe i don't need it because you start at zero so actually maybe i want this to be the case okay right oops coming zero and ending at index i right so that's basically the idea and then here the naive way you would do is for me for i is you gonna range from one to n uh non-inclusive because you know just uh non-inclusive because you know just uh non-inclusive because you know just the indexes and now for j is in range of say from one to k uh plus one inclusively let me actually make sure so k what does k ace k step forward right okay yeah i plus k so yeah and then here you want to say that dp of i is equal to the min of dp of i uh dp of i minus j we probably need to add a if statement um yeah that's the best spot there plus the current number right um is this right uh yeah that's one spec it's one step backward and then two and all the way to k step backward so that's gonna be our answer i'm gonna print out the dp and then we're gonna return the last uh cell because that's what it's asking for right what's the max score you can get to oh i won't mean for some reason uh the max uh and here that's right max right and this should be okay though maybe too slow right yeah so this is okay and i just pointed out for reference um so that's the basic idea and i think this is basically what you might think about right in that you know if you don't understand this i do recommend practicing dynamic programming i think this one is a very standard or i don't know if it's standard maybe i won't use that word but here's something that you will get or expected to know in an interview so like it is almost like prerequisite so if you don't get this you probably need to uh hung up on that skill to get it right at least this solution and basically the solution is just and i'm gonna bring out my um my paint real quick uh let me draw some stuff on the screen for y'all but basically this is almost like one of those things where you know you have a lot of cells right oops man this drawing stuff is hard that's not even straight lines all right let me just run a box here like this right make sure that it shows up on screen okay so let's say you have all these indexes right and you have something like you know um and then the idea is that okay for here you know you're looking at it uh backwards for this cell you know that the last place that you can jump from is here and here the last first thing you draw from is here and then here right and then here let's say k is equal to three right then here you can look at you know one two three where it's the last stride here it could be one two three as the last spot and so forth right dot so that's basically the idea here is the dynamic programming right i mean i know that i wrote it maybe a little bit quickly but the idea is now that we look at okay if i minus j is the last spot what is you know let's get the best score that is at that spot plus the score of landing it here right okay and then now the question is there another way to phrase it right well looking at this function what do we see right uh rewriting this very quickly let me put that with stuff first looking at this very quickly we now notice that we're basically and as i'm doing a simple quantum one oh this is kind of i want to say this is maybe a little bit tricky for a medium one but maybe not maybe i did it in a silly way hmm no i'm okay but yeah maybe there's an easier way but i want to explain the technique anyway but yeah looking at this formula right what do we notice well let me actually write it out on the pane again because i think that's more uh better right so we basically have this idea that um we have some f of i is g code 2 some f of i minus j for j is you know uh well this is plus some a sub uh a sub i minus j for uh how do i say four whatever i'm just gonna make the word four i forget what cherry the apple goes i always forget for j is in uh one dot all the way to k right so that's basically the idea and then once you see this formula the thing to do is noticing that oh sorry i made i'm messed up here hang on this may make it confusing this is not i minus j this is a of i right okay now this is more clear maybe hopefully right so now let's say we have this formula right and we want to optimize it or think about rewriting it another way well what can you do right basically you want to mend this function is basically the idea well actually sorry max this function because i don't know i keep saying min but so you have this function and you want to max this function over 1 minus k right or 1 to k and then the idea here is that well this number this term does not change so basically you want to rewrite it to max from one dot k this is a j um f of i minus j plus a sub i right okay i hope that this probably makes sense right so hopefully this point makes sense and i'm gonna write it rewrite this really quickly right so what do i mean by that i mean that here you know like i said i'm doing this for teaching purposes so definitely i would have done it a little bit better in my head but let's say i is equal to negative infinity which you know what it does let's say the current uh best is to go to negative infinity maybe i don't need this quite yet um but and then here you may say you may rewrite this as best is equal to min or sorry i keep saying min uh dpi minus j plus num sub i right and then at the end dp i is equal to best right so that's another way of writing it perfectly okay should be the same thing let me just want it real quick because i have a typo right yeah so it looks good and then what i was going to say is that okay now you realize that you take out this term because it's going to be the same on over the entire range so then let's get it out and then put it here right okay and then now essentially what are you doing what you're doing now is getting the max of the last k um numbers that's basically what we're doing and so how do we optimize this right and the way to optimize this now is just by using something a little bit a little bit trickier but still doable the idea here is now you know um well the idea is going to be sliding windows i'll just say that part out loud um and you can kind of visualize why that is right because now and okay i'm gonna go back to drawing i keep on putting the drawing away but maybe i want it back um because now instead of let's say this thing that we have on top what we have instead is let me erase this let me raise this um so now instead of this thing well let's say you're looking at this cell right what happens well you want to take the men of here oh sorry the max i said keep on saying min but you get the idea you're smart at home you know what i mean uh and then now let's say we're looking at the next cell afterwards right what happens how did that happen i guess i am trying to figure out what happened oops right and then here let's say this hour moved to the right so now you have to here what happens well this range that we're looking at also shifts to the right same thing here shifts to the right um so i think now there is you know like very naively i mean hopefully that visualization makes sense with the sliding window and of course there are some uh some let's say there's some like logins example some solutions but we're going to be going over um uh an of n solution instead or not all one solution for an update instead right um how do i do this and i don't have it i have the idea but we'll prove it together and we'll figure out together but i think the idea is just yeah and this is by itself going to be another medium problem so definitely it's possible there but um yeah okay so now as you can see so why do we want to optimize let me go over that really quickly as well because what is the complexity here right well this is going to be n this is going to be k we look at the constraints n is equal to 10 to the fifth k is 10 to the fifth so this is going to be 10 to the 10 and that is no bueno i mean maybe i know that you can actually that's not a tight bound you could do better or on average you'll be much better a bit but you know that's still going to be even if it's 10 to the nine it is going to be too slow right so that's why if we are able to we look at this formula uh and i say formula in terms of code and we'll be able to get this to o of one then now you have well o of n if we're able to optimize this two over log n then we're gonna have n log n right so um yeah so that's what we're going to do so you can also by the way you can use a heap to keep track of the max and that will give you a login algorithm for example maybe sorted list if you don't want to use a heap but that's one way to do it and then you know you're sliding window in and you're sliding window out so that's going to give you an n log n solution i'm not going to go over that one but that'll probably be fast enough i imagine so um but what i am going to do is talk about a linear solution or a constant solution for the thing inside and then o of n all together um let me think about how i want to do so the answer is going to be using a queue the idea and this is way this is going to be the general idea for sliding windows right because basically uh you start with a queue and here we use the deck because when we move to front and top but now um yeah and we want to look at the last case so if length of q is greater than zero we do oh sorry greater than k oops we pop left and of course you get you would only ever populate one number so it's fine okay what happens right what do we want to do basically we want to get the max of um the thing right so let's say we're so the new number that we're adding is going to be uh the new number we're adding will be dp of i minus one because that's the new one um actually maybe we don't need to do that here maybe we'll do that after processing the best so then now it makes more intuitive sense maybe yeah okay and then maybe in this case then we can keep doing variant here instead after we push the new number um okay and then so then here then variant would be that q has k elements or less than right uh at most say okay cool so then now we just have to update it with best and the way that we're going to do it and let me kind of work out some math i don't this part i have to prove i always have to prove a little bit in my head right so let's say we have uh and this these are on the dp values by the way not on the sequence but let's just say we have a random sequence that looks like this and we want to get the max of the last say three numbers so then first uh yeah it's gonna be a mono cube i don't remember which way i never remember which way i just prove it to myself every time but the idea is that okay so each element will have two items right one is the max inside and then one is the current number and then so okay in this case i would build um a 10 right and then the next would be a negative five and the question here for these kind of mono problems is kind of asking myself okay given that the current max is 10 can this negative five be a max and the answer is yes when the 10 gets leafed out right so then here we will write down negative 5 right oh maybe i don't need maybe i'm making it's too complicated because i think there is oh i think there is a one version where you always pop and i think we need to keep that version is why okay yeah i think that makes sense uh it's just that right now it's same logic for negative two but then now let's say we have a four right and i think the q version is yeah i mean i think we need to change this a little bit but um but i think we're fine yeah okay we need to uh remove an element from i minus k right so yeah so maybe the pop left was wrong um yeah okay then in that case we don't need this double q thing or double letter q is just you know negative five right and then negative two and then what happens when you see a four right uh i guess this doesn't need to be tuple um when we see a four we go okay can four be the biggest number well yes but within this range negative 2 can never be a possible biggest number anymore right so we remove it negative 5 could never be a possible num biggest number anymore so we remove it and then now we have 10 and 4. and then now we have a zero what does that look like that looks good because zero can be the possible biggest number if these two numbers go away right and then the same thing with three when we insert the three we go okay zero can no longer ever be the possible max number so we will move it okay and then now the max number will be the number in the beginning so okay so then now what we have to do is replace best is equal to q dot uh not pop left just keep that zero if length of q is greater than zero right so you don't do it for the first element for example um oh we always will have at least one element because we start at one here i was just trying to think about the case where we start at um oh it's a pandemic uh then we start at the zero element but yeah okay so then this will always have zero at least one element so then this is good and then now we can do this and then now we have afterwards we have to process um also if you got confused what i did here i do have a tutorial on mono cues and how i derived this so definitely check out that video um remind me in the link below if i don't have it below but yeah so then now basically it's going to be monotonically decreasing q so then here yeah we add this and then now we go now we're trying to insert right well um this loop is also wrong but uh yeah so while um q dot we have the last element let's do while link is greater than zero and the last element is if the last element is smaller than this element then we got pop right because we want to pop it from the right and then we add it okay and if it's equal we don't want to pop it because we want to keep two instances of it for us for one reason and then now we go okay if i is greater than equal to the k then we want to look at the element on num sub i minus k and then we want to try to remove this element from the queue if it is the biggest element right so if q of zero let's say with is equal to element then we do a q dot pop left and that should be good i lied because we forgot to insert the number but mostly good right um and i think this should be okay let's give it a spin i guess i should just run it before saying that because it might not oh it's just pop that pop right some of the name naming inconsistency is a little bit awkward yeah so that looks good now and yeah and this is gonna be linear time so let's give it a spin i might have a typo who knows but oh no i have a typo or do i mess it up maybe i messed it up uh hmm that's sad might have been off by one basically it's a hundred go to minus one a hundred right so why am i getting this wrong also you may notice that we actually don't need to keep track of stuff anymore oh this is dp whoops okay i because we don't want to remove the number we or we don't want to remove the input number we want to remove the last thing that we inserted k elements ago which is this thing so we do need it okay let's try it again with the submit a little bit silly on off by ones i think if i did it with a sorted list or something like that um you know this would be no that this is a silly mistake i could make this mistake and sort of list anyway so yeah so that's basically the idea is dp with a mono queue and of course this is going to be linear time why is this linear time even though there's two for loops right well this loop is going to be in linear number of iterations you know makes sense and the queue each element can only be added to the queue and we move to the queue once so even though this is a while loop this will only execute over one time per element at most because otherwise it just doesn't do anything um i guess i could have just added this as a part n but anyway um so yeah so that's going to be linear time in general and then for space this is going to be linear space for the for both the dp and the q um this is a i consider this kind of a very hard one especially if you do it in a linear time and linear space and again it's slightly easier but still kind of tricky because this um this idea actually comes into play a little bit on the harder dynamic programming ones um and if you don't remember to make this optimization it is kind of tricky um to see it the first time and of course i just have a typo open which is fine maybe i could have tested more now you sorted this last time i acquired you sort of this last time right yep oh larry you started this and this time i removed the right one uh did i do it the first time as well yeah okay so yeah if you want to see the n log n solution check out the past but today i think i don't know what i figured but today i wanted to do the linear time one so hopefully that makes sense hopefully this is good um some parts of the explanation is a little incomplete the two things i would look up or just practice is dynamic programming which is all this week and then i have a video on monocube what did i call it uh let me just find a link really quickly or like just have it up on the screen uh but yeah oh it's what it's in the classic uh so it's in my you know my channel thing list it's called the larry explains mono cube part one and part two go check those out and then let me know what you think um that yeah that's pretty much all i have now though so have a great weekend if you do contest good luck um i'll see you later stay good stay healthy to good mental health take care have a great weekend bye
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
725 |
Ram Bhai Sir, today is 6th September and today 's question is 7:25. Split link list 's question is 7:25. Split link list 's question is 7:25. Split link list in part question is that you have to give a link and how many parts have to be divided into parts which you have given us. And how to divide if our length is complete and has been divided but still we need parts of one more then we can make them tap and what is given and keep it that whoever is coming first should come first. If the parts are not divided into equal parts, then the size of one part will have to be increased. In that condition, if you increase the size of the starting part, then let us move on to the example and it will be clear, but before that, if you subscribe. Do it without going or watch the video. If you are going without Puri then if you do not watch the full video then you may face losses because this question has been asked twice in Amazon and again in Apple and many more statuses can be asked. Therefore, if you do not have such a face, then watch the entire video, subscribe and like, so let's go, the example is 123, we have to divide it into five parts, so I will say 3/5, then three 3/5, then three 3/5, then three yes and no will come, basically three parts. So you will become one, you are done and you have become 3 but if the remaining two parts are cancelled, then we have been told in the question that if we have to return null, then the remaining two have been done in no. Very good second example, three done, how many equal parts in total? Can So what will be the three parts? 1 2 3 will become 1. Second will become four five six. Third will become 789 and 10 will A alone or will it be joined with it in the last. No. The question has said that if there can be difference of length. What do you say, there may be a difference of one, it is possible, but what you have to do, whatever length is bigger, it should be in the starting, then 10 I am right here, otherwise the order will be broken, so say this. If it should be in the order, then basically I will have to remove all this and do 123. I will also have to take the module of this time along with it, then it will be one, that is, how to do that, how is it, because if you understand it better in this, then the total will be. The length is 10, so first of all, I showed you in the hit that if you divide the total length, then we will get how many parts are there, if we get the number of parts, then what will be the number of parts, then to check extra, I What will I do extra, it will be equal, you will put 10 both in one, no, we have seen that there can be a difference in the size of the same, we have read this in the question, so then let's how to do it, so first of all, how many parts have I made to make the parts? I am going to make a blank, do one, two, three, first of all, I will put a check, first of all, I will put only one tractor, so first of all, I will have the result, I will have one current and one result, then what will I ask on the result, then look at this, hey. It is not that you push 123 complete or 456, this is a link list, so in this you do not have to keep in mind what you are pushing, for that you should not know that if you give the head of the link list, then the rest. Link with A is caste because these are pointers which were of point, so what do we have to do to the next element, basically whenever we want the element, like mother, first I have to point to the national of two elements one and tu, okay If we have to do this thing then we will give the current variable name and we will also want a previous variable which will be null in the starting. Okay and then we will make the previous equal to the current and move the current. Then when we move ahead, we will do the same first. So first of all one push is done, Result is equal, what is the current, then the current is pushed forward, the previous one is fine here, which will last till K, in this all four will fail one by one and inside that, a loop will run, in this there will be a current painter and this will be the previous point. For how long will it last? How long will it last in total? Basically, every time I have to do these flowers one by one, so basically how many times am I moving my current to file it. If I want to know, then I will make the current move which. There will be a counter of mine and it will move, basically how many parts are there and I will check that I have extra parts, if it is more than one then I will give one part here, if not more than one then I will give it zero, so this is our condition. If it goes well then basically what will happen is that first we pushed and then we are moving the current on you, we have extra parts from the extra part, so you are plus one three, you are plus you are four, meaning if there is an extra part then what will be the length. So here, when it comes to free, we will exit from the loop, so what do we have to do, no previous, you will not do it now, current came, then did the previous here, then took the current forward, now what do you have to do when you are in this condition. If yes, then see that the current here will come to the point behind the previous one, then tap the next point of the previous one and then do the dog. So this one is from the painter, that means it passes one. 123 is stored here, now what do we have to do next? Next we will do the current here. But if there is then four is pushed. In the next situation, the current is pushed in a second, four comes, then we will see and here you will also mine these extra parts, reduce the size, otherwise extra parts will be made. Come on, and here because zero is zero. If it is greater than zero, then for how long will the current move? I will make the current move. If the part is two, then you will move plus one because one will pass. If it is greater than zero, then the total will move three times. Then the name of the previous one is current. Next increased and at this point we did not do the next of the previous and like girls i.e. here we have 456 store, we i.e. here we have 456 store, we i.e. here we have 456 store, we will move ahead and then finally in the last there is river so this was basically the whole question had to be found so if its time If we talk about the complexity then how much will it be, first we have to write the code and then let's see how much will be, so first of all I said, brother, what will I do, tell me here, I saw that if I have to take out lunch, then first of all I need current. Which will point to the head, very good, what do we have to return a vector named result and first of all we will add the current value in the result, very good and now what we need is what will be the length, then the total length. How will I account for the current which is ours till it becomes tap i.e. the current is ours till it becomes tap i.e. the current is ours till it becomes tap i.e. the current is exiting then I can add plus to the length and move the current to the next side of the current then this will give me the length. Friend, someone may ask you. Tell me the length of the link list. If you write this much dog, you will get the length. So here you have got the length. Now what to do is to move the current back and make it late tomorrow. Now I have taken out the late. How many parts are the parts? Our length will be divided by K and how much will our extra parts be, extra notes will be our length modal ok example very good so there counter then we will push one, otherwise zero we will do something, this will be our condition and then make the account plus now inside What will happen, sir, you have not created that, here we have to create the previous also, so the list and this is also equal to the starting one and then we are moving the current to the next of the current, when this condition ends, that is, we have filled a complete segment. What I had to do after that, I had to tap the next button of the previous one so that it can be destroyed and this link list will also have to be reduced because brother, we can read your code only then what we say will make it previous. Will it be nationalized otherwise it will be created automatically because it is equal to the previous current, extra notes have been reduced and then finally what do we have to return, we will return the result, why is it so here is the runtime. A is there because we have not put the bracket here, so what is happening every time is that if there are extra notes in the parts, A is always greater than zero, then only zero is passing, so it will be messed up, so this condition is in the bracket. Do this and we are writing the code like this is our growth, so it is good, you can also write it separately, do this, but like this, submit, and then let's see what is the time complexity, Priya, this has been submitted, very good. So now if we take out the time complexity of it, then what is happening to us is that this is the first loop, it will run, then what is happening along with it, we are putting the loop here again, so n² will not be there because we have only one mode for each mode. We are visiting either K in place of M or N in place of it. Here it will be K plus M because we are visiting A again or you can make it K + M / K or you can make it K + M / K or you can make it K + M / K * K * Sum. If * K * Sum. If you take variable So watching the match please share with your friends subscribe you like it very much like comment and till then bye in the rest of the video Suraj Ki Roshan
|
Split Linked List in Parts
|
split-linked-list-in-parts
|
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50`
|
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
|
Linked List
|
Medium
|
61,328
|
51 |
hey everyone it's Chaz welcome back to the channel hope you're ready for another coding challenge because in this video we will be looking at leite code problem 51 n Queens this is actually going to be the first hard problem that we do on the channel but honestly this problem it's not hard because of the algorithm that we're going to implement it's listed as hard because it turns out there are a lot of steps involved in solving this particular problem so the Queen's problem is a classic computer science puzzle that's why I wanted to show it on the channel the difficulty arises more in the fact that we're talking about Queens in chess and so you have to know how to implement some of the rules of Chess in order to solve this problem and I think that's where the difficulty lies but I'm going to do my best to explain this and show it to you visually show you how the algorithm works and hopefully you'll be able to follow and you'll be able to solve a elite code hard problem with me today let's look at the problem the N Queens puzzle is the problem of placing n Queens on an N byn Chess board such that no two queens attack each other just to break out of the algebra here what they're saying let's say that n is 8 so that means we have an 8 by8 chess board just a standard regular chess board and they want you to place eight Queens on the board in a way so that none of those Queens can attack each other or if it were say Nal 4 then you want to have a 4x4 chess board and set up Four Queens so that none of those Queens can attack each other and then it says given n integer n return all distinct solutions to the N Queen's puzzle and you may return the answer in any order what will happen is for some of these chessboard sizes there's going to be more than one solution we are being asked to provide all of the solutions not just one of them and then finally at the end it says each solution contains a distinct board configuration of the N Queen's placement where Q and The Dot or the period both indicate a queen and an empty space so to show you an example I'm going to look at the image here for example one so this is the case where n equals four so we have a 4x4 chessboard and we're placing Four Queens as it turns out there are two distinct Solutions and they're asking us to return this solution in the form of a list of strings where represent a queen as the letter q and an empty space as a DOT or a period if you look at this list of strings here if I lay it out vertically instead of horizontally the way it is here you could see that the layout is exactly the same as what you see in the picture there are cues in my list wherever there's a picture of a queen and there's a DOT everywhere that you see an empty space and because there could potentially be multiple Solutions it won't be enough to just return this list of strings we actually need to return the other list of strings also so it's like you have to have a master list that contains each list of strings so it's not just a list of strings it's a list of strings so we'll have to come up with a way of submitting multiple solutions to the end Queen's problem before we return the master list and then finally at the bottom of the problem they provide the constraints which are pretty straightforward the n in the N Queen's puzzle will be anywhere between and N including those values so we need to come up with a solution that will work for one Queen on a one by one board just a single Square basically and also nine Queens on a 9x9 chess board and also all of the whole numbers in between so we are going to solve this problem using recursion and we're going to use it with backtracking now I'm not going to go into huge detail about what recursion is because I've actually already made a video about it and in this video I explain recursion and show you a few different practice problems that I go through visually and with code so if you're still a little shaky on recursion please watch that video first because I think it'll do a good job of explaining recursion for you in a way that it will help you understand how to now add backtracking to it but basically in that video I say that recursion is the use of a function that is defined in smaller simpler versions of itself or in other words if you're coding with recursion you are using a function that calls itself inside of the function okay so we perform our recursion so what about the backtracking is going to be a technique that uses recursion to build up a solution one piece or One path at a time one common way to think about backtracking would be say you had a robot that was trying to move through a maze what you can do is you can just try a path and if it turns out that you reach a dead end just go back one step and try a different path try the next available path and if that doesn't work you just keep working backwards until you can successfully find a path and eventually your robot will reach its destination so like in the case of this n Queens problem we are going to build up a solution that starts with one Queen we're going to then add another queen to our solution and whenever we can successfully add a Queen we'll just move ahead to adding the next Queen but we might find a situation or a path where placing the next Queen is not possible so if a certain path does not solve the problem the algorithm abandons that path it backtracks and tries a different path and so every time we successfully place a queen we can move forward every time we find that it is impossible to place a queen we go back one step and we do this until we can find a way to place all of the Queens on the chess board and at that point we have a valid solution and we can submit it as part of our Master list so in order to solve this problem you have to know how Queens attack in chess and I think this is where most of the difficulty comes from in this problem in terms of like a two-dimensional array Queens are two-dimensional array Queens are two-dimensional array Queens are attacking each other or attacking any piece in chess if that Queen is on the same column as the other piece or if the two queens are on the same row then they are attacking each other and also if they are on the same diagonal and in fact it doesn't only have to be the center diagonal it can be this diagonal and it doesn't have to be going from left to right either this diagonal also would be considered attacking so the difficulty in this problem is less so the recursion and More in implementing the rules of Chess right before we work on the code for this solution I'm just going to show you what the recursive algorithm looks like along with the backtracking so I have a partial chess board here 4x4 I know that in Java we use zero indexed arrays but for the sake of Simplicity I'm actually just going to call this Row one row two Row three and row four and then for the columns I'm also just going to say column 1 column two column three and column four when we actually code some jav we'll go back to using a zero index or so the way our algorithm is going to work it's going to start in row one and then in row one we're going to try to place a queen in column one now anytime we successfully place a queen in a row what I mean by that is anytime we place a queen in a square where it is not being attacked by any other queens that will allow us to move on to the next row now there's only one Queen on the board right now so obviously it's in a safe Square so we will move to the next row and in that row we will attempt to place a queen in the First Column obviously this isn't going to work it's being attacked by the queen right above it so we will just iterate to the next column we won't backtrack yet we'll just go try the next column we move to the next column it's actually still being attacked so we try the next column and this is a safe Square so that will allow us to move on to the next row so we try to place a queen in Row three in the First Column it's being attacked move to the second column it's still being attacked third column still attacked fourth column still attacked and we have actually run out of columns whenever we run out of columns this is where we will backtrack to the previous row and try this queen in the next column so we will just move this queen over this is actually another safe Square for that Queen so we will move on to the next row try to place a queen here again it is being attacked we go to this square and this square is actually safe so now we can move to the fourth and final row we place a queen in the First Column it's being attacked here it is also not safe it's not safe here either and it's also not safe here so we have run out of columns so we need to backtrack we go back to row three and move this queen well that's not a safe square and that's not a safe Square so we have run out of columns again so we need to backtrack again so we backtracked this queen but this queen doesn't have any squares left so we need to backtrack again to the first call and move this queen over by one column now since this is the only Queen on the board right now it's automatically safe so we can move on to the next row we'll place a queen in row two that square is not safe but this square is fine so we'll move on to the next row place a queen in the First Column and actually the first column is safe so we can move on to row four that square is not safe that one's not safe but this one is safe so we have actually completed the board at this point so now what'll happen is we will establish a base case where if we successfully fill all four rows then we will submit this as a solution to the problem we'll add this to the list of solutions essentially now we know from the example that for a 4x4 board there's actually two solutions so we've only found one of them our algorithm is actually not going to stop here all it's going to do is submit this list as a solution but it's actually going to keep going so essentially what it's doing is it goes to a fifth recursive call almost like it's trying to go to row five but it's really not going to row five when it passes row four it realizes that we have a solution so it generates a board for that solution and then when that call returns it goes back to the fourth call so that means we're right back in the fourth row and this queen is actually going to move to the next column it turns out this column is unsafe so we'll run out of columns in this row so we'll end up backtracking this queen actually will not have any safe squares so we'll have to backtrack again this queen has run out of columns so we'll backtrack again we're back in the first row we'll move this queen over that Queen is safe so we can move on to row two that's a safe Square so we'll move on to row three not safe but that square works just fine move on to row four that square is not safe but this square is safe we actually just found another solution we will submit this as a solution so we'll add this to the list of solutions we now have two on our list which is what we were expecting so at this point we've actually solved the problem but our algorithm does not know that it's actually just going to keep going so let's just see what happens so when it returns from submitting our solution it will actually go ahead and move this queen again that's not a safe square and that's not a safe Square so we run out of columns so we backtrack this queen also runs out of columns when it tries to move over so we backtrack again and then none of these squares are safe so we backtrack again and then this queen moves to the fourth and final column in row one that square is safe so we'll add a queen that square is safe so we'll add another queen and then this queen is not safe until it reaches this square and then we go to the fourth row and then none of these squares are safe so we run out of columns so let's backtrack that square is not safe we run out of columns again we backtrack again that square is safe for this queen move on to row three and then none of these squares are going to be safe so we run out of columns backtrack that square is not safe we run out of columns backtrack to the first row and this queen has run out of columns so in this case our very first call is now complete and so we can submit our solution which contains a list of two valid jports what did I say Jess chess boards so because this problem is so complicated we've already taken a lot of time to explain the algorithm itself with no code I'm actually just going to stop the video here we're going to break this up into two parts and in part two we will finally code this algorithm using Java so that'll be it for part one for this video thank you very much for watching and I'll see you next time
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
1,437 |
Hello Hi Everyone Welcome To My Channel Let's Check All The Problem Is All 108 List Length Of Places Where They Sleep Very Straightforward Problem And Easy If You Have Done From Problems With Solid And Liquid 10K Through All Subscribe For This Problem Is Given To Subscribe And the distance between the subscribe our Channel को subscribe कारे Channel को subscribe कारे Channel को subscribe कारे पायर सावन एनिमेट्से डिस्पॉनेट निकल पायर सावन एनिमेट्से डिस्पॉनेट निकल पायर सावन एनिमेट्से डिस्पॉनेट निकल बिट्टू आर इडली The distance between Remedy K will keep doing r बिट्टू आर इडली The distance between Remedy K will keep doing r बिट्टू आर इडली The distance between Remedy K will keep doing r not satisfied with us will solve they will reduce the numbers are elements in the last one year distance between Greater Noida Subscribe and Like Share and Subscribe Star Plus One Which App That Is This A And B Were Defined As One Will Send You A Great Karenge Is Vipin And After That Will Adhere To This Conic Ki Movie 2018 20123 404 - The Difference Between And Minus 20123 404 - The Difference Between And Minus 20123 404 - The Difference Between And Minus Subscribe to Vice President of One Solid - 200 and Solid - 200 and Solid - 200 and Quarter That We Keep Moving Cars in Television and the Deathly Blouse Painting of Switch Off R15 V1 Minus One is the Return of Birth Foundation New subscribe this Video not Returning from the Giver and Subscribe to 137 Walking find which can submit this that and not accept what is the time complexity of vacancies in treating all the number one subscribe button subscribe my channel like this maximum and minimum distance between the person setting on the road to the problem is
|
Check If All 1's Are at Least Length K Places Away
|
minimum-insertion-steps-to-make-a-string-palindrome
|
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example 2:**
**Input:** nums = \[1,0,0,1,0,1\], k = 2
**Output:** false
**Explanation:** The second 1 and third 1 are only one apart from each other.
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= k <= nums.length`
* `nums[i]` is `0` or `1`
|
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
|
String,Dynamic Programming
|
Hard
|
1356
|
148 |
video we're going to look at a legal problem called sort list so given the head note of linked list we want to be able to sort this list in ace and the order so the goal for this question is we want to be able to do this uh complete this problem in n log in time complexity and its base complexity is constant right so in this case we know that the two sortie algorithm um is either merger sort or quick sort can be able to achieve and log in time complexity there's also a heap sort but the thing is eavesworth we will need to require a heap right which basically adding all the elements onto the heap and then be able to sort them in this case it will give us a space complexity of linear so what we can do instead is we can be able to use something like merge sort or quicksort but the thing about quicksort is that um in this case quicksort we need to find the partition index right in this case the partition index in the linked list the only way we can choose is basically the first node right the first head node so that might not be sufficient if we have a situation where the list is already sorted so in this case a worst case scenario if we use quick sort it will give us a time complexity of n square so the very common solution to solve this problem is to use merge sword you can still use quick sort but it's not as sufficient right efficient uh as merge sword so for merge sword um the time complexity is going to be in log in but space complexity is basically big o of h where h is basically the height of the recursion stack right um or basically you can also say as big o of login right to solve this problem using merge sort basically what we're going to do is we're going to basically using divide and conquer so what we're going to do is that we're going to divide the list into sub list right until we cannot divide the list anymore right until there's only one note in our list then what we're going to do is we're going to start to merge the list back uh in a sorter in a in an ascending order right so you can see here we have our list right this is our list this is our original list we split it in the middle so basically we iterate we've we know how to find the middle node right in our linked list from our previous videos in on our channel basically what we're going to do is that we're going to find the middle node split it right divide this list in half so what we're going to do is that after we divide the two less than half we're going to continue to divide the two list in half because this we have at least we have more than one note right once we find once we found that our kernels has only one node what we're going to do is that we're going to start to merge them we're going to start to sort them right in this case we have no four no two so what we're going to do is that we're going to treat it as two sub lists right so we know how to merge two uh link lists together right so what can do is that we can be able to merge them in sort in sorter in ascending order so node two is bigger less than node four so no two comes before node four so we have no two dot mass is no four right and then same thing for this sub list once we cannot split them anymore we can be able to uh merge them right so now we have no 1.03 1.03 1.03 so once we have the two sorted sub lists what we're going to do is we're going to sort those two sub lists right so in this case we're going to get no one smaller than no two right so in this case we have pointer points to here one pointer points to here so no one is smaller than node two so we have the first node it's going to be no one and then node three is smaller bigger than o2 so we have no two for an s node uh no four is bigger than node three so we're just going to get no three uh points uh be at this position and then at the end uh we retrieve we get to a null right what's going to happen is that we're just going to append the remaining elements on the on this list onto the result list and at the end we're basically returning the head node right so this is basically how we're going to solve the problem using divide and conquer or merge sort so let's take a look at how we can do this in code so basically do this in code it's very simple first we define our base case right if we cannot be able to split um if there's only one node in our list right we cannot be able to split anymore then what we have to do is we have to return our current node right and then what we have to do first we have to split the list we have to divide first before we merge right so we split in the middle right so we have this function called split mid or split middle node right split in the middle um so what we're going to do is we're going to have two lists right one is this one right here which is the first uh first half of the list the other one is the second half of the list so what we do in the split middle node function is we basically iterate to the middle right so we have a slow point or we have a fast pointer and then we basically iterate to the middle and then what we're going to do is that once we find the middle node we're going to get pre dot nest this is null and then we're returning slow so slow is basically the head node of the two the second or the last half of the list right the head node of the last half list so once we have l1 l2 what we're going to do is we're going to sort the last left half and then we're going to sort the right half right once we sort the left and the right um what we're going to do is we're going to merge them together right so what we're going to do first is we're going to create a dummy node and then this is our result that we're going to return at the end right so what we're going to do is we're going to basically merge them right we know how to merge two linked lists right we know how to merge two sorter link lists right so what we're going to do is that whoever has the smallest value we're just going to say rest.nest is equal to l uh that node rest.nest is equal to l uh that node rest.nest is equal to l uh that node right whoever is smaller right and then what we're going to do is that we're going to move that pointer one to the right um and then same thing after that we're gonna move the rest pointer right result pointer one to the right one to the next node right once we uh hit a condition if l1 is null or l2 is null what we're going to do is that if l2 does not accordingly we're going to get rest.nest is equal to l2 right if rest.nest is equal to l2 right if rest.nest is equal to l2 right if there's more nodes left we will make sure we will pen that right we will get the tail node of the result list point to the sorted uh for the remaining list right for the remaining elements um and then once what's going to happen is that we're going to return the head node is actually going to be dummy.nest node is actually going to be dummy.nest node is actually going to be dummy.nest right so dummy is basically the node and then we're going to get dummy dot nest is pointing to the head node of the sorted list right and at the end we're basically returning the head of the sorted list right so basically you can see this is how we solve the problem and you can see this the time complexity for this algorithm is going to be big o of n log n and space complexity in this case is going to be big o of log n right so there you have it and thank you for watching
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
1,662 |
Hello Hi Everyone Welcome To My Channel It's All Also Problem Text To Strings Are Yaar Equivalent To Give Into Steve Whitmore Aka He Tours And Travels The Amazing Contaminated Water For Subscribing To String Events Will B C D E F This Is The Spelling Of Birth subscribe The Members of the Channel Please subscribe and subscribe the Very Straightforward Thing The Problem Is Indiscriminate Extra The Explanation Users Painters The Solution You Can Do Subscribe How To Give For Them Like A String From This Point Cutting Also One To Three Do Subscribe Definition And Implementation Of Subscribe them birds no veer whatsapp khol subscribe to 200 here visit for each word in words the world in words you and introduced in builder and have and here return Ajay to a string of bar that Rishi to string with respect will convert into a String and let's try to compile attend c subscribe 598 137 accepts what is the time complexity of dissolution total number of characters in world in the native will not lose its total number of world channels subscribe don subscribe and subscribe that equal to 2 days if hindi Join Boosting Join with node eliminator and chief world where to subscribe like one liner research on of class nine I think it's static method to be in this printing on Thursday it's a this time Swayam 3D Ne Singla Recording Dance Class this channel subscribe my channel thank You
|
Check If Two String Arrays are Equivalent
|
minimum-numbers-of-function-calls-to-make-target-array
|
Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "\]
**Output:** true
**Explanation:**
word1 represents string "ab " + "c " -> "abc "
word2 represents string "a " + "bc " -> "abc "
The strings are the same, so return true.
**Example 2:**
**Input:** word1 = \[ "a ", "cb "\], word2 = \[ "ab ", "c "\]
**Output:** false
**Example 3:**
**Input:** word1 = \[ "abc ", "d ", "defg "\], word2 = \[ "abcddefg "\]
**Output:** true
**Constraints:**
* `1 <= word1.length, word2.length <= 103`
* `1 <= word1[i].length, word2[i].length <= 103`
* `1 <= sum(word1[i].length), sum(word2[i].length) <= 103`
* `word1[i]` and `word2[i]` consist of lowercase letters.
|
Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even.
|
Array,Greedy
|
Medium
| null |
796 |
Hello everyone, how are you all, so today we will delete another interesting question whose name is Roti String 1796 question and in this we have to write the string, one S and one code, so we have to rotate the string S and number of numbers. Off character in that barium can make me cry D by crying Our street string is that and the one that is our S is equal A caste so I have to return true otherwise I have to return water so I see its logic is simple There is some logic to it, so let's see, now we have string ABC here and where is our string starting from A and Andoriya is our I, so what do we have to do, if we want to do Rote, what do we have to do Rote? There is a circular rote, there is a circle, that rote is relief, infinity time technique, there will be no infinity time, whatever it is, it will move to the first position and the last one will shift to the second last position and the BB will shift to its second position and Which is our A here, this A will go to our first position like this, here Roshan, if our string is starting from A and more are coming to I, then what will we do after Roshan, where will our string start? Will start from A and will be D then where will our string start Will start from D and will be C Roshan First it will go here then D will be last then A will go here then C will be last then C will be at the first position When Roshan will go on, what will we do? Tomorrow we will keep comparing with the string. What will happen first? What will we do? Where will we get the shifting done? We will get the shifting done from the ending. We will shift D to the last position. C will be shifted to the second last position. We have set this at the position of C and A at the position of B, but how will our last element shift to the first position? What will we have to do with it? We will create a character L and store the last element in it and whenever. Our shifting will be finished, D has gone to the last position, C has gone to the second last position and A has gone to the middle position, then our first position is ETV. If our clear position is vacant then what will we do in it. This is the last element, we have the last element and put it there. We will set it at and after setting the string that will be created, it will go to our first position, then it will go to A, then B, then C and D. This will become our position. When we insert the last element at the first position, we will set it. So what will become of our string? Our string will become like this, A went to the first position, then A, then B, then C, then what will happen like this, Roshan will keep moving and we will keep comparing our string with the goal, so let's see. We implement this. To implement this, we have a string called jivan. This is S and a string which is one. First of all, what will we do? To solve this question, what is the string we have? Everyone knows that history is immutable. There are some other languages in Java. String some other languages in Java. String some other languages in Java. String Immutability is the meaning of immutable. We cannot change a single party string by declaring it, but when a problem started facing, the string is called Stringbuilder. What is Stringbuilder? String is in the form but we can change the string builder. We can modify the values in it, so modify the values in it, so modify the values in it, so what we will do is convert this string into string builder and then we will solve our question, so we define string builder just like string, this is our screen builder sp name. Let's take from and new and pass the value in it, we will s which is our string now s what is the value of We will start the loop for Roshan and which will be our source length, the value of length i will be incremented which will be our length till there the value of i will be incremented so that we can update the string as many times as there is no benefit in repeating it indefinitely. If we have anything tomorrow, if it has any string, after the above illumination, then it has a smooth character, it has never come in that much illumination, then the second loop we will apply it from the length, which is the value of K, apply, we will apply it from the length, which is the value of K, restored left. Why did we do it because we have to shift, I just told you here also what we have to do is shifting, first we will shift D to A's place, then C to D's place, then B to C's place, like this we will end up If we start shifting, then what will we get? The first element will not be there and we will store the last value in it. Sign the value of the last key in it. Where does the value of six start from? Stop length minus one. We did this because if Our string is 5 feet in length. How far will the indexing go? And indexing is done till m n - 1. So And indexing is done till m n - 1. So And indexing is done till m n - 1. So now what will we do, this is our greater than zero and I - do, this is our greater than zero and I - do, this is our greater than zero and I - K - sorry here on zero minus which K - sorry here on zero minus which K - sorry here on zero minus which we have. After shifting, let's do the shifting first. Now we will take the character in it, character C which will be storing our first one, which character will be storing it, do that SP, do care, the minus one of the position, the minus one of now, why did we do it now? I understand you and in Spots and Stringbuilder itself, we will set the value at which position we will set the CCO site. Now let me tell you why we have installed the value of K minus one in C. Six minus one. We have this index now. What we did is what we did here is we initialized the value of J - 1 in C and set here which J - 1 in C and set here which J - 1 in C and set here which character at which position, what is the last egg in J, we stored the value in C and we gave Shifted it to I and then to C like this, we will shift position B to C, A will become there, we will take the character of MP, we will stock it in the last wing list here, sp dot care and this one. Our task is being performed, what did we do in it, did we shift it and what does MP do to the first element, what will we do in the first element which is our zero index, after this the gold and our stringbuilder sub is equal or not? SPK is there, we have StringBuilder so it will return
|
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 |
45 |
this is a fairly simple problem to solve as long as you understand how do you reverse a string in the best time possible so in this particular video I will be discussing three different methods how you can reverse a string and each of the method is equally optimal and fast as well all of them will give you a correct answer so let's find them out Hello friends welcome back to my Channel first I will explain you the problem statement and we at some sample test cases going forward we will see how you can break this problem such that you only have to reverse a string and that remains the main part we will look at three different methods and then also do a dry run of one of the methods so that you can understand and visualize how all of this is actually working in action without further Ado let's get started first of all let's try to make sure that we are understanding the problem statement correctly in this problem you are given a string s and you have to reverse the order of each of the words while preserving the original spaces and the word order so what does that actually mean for example I have this test case with me you can see that this string has four words welcome to this world and each of this word is separated by a space that is defined so what you need to do is you need to preserve this exact order and reverse each of the word so when you perform this operation your final string should look something like this what do you see that this word welcome has been reversed then t o has been reversed then this has been reversed and then world has also been reversed notice that the punctuation mark has also reversed this exclamation comes over here so that is what you need to do similarly in a second test case what do you see you just have two words what's up and notice that words are separated by a space that is all you need to keep in mind so you reverse the first word and this is what you get notice that the ordering of the punctuations will also change it means that when you reverse the string you should not get f t a h apostrophy and then a w you want to reverse the entire thing so that is what the problem statement is how do you go about approaching it let us start with a sample test case I have this string welcome to this world and if you remember I said in the beginning that this problem just relies on the fact that how quickly you are able to reverse a given string so although you do not have to reverse the entire string you have to reverse each of the different words correct so the problem just simply breaks down into that you take up this string and then start to Traverse it as soon as you find a space this gives you one string correct so you will have this string with you and then you are going to pass it in a function now this function should return you the reverse string you will get back that string place it in your original string and then keep moving ahead similarly you will now get your next string send it to the function and then get the Reversed part once again you will do it for the next word and you will do it for the next word so this is how you proceed so if you notice the major time you will be spending that is only when you are reversing a string so if we are able to crack that okay this is how I can reverse my string in the most efficient way that will give you the solution correct and that will be the most optimal so how can you go about reversing strings I want to discuss three particular methods and all of them are equally optimal so first of all let us say I have a sample string with me correct a Brute Force solution would be that okay you start from the beginning go all the way up to the end look at the string and then get it once again start from the beginning go to the second last and then get it instead what you can do is instead of traversing from front to back what you can do is you can start from the back Direction so now if you have a string you start traversing one character at a time from the backwards Direction and then construct your string so over here you will start to get e then a l then a p M A and A S and this string will get reversed correct so we were going step by step from the backwards direction right notice that this method takes up order of end time complexity because you are traving each of the character and it also takes up order of n space complexity because you need that extra space to store your reverse string right and it cannot get better than this the next method I want to talk about out is by using the stack data structure a stack data structure is very helpful because it follows the policy of last in first out so for example when I have my sample string over here and now what I do is I simply take a stack data structure and then what I'm going to do is I will start to Traverse from the left Direction character by character and put all of your characters in your stack right once you have iterated over the entire string all you need to do is just look at your stack and then start popping each character one at a time so first of all you will get an e then a l then a p then M then a and then s so what did we just do we were again able to reverse the string correct and once again what was the time complexity is order of 2 * by n because you are is order of 2 * by n because you are is order of 2 * by n because you are first traversing the entire string to put it in your stack and then you are popping each character from the stack to get all of your entire characters so that is order of 2N and the space complexity of this solution is also order of n because you need that extra space to maintain your stack right order of 2N is also equivalent to order of n because two is just a constant but this is just a comparison how all of these methods are actually working you can use any method that you like I want to discuss one more method this next method I want to disc is the two-p pointer I want to disc is the two-p pointer I want to disc is the two-p pointer approach and it is slightly faster because what we do is we manage two pointers the first pointer and then the second pointer from the very end so now both of these pointers are pointing at the first and last locations correct and when this string will be reversed both the position of these characters will also be reversed in the final output right this s will be the first to appear and this T will come at the last so what I will do is when I have my pointers initialized I will swap the positions of the first pointer and the last pointer so what will this do this will start to change my string will now start to look like s over here and then a t over here right all of my characters are still intact but I'm not writing them now next what you do is you do left Plus+ and then you do WR minus and Plus+ and then you do WR minus and Plus+ and then you do WR minus and once again just swap the characters at both of these positions what do I get now I get an r and I get a w similarly keep moving ahead left Plus+ and then keep moving ahead left Plus+ and then keep moving ahead left Plus+ and then right minus swap both of them and now what do you get e over here and O over here this will go on happening and ultimately I will have t and then a n and then a p and a o and an I at this moment both the pointers will be pointing at the same character and that is how you know that okay you will stop so what just happened just by traversing half the string you were able to derive your reverse string correct so in a way this method Works in a Time complexity of order of N by2 and that is what makes this method slightly faster the space complexity of this solution will be order of n because you will need that extra space to actually swap your all the characters and then store your string so although all of these methods are different but the overall time complexity Remains the Same because even order of n by2 translates to order of n so you do not get a lot of speed difference but it is just good to know that hey there are ways by which you can reduce the time because think about it is not always necessary that you have to Traverse the entire string there could be some use cases where you just need to determine how you are reversing the string and that is where these kind of approaches come in handy and it gives you more ideas as well so once you have figured this out here is my sample string once again right so I will take one word at a time and then apply the two-p pointer approach on each of the two-p pointer approach on each of the two-p pointer approach on each of the word so I will keep on continuing this for each of the word and then ultimately I will have my resultant answer right so I want to discuss this approach and just do a dryon of the code so that you can visualize how all of this actually works in action on the left side of your screen you will have the complete code to implement the solution and on the right I have the sample test case that is passed in as an input parameter to the function now before writing any code we must first learn how would you implement a function that takes in a world have a left pointer and a right pointer and then it would reverse it and then we can plug it in all the required places so over here I have my method this is a method which will take in a character array that is representing my string it has a left pointer and a right pointer and then it will reverse all the positions so what does it do it runs a v Loop until the left pointer is behind the right pointer and for each of the iteration it will swap whatever is present in the left character and the right character and then just swap it and then it does a left Plus+ and a right minus so left Plus+ and a right minus so left Plus+ and a right minus so this will give me a reverse string now how do I actually use this method in my actual code so first of all where does this character array come from that is the first thing that we do what we do is we take our given string and convert the entire string to a character array so what it basically does is this is your string it will now start to look something like this has now become a character array where each of the position is occupying one character right now Begins the fun part I initialize two pointers that is left and right currently both of them are pointing at the first character that is W the next part is to actually determine when are you getting a word so over here I'm running a while loop that will keep on incrementing the right pointer until I find a space so what does this Loop do this Loop will check if the element at the right pointer is a space if not it will keep on incrementing this right pointer one step ahead correct as soon as you reach this location this is what we are doing right Plus+ as soon as I reach this right Plus+ as soon as I reach this right Plus+ as soon as I reach this location as soon as I encounter that okay my right character is at a space what do I will call my reverse function and in this reverse function I will send in my character array and then I will send in the left pointer and I will send in the right pointer so this character array gets sent in to my helper function that I just created and it has both of these pointers the left pointer and the right pointer and this does its magic all of the characters get reversed and they are placed back in your original array so basically your array starts to look something like this notice that this word has been reversed and we are done with the first word now so what do we do next we do left equals to right + 1 so next we do left equals to right + 1 so next we do left equals to right + 1 so this will increment my left pointer right over here and then once again this Loop will continue to run we will now increment this right pointer again ahead until we find a space you found a space again over here so it will go into the reverse function and then it will have the Reversed word over here so this will continue happening until your entire string is reversed and now once you have reversed each of the word you will simply return this new string from this array this function will convert the array back to your string and it will be reversed I hope I was able to simplify the problem and it solution for you as for my final thoughts I want to say that I would expect this kind of problem in a coding interview which is for a entry-level position because at those entry-level position because at those entry-level position because at those positions your interviewer is just trying to assess what is your thought process like how many different methods can you come up with so do not just rely on a single method your interviewer can always say that hey you cannot use this function so what will you do in such a scenario thinking abstract and thinking out of the box for different methods is very helpful so while going throughout the video did you face any problems or do you have any other methods in Mind by which you can efficiently reverse a string tell me everything in the comment section below and I would love to discuss all of it with you also it will become a very good collection of all the different methods when you come back in the future and revise the problem 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 simplify programming for you also a huge shout out to all the members who support my channel you guys really keep me going and as a member you do get PRI to reply to your comments as well stay tuned for my next video Until then see you
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
368 |
hello everybody welcome to my channel today is the day 13 of june recording challenge and the problem is largest divisible subset so let's read the problem statement and try to understand the given example so given a set of distinct positive integer find the largest subset such that every pair s i and sj of element in this subset satisfy this property where as i modulo as j0 or sj modulo si0 so anyone should follow and if there are multiple solution written any subset is fine so in example when we have three number one two three if we do modulo two with one is zero if we do modulo three with one is zero if we do try to do modulo three bit two is not zero so we can take at max two elements as a subset so it is either one or two or we can also return one or three so this is the answer for n in example do we have one two three four so here we can so these all four numbers are 2 to the power 0 1 2 3 accordingly so each number can we divide the modulus let's say like this 4 modulo 8 like 8 modulo 4 0 2 mod 4 modulo 2 is 0 and 2 modulo 1 is 0 so all 4 can be the part of answers so this is the answer we return let me explain you few important thing here we need to use so let's we have 3 number in a is 2 and we and v is 4 from the example 2 i am trying to explain you and this is c is 8. so here what we can say c modulo b is 0 correct and b modulo a is 0. so with these two conditions so this should be modulo here so with these two condition we can say so modulo support the property called associativity so this property this both of them will implies us like c modulo a is also 0. so this property is called associativity and the number is in ah increasing order so if number is in given we can we don't have to check for c modulo a if we already checked with c modulo b and b modulo a in the increase owner so this is a very key idea here we will gonna use in this uh solution so let i have draw one custom example here like in array we have 1 4 5 8 12 and 9 so for using this associative property we will sort the number and there is another reason of sorting these numbers first because if we are doing for now let us say some number i if we are checking for some number this i we know all the number before this is j at all the jth index are less than this i nums of i so if this is less than so we can easily check with the all the number we so here let me take another array where i can store the counts of the modulo how many numbers max number in a subset so initially like each individual element is also a subset so this is a subset 1 subset 4 is independent subset like these all are independent subsets so we will initialize this array with one so every element with subset ending here all the index is with initialize is one now after that we will go through this using the dynamic programming approach so if we check for this is already one there is no left side and if we are checking for four so for this number what we will do for four we will check with the all the previous number like how many numbers this 4 is like divisible so if we check with 1 so like here so if i check here let me draw the step if 4 modulo 1 is 0 or not yes four modulo one is zero so what we can take so this will be zero so this is zero then we can check the count of 4 basically at index 1 so this is at index 1 is equal to max of count of this itself and the count of 0 plus 1 because we are adding 4 in that so this is will be this will be max of one comma one plus one so which is two so here the value of count two similarly we will check for five so for five if we check with first four so here let me show you this as well so 5 mod 4 if each 5 mod 4 is 0 no the 5 mod 4 is not 0 so it's let me put like this it's not zero um so here the count of this will be we cannot consider this in the increment though so we will continue go to the down then we will check with five mod one is it zero yes it is zero then we will again do the same step this what we did for the four so the same step here we will do for four five so five is at index two so this value is two and we got at zero and zero one plus one again the four five also we got similarly we will get for these other number here 3 is divisible with 4 and 1 then it is 3 and the 9 is not divisible with 5 and 4 and 8. so it divides by directive 1. so it's 2 and the 12 will divisible by either 4 or so 1 4 12 so yeah there is length 3. so this is after the we check the all the array so now once we done with counting the maximum ending at all the index so this is like ma we will look for the where is the max value of the subset count subset so here like one is this another is so we can pick any one so here let's pick this sky so once we got this we have to construct the subset get all the subset value what we can do so for getting this once we know the index so we will take the index which is has max so let it call it max index and we will take this max index we will get from eight it is three so once we got this what we have to check so total three element in our subset which will be the max subsets and satisfying the given property so first we they take this and then current count we will count the value like start taking the count of max index here so this will be three so for this we have to go back like from which 4 is came last so we will check the modulo again with this backward direction so with 4 we are getting this then we will add first 8 and after that 4 and then we will take 4 is coming from this so it is 1 so this is our answer subset of 8 4 1 another we if we can construct that as well but we have to return any one so that is fine so let us start the implementation is like now i is very easy so first we will get the length of the array which will be nums dot length which is if we will check if there is no value in the array so we just simply return the new list numeralist so this is the first step second we have to sort the this is our step one so let it write me step one so we will sort the array sort ok so once i sort so i will use the arrays dot sort and simply sort the nums i sorted this now we need to store the need count array to store the max ending at each index lets me take a count array and which is of again the size of the array which is n and then we will do the step one or step two now arrays dot fill with one because each individual element is a subset of length one so here i need to fill count with value one so this is done now after that we will iterate through for end i is equal to one and i less than n and i plus for each element we will iterate through and then we will check the previous element how many previous element are dividing that element so j start from i minus 1 and j should be greater than n equal to 0 and j minus so if nums of i modulo nums of j is equals to 0 in that case we will update our count of i which is math dot max of count of i comma count of j plus br including the i th element so one so this is this will help us to get the so this is whole together you can see step two of dp generating the step two of this solution like ah generating calculating all subset generating dp generating count dp for all the index now the third step is so the third step is we have to get the where is the max index so max index from the our count array so here for max interaction it is max index which is at 0 let us say then we will run through the loop for in i is equal to one and i less than n i plus then we will check max index will be is equal to if count of i is greater than count of max index in that case we will update max android with i otherwise we will keep max index as it is so this will get us max index now the third step fourth step is construct this subset step 4 is construct the subset construct the longer subset longest subset ok so for this we need first list because we have to return so we will create a list integer which is name called result from the arraylist implementation in the java library and after that we will take a temporary the value at that max index so nums of max index once we got that and we will take the current count of how many max number of element in our max of set so which is current of max index correct so now we have to iterate through from down the loop from int i is equals to from max index and it should be greater than or equal to 0 and i minus once we go down then we have to check if temp our current temp is divisible by module like nums of the current i which we are looking for is equals to 0 and the current count is also equals to the count of i the value we are looking for once we got this particular element so we will update the temp first we will add the current number in the list so this will be num stored at nums of i result dot at num so five then after that we will update our time temp will be nums of i ah sorry this will be nums of i once it we got this then after that we will current decrease the count because we have already picked that current value so continuously this will run for total max index times and we will pick the current counter in our subset once we got in the values in our subset we will return the result so this is the whole implementation using the four steps step one sort this step to generate the generating the count dp and then step three in max found the max and once we got the mechanic we will construct the longest subset let us try to compile our code current it should be count sorry i mistakely use here current it should be count because i am using defined as a count everywhere and here i use this should be okay other than that i guess it's fine yes it's fine so let's try to compile it yeah it's got compiled and we got the correct answer so it can abso accept in any order so let us test our the test i example test case i explained you with that help let me try to test that and the custom task is so we have array 1 4 5 8 12 9 so let's see whether we are getting either 1 8 1 4 8 or 1 4 12 yeah we are getting that so that's correct let's submit our code and it is accepted so this is the simple solution let's check the time complexity and this space complexity so here we are doing n log n and log n steps in sorting but we are running this loop two times so this will be uh n square and also after that we are is max is n square so and the space we are using this array counter is so it is so total here time complexity is o of n log n oh sorry n square and the space complexity is o of n thank you if you like my solution please hit the like button and subscribe to my channel and share with among your friends so that everyone got help
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
1,675 |
Okay so today our daily task problem is minimum division in Hey so today we have to solve this problem so you can see now just 3 minutes ago it was accepted after three trials three colors answer tirely after that it was accepted Namas Joe It will remain basically unsorted if it is necessary and we had to tell what will be our minimum division and our definition of minimum division is whatever our maximum difference will be So now by doing these two operations, we will get our division. Which is division, whatever our difference should be, it should be minimum, that is, we have to minimize the maximum difference of our whole. Here, we have to tell how much minimum we can make the division by doing these two operations. If we can, then if we analyze this problem a little better, then we will be able to understand that if we are right, then we will come to a point where we will get the answer, which means that every time after performing the operation, we will find our element in our era. Keep sorting like if we look at its root four then our current is 1234 so our 4 - 13 so our 4 - 13 so our 4 - 13 after that we will divide the last one by you then 3 will become the biggest then 3 - 1 will become our 2 but then see If we 3 - 1 will become our 2 but then see If we 3 - 1 will become our 2 but then see If we multiply hoon ma then this will be ours. Our answer van will come in this. So to do this question, there are two operations given here. First of all, what will we do? We will remove these two operations and we will do only one operation. If we convert our question into , only one operation. If we convert our question into , only one operation. If we convert our question into , then what will we do to do that, if we look at the OD numbers that we have, all the OD numbers that we have, if we look at it like this is 1543, we have to convert these OD numbers only once. We will have to multiply by t in every gas because once we multiply by tu then these and will become and, after that we will have these and when we will have only our and numbers in the whole, then we will have only one operation left to divide by tu. So first of all we make our whole numbers because it is given to us unlimitedly that we can multiply any number by 2 any number of times and divide the number by photo and because we want it in sorted form. For everyone who needs it, we can do it using multi sets, so here we will do it using multi sets, first of all it was simple that if our element is there, then we will insert it by multiplying it by tu and If not OD then you will insert directly. Now in our multi set we have all the numbers and it remains sorted in the multi set. So now we have to see here that in every case we have to take the first element and at the end we have to take this element. If we want to take the difference of multi sets and both, then what will we do for that, we will create an answer variable in which our answer will be stored and we will create a count variable in which we will have to run vice look to get the first and last element. How many times do we open the numbers, so if we look here, our name is, if we see, our Rafalei is approx 2^20, so it means if we approx 2^20, so it means if we approx 2^20, so it means if we divide Safai by 20 times, it will become, so we can see this. We will take that as long as our account is there, now we do not have to do anything, we have to go every time to get the first element because our ms.bin will be done and we have to go and get our last element, it will be non-stop and for the last element non-stop and for the last element non-stop and for the last element we have to 81 - If we have to finance, then we have to 81 - If we have to finance, then we have to 81 - If we have to finance, then what do we do here? We have to take the minimum in the answer and minus number and I have taken the minimum in this and I have to see that if my name is you, if it is and because what will we do? We will always try to make the larger element which will remain last, smaller. We will never make the first element smaller because if we make the first element smaller then the difference will keep on increasing till all the bins remain. Now, since we will have all the events in our multi set, first before dividing, we will see how much we can make our last element as small as possible so that our difference becomes minimum. We want minimum difference, so first of all we will remove it from our multi set. And when we insert, ours will be tu divided by tu and here it is taking our minimum answer, so just for the sake of simulation, we have to return our answer, in every case it will take the minimum and in the worst case, see which is 20 times. To make any number van, if all the nines are there then it will reduce all the accepted submit or accepted soya tha's it is for today daily problem.
|
Minimize Deviation in Array
|
magnetic-force-between-two-balls
|
You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109`
|
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
|
Array,Binary Search,Sorting
|
Medium
|
2188
|
538 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem is convert bst to greater tree so in this problem we are given root of binary search tree converted into a greater tree such that every key of the original bst is changed to original key plus the sum of all the keys greater than original key in the bst okay as a reminder a binary search tree is a tree that satisfies these constraints left sub tree of a node contains only nodes with keys less than the nodes key right subtree contains nodes with keys greater than the nodes key and both left and right subtrees must also be binary search tree so i hope you're familiar with what is binary search tree and what are its properties so what in this problem we have to do right let's see that so this is the test case for example let's take this three node let's take this so here this three will be replaced with three plus like the current value of this node three plus all the values in this bst which are greater than three okay for example 4 is greater than 3 5 6 is greater than 3 5 is greater than 3 7 is greater than 3 and 8 is greater than 3 so when we add all these we get 33 so this three will be placed with 33 this three will get replaced by 33 okay similarly if we see for this eight now see guys for this eight obviously this is the right most child now in this binary search tree this is just make sure you know that this is a binary surgery okay so in this binary search tree this eight is the right most child so if it is the right most child it means that it will be the most greater value right most child right so obviously eight will be the largest value in the entire bst because this is the right most child so obviously there will be no element greater than 8 so 8 will be remaining it will remain as such okay so 8 plus nothing will be there so 8 only so if you see here 8 is 8 only for the 7 so for this 7 what is there 7 plus we can do 8 7 plus 8 so it will be 15 because only 8 is greater than 7 so 7 plus 8 will be 15 and this 7 will get replaced by 50. okay so in this way every node in this bst right we have to replace it with the uh greater than all with the current value plus all the values which are greater than let's say it is x so current node value is x and we have to added it all the node values which are greater than x so this will be the final value of the node okay so i hope you understood what the problem is now let's see how we can think of the approach so this is a tricky question right it's very simple but just it's little bit tricky so the trick is very awesome let's see that what it is so 7 8 and 3 now see guys generally when we have to do some every terminal like one simple and very not efficient approaches that for example if i'm at this node i will search in the bst right i will find out the sum of all nodes some of all nodes which are greater than this two node obviously i can do this so when i'm at this two node i will start traversing from this 4 and i will find out the sum of all the nodes which are greater than 2 so i get that sum as x1 so that x1 i will add in 2 and i will replace this 2 with that value let's say it is y so i'll replace this 2 with y but see that is this approach what you need to do every time you need to do for every node for example if i'm at 1 again i will search in the whole pst sum of all the nodes which are greater than 2 oh sorry greater than 1 and that sum i will add in one thing right so obviously this is not an efficient approach because we are for each node we are traversing bst again and again right that is like for this node also we will search in the bst the sum then for this node also will search in the bst so when this repetitive work is coming now like we are again and again searching or finding out the sum so when this repetitive work is coming then what we can do is we can return or we can have some variable which will store the value how does that work let's see that so let me here c this is two right so in this case what we will do right in this approach the thing is that right most child will remain as such right this right most child will remain as such and there will be obviously no greater than element than this right most child so what i will do now i will i'm right now at root first of all i will recursively traverse till the rightmost cell here i came here now this eight will be eight only i will have a variable sum initialize it with zero so first of all what i am doing i am making a recursive call i am going to roots right every time so here root is 4 so i go to roots right which is 6 then root is 6 so i go to roots right which is 7 then root is seven i go to seven's right which is eight so now root is at eight so this is the right most child so here some we are currently some will be zero and from here we just return we return right and this 7 here this 8 right will be added in the sum because this 8 will be value greater than 7 so this 8 i will add in the sum variable and we will return from here and in this 7 now this is the root 7 is the root so here let me just write it like this 7 is the root okay so now in 7 what we will add this sum variable so 7 plus it will become 7 plus 8 which is 15 so this value 15 we will update in roots value so roots value will be equal to 15 that is here 7 will replace by 15 okay and now we will return so we return right so right now uh what after this first step after this recursive call what we did the second step was that is in root roots value we added sum that is this step and then third step was that we updated roots value 7's value with this sum which is so let me take this as y sum so root value will become 5 y 15 and after that what we are doing we are just returning okay so from here we will go to 6 we will do 6 plus now see here some this sum right this sum needs to be 8 or it needs to be 15 just think about it what this sum should be when we are adding in 6 this sum should be 8 or 15 i think it should be 15 why because 7 and 8 both are greater than six so total sum which is greater than six is fifteen so every time right whenever we are updating the roots value this sum value also will become one uh y so sum will be fifty and then six plus 15 this second step we are doing so this will come out to be 21 and then this 21 will update as roots value and also sum will update 21. okay right now guys see now should we go here or should we go to the left i think we should go to the left right so here what i will do after this here fifth step will be recursive call to roots left because if called two roots left so six here it goes to left five plus sum which is twenty 21 so 21 is the sum of all the nodes see 6 plus 7 plus 8 this is 21 so 21 is the sum of all the nodes which are greater than 5 so 5 21 26 5 will be replaced by 26 so see we are making this tree right 26 21 now here uh this root node we have updated some we have to update to 26 and recursive call left is nothing so we just return from here and we return to this 4 so for this 4 plus some value which is 26 30 will become 30 we update here and 30 we update in the sum so you might be thinking that why we started from right because see guys these right subtree values will be always greater than right this left subtree so what we are doing is we are maintaining the sum of all the nodes which are great like the sum of all the nodes which are greater than a particular node for example if i am at 6 in this sub value i will have the sum of the nodes which are greater than 6. if i am at 4 in the sum variable i will have the sum of all the nodes which are greater than four okay so from this four now we will go to left so left it will go here one but see now guys now here it will not calculate for this one first it will go to the right first two and three so it comes here at three so this three plus what will happen 3 plus you think about it year 3 plus it will be 30 sum is 30 right 3 plus 30 this will be 33 updated 33 sum updated to 33 and we return so for this 2 now 2 plus sum is 33 so it will be 35 and sum will be 35. so see this 3 is greater than 2 right so that's why first we have gone to 3 and then we are going to 2 so then we go back 1 plus the sum 35 so it will be 36 and now we go to the left because this one was greater than zero so first we have to go to one and then to z so this will be uh 36 plus 0 so it will be 36 this will get updated to 36 okay so something like this is the tree which we have created so i hope you understood this approach very simple just we need to do the opposite traversal right first we have to go to the right then we go to the root so here first we go to the right then we go to the we do the work on the root and then we go to the left okay so now let's quickly see the code for this ins and see the time complexity will be what we are going to each node right every time we are just going to each node once so time complexity will be o of n where n is the number of nodes and space is also often like if recursive stack is taken into account okay so see we have taken a sum variable this will be a global variable right it will be a global variable as in it will be a private variable so here we have convert bst function first root is not null so we make the right call we add the sum value root value in the sum update the root value and we convert uh then we make the left call and last we have to return root because we have to return this value 30 right return type is tree node i hope you understood the problem and the approach drier and months and it will become more clear let me know in the comments if any doubt found the video helpful please like it subscribe to my channel and i'll in the next video thank you
|
Convert BST to Greater Tree
|
convert-bst-to-greater-tree
|
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\]
**Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\]
**Example 2:**
**Input:** root = \[0,null,1\]
**Output:** \[1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-104 <= Node.val <= 104`
* All the values in the tree are **unique**.
* `root` is guaranteed to be a valid binary search tree.
**Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
| null |
112 |
lead code number 112 it's a question called path sum and here we're given a root of a binary tree and an integer target sum we want to return true if the tree has a root to leave path such that adding up all the values along the path equals the target sum and a leaf is a node with no children so here we have this tree and if we add up this numbers on the path from the root to leaf path they do add up to the target sum which is 22 so it's true here from root to leaf the target is 5 and there's no root to leaf path that equals 5 so we're going to output false okay so the way we want to think about this is we're going to have to create a recursive solution and what we want to do is we want to figure out when we are in our base case when we hit that leaf level and as we go down the tree as we traverse from top to bottom we want to subtract whatever the value is at our current node from the target sum we just want to pass that target sum as a variable all the way down until we hit the bottom and when we hit the bottom if whatever that is in that sum equals whatever the value is at the bottom then we know that the path all the way down is going to equal the target so let's break this down so here we start at the root 5 and our target is 22 okay so target here is going to equal 22. now we're going to recursively call our debt first search helper function and we're going to subtract whatever the value is at our current node when we pass it down to the left and the right okay so we're going to subtract minus 5 from that 22 and we're gonna subtract minus five so now here on this call target is going to equal 17 and target is going to equal 17. our base case is are we at a leaf node we're not so we're going to continue on now we're going to subtract from 17 we're going to pass in for the left we're going to subtract 8 from our slate sum the sum that we're passing in down the tree and we're going to subtract 8 from the right side here we're going to subtract 4 as we pass it down as a variable okay so now on this level of the tree our target becomes nine and our target here becomes nine and now here we did hit a leaf node we just ask is our running slate our running sum does it equal whatever the value is at the leaf it doesn't so we don't do anything we just return out of it okay here we do have a right node this is right so it goes this way we do have a right node and so what we want to do is we want to pass in we want to subtract 4 from our target so when we get down here to the bottom our target is going to equal 5. and then we ask does this equal whatever our running tar what running sum is it doesn't so we also return out of there we don't do anything let's go over to the left side here we subtracted 4 from 17 so our target is going to be 13. okay now we hit this 11. there's a right and a left so we're going to subtract 11 from our running sum and we're going to subtract 11 from our left side and our right side so here when we subtract 11 from 13 our target equals 2. does this equal 7 no it doesn't okay so we also return out of there and here our target is going to equal 2. does this equal our running sum it does and so we have a global counter which is we can just name it has path right we can set that as a global counter and we can initialize it to false but if it does hit this base case and it does have uh the running sum does equal whatever is in that node that leaf level node's value then we just change this to true okay and then when we break out of our helper function we just return our global has path and it'll be true and you can see here that if you add up all these numbers together it does equal our target sum okay so that's the idea let's talk about time and space complexity for time complexity we're going to have to traverse through every single node because we have to figure out the path for every single node what the sum is at the leaf level okay so our time complexity here worst case is going to be o of n now what about space complexity well we're not generating any new space because we just have a counter here we do have this running sum that we're keeping track of so we do have some space there but we also have the call stack because we're using recursion we're going to have a recursive call stack and the call stack is going to be at the worst case at the leaf level it's going to be the height of the tree okay so if you're dealing with a balanced binary tree then it will be log n but if the tree is unbalanced for example if the tree just looks it's just one-sided one-sided one-sided right then the height of it will be uh n it'll be the size of the tree so our space complexity here worst case if we're dealing with an unbalanced binary tree it's also going to be linear as well okay it's just going to be the size of the call stack and also the sum that we're keeping track of okay so that is the basic idea let's jump into the code okay give me one second here let's disconnect there so now let's take a look at what we want to do the first thing we want to do is we want to take care of our edge case of if we if the input is empty so if the root is null then we want to go ahead and just return false okay now what we want to do is we want to create a global has path a global variable a boolean so we can say let has path equals false we'll just initialize it to false and now we want to set up our recursive depth first search helper function okay this is going to take in a node and then it'll take in our running sum and now what we want to do is we want to check as our base case we want to check are we at a leaf level so if node we can just say if node.left node.left node.left equals null and write equals null then what do we want to check is the sum at that leaf level equal the node.val so we can say if equal the node.val so we can say if equal the node.val so we can say if sum equals node.val then we do have sum equals node.val then we do have sum equals node.val then we do have a viable path and we just want to change our global variable to true so we can just say has path equals true and then we just return out of that if we're not at a leaf level then what do we need to check if there's a left node and then recursively call depth first search on that and then check if there's a write node and recursively call depth first search on that so if no dot left then we just want to do depth first search on no dot left and then subtract from the sum uh no dot vowel our current node's value we just want to subtract that from the sum okay here we want to do if no dot write depth first search node.right depth first search node.right depth first search node.right and then subtract sum from the no dot val okay and then we just want to call let me go ahead and make some more space here we want to call our debtfirst search helper function pass in the root and then pass in the target sum lastly we just return has path okay so that's it let's go ahead and run this make sure it works and we're good okay so it's not too difficult of a problem um you know this is a common pattern this depth first search helper pattern it's also used in combinatrix you know com you know combinatorials many different questions that use uh this particular pattern so it's a good one to know we'll do other questions that use the same pattern so if this still isn't clear just you know watch the other videos in this playlist and it'll start making sense okay so that's lead code 112 pat some hope you enjoyed it and i will see you all in the next one
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
111 |
hi let's talk about the second question which is minimum depth of binary tree right so if you have not checked out the similar question maximum depth of a binary tree I would strongly advise you all that please make sure you look at that video and we then come back here because then yeah this question is basically kind of a second part to that question all right so in this question the question is given a binary tree find its minimum depth the minimum depth of the is the number of nodes along the shortest path from the root node down to the nearest Leaf node right a leaf node is a node with no children so as like uh the previous example we know how to read this tree correct which is given to us right and we suppose here has also told us that the depth is basically calculated in terms of number of nodes right so we know what depth needs to be given in what terms right so here if you see now from the root node what is the minimum number of nodes until I reach a leaf node so from 3 to 9 is a leaf node how many nodes you have two from three to 15 how many nodes you have 320 and 15 3 notes three to seven again three notes so the minimum among them is what the number two because three to nine you have this two and that will be your answer correct now this question is very similar to the maximum depth question okay I hope you all agree with that right so let's just uh you know so now if I have to look at the code what will be your first guess most of you who will tell me whatever code we have written for maximum depth wherever the value was 1 plus Max of you know left comma right we instead of doing maximum we'll Now find minimum yes or no that will be your first case let's try to just check whether it works for all situations okay so we have a three year no there is a tree let's put some data in this so let's say let's take a black color right so here I have three okay nine then you have twenty you have 15 and you have seven let's draw another trigger where we have 3 20 okay 15 and 7. so let's go by the you know wherever one plus maximum of whatever in the left and whatever in the right so sorry instead of Maximum now we are going to go look for minimum because we are interested in finding the minimum depth of the three so one plus minimum so our guess is in that maximum depth question if I just change the line just basically just change your word from Maximum to minimum I should be able to get my answer so let's see what we are getting here so if you look at this particular node is going to return what a value 1 correct because how many nodes are there one node is there what about this now you start from this root note right first it goes to this left child right you finish this then you come here this is now this will again go towards left side now this is going to return what 1 for this right this is going to return one year so one returned here yes you're taking at one plus minimum of left command so one plus minimum of 1 comma 1 is basically one so one plus one is going to give you what two right so let's uh so this is going to give you two okay so let's do one thing this two value will be returned back here okay I'm just keeping this as it is what is this going to give you this is the root value is here at root also you're going to apply the formula one because you have to count the root note right three one plus minimum of 1 plus 2 is nothing but 1 plus 1 which is equal to 2 and that was actually the answer for our question as well so here you will see the minimum depth of this tree is to and it worked right just by changing that line worked let's try to use the same formula for the second example right if I mean if you come up with a formula or logic of you know uh question it should work for all the test cases most of the time I have seen you know students coming up to me and saying that yes they solve a question what happens is whatever logic they apply does solve you know it kind of works for these sample inputs okay but when they try to submit now when you submit actually more not just these two examples but a lot of test cases are going to run correct which are going to fit into this constraint So when you say your logic or whatever problem you have solved is correct it should mean that your problem should be able to solve correctly okay for all the different test cases right that means whatever logic we have applied if it is correct it should also solve for this tree okay so let's try to do that here what is this going to return to you there is no nodes here right because this is null so this is going to return what 0 yes what about this is now start from root left was zero so this is your root okay now this is going to call the left child this is going to return 1 this is also going to return 1 so we're going to return back 1 okay you're applying the same Formula 1 plus minimum of 1 comma one so you're gonna get one plus one which is equal to 2. you're returning this value to your parent now look at this for the root number three for the tree two what is the formula you're going to use one plus minimum of 0 comma two what is 1 plus minimum of you know zero comma two one plus zero what is this one this is the correct height of the tree the correct height of this tree well I mean the minimum depth of this tree should be basically three and not you know two why because according to the question the minimum depth is nothing but those many nodes okay starting from the root node to go to the leaf node tell me if I had to I mean I cannot have one here because this is just a non-leaf node I mean it's a root just a non-leaf node I mean it's a root just a non-leaf node I mean it's a root but if you have to calculate the minimum depth starting from this node I have to go over where I have to go to a leaf node now the leaf nodes which are present in this tree are only two fifteen and seven right so I have to find out the minimum depth between this path 320 and 15 or else the minimum between 320 and seven so both 320 and 15 are how many notes three nodes here and even for this part there is three notes so what actually should be it should have been my answer three and not one but that means using this logic okay my all test cases are not going to give me correct answer do you understand yes it works for this but it does not work for this scenario okay so that means this logic is flawed and we cannot use this logic right I hope this makes sense now let's understand and why did let's say this is tree one and this is tree two let's understand why did this you know logic failed for tree two what is what was something different from a test from T1 okay can I say if there is a left child okay and there is also a right child all right if this is the case can I say then you can apply the Formula 1 plus minimum of whatever your left height it is and right and I do that yes think about this is what you're actually that is this because of this condition this trees was giving a correct answer if you look at this tree when you are trying to calculate the minimum depth you know looking at the root node there was a left child and there was also a right child correct and that's why we applied this Formula One Plus minimum of left comma root and it worked and we had got a correct uh you know minimum depth for this tree but look at here is there a left child no so if you have only one child like it's a binary tree means you will have at most two children so if you have only one child what you should be returning is you should be returning one plus suppose if you have only the left child if left child exists so you're going to return the minimum depth will be one plus whatever the depth height of at the left subtree let's say if only right three sub three X's I mean we right child is present you are going to return one plus right yes so see if I had used this condition look at this in this place okay here what was this is 0 right this was what two but what is this particular root does not have both left and right child so this condition I cannot apply it basically Falls in this condition where I only have the right check when you only have the right child I have to use the Formula 1 plus whatever the height was there on the right subtree so one plus two right this was the height will give me what three and that is what would be the minimum depth for this question I hope you get this right so this just applying one plus minimum of left entry or left hand root is not going to work for all test cases it might work when you have a no when you have a node which has both left and right side but if you have a tree in where you know you can have a node which does not have both left and right it can have only one of the child in that case you have to return what one plus whatever child is available okay I hope this makes sense so now then the code because comes very easy correct now if you remember here also we have all that you know tree node you can simply I'm just simply removing this so what I'm going to do is first thing a balance fault everything Remains the Same right what we had if root is equal to null I could have simply returned and return 0 yes that's always going to be written 0 then I am going to say 8 left equal to Min depth right and you're going to call Root dot left okay then you have in right equal to mean depth of you know root dot right now what we said if both the left and right child existed then we could return 1 plus minimum of left and right how do you check that if both left and right shell existed that means left is not equal to 0 and right is also not equal to 0 why because if left child was I mean there was no left child so obviously when you return you would have you know called a function on mean depth on a null value and when it is a null value you are returning what the value as 0 correct so just to check whether there is a left child on the right cell can simply you know use a condition if left is not equal to 0 and right is not equal to 0 that means there was a left and right side for this root if that was the case then I could simply use the formula which is going to be return 1 plus math dot minimum of you know left and right but let's say if this is not the case so if this if condition is not true that means if you're coming to line number 15 that means that particular tree or particular root does not have no okay it has only one child either it's left or right how do you find out you can simply say 1 plus math dot Max of you know math dot Max of left comma right and why will this work this will work because think about this okay let's say suppose you had only you know the left child existed and right child was none right because it is null the right value would be zero correct so a maximum of a left value which is a positive number right it can be two three any number of nodes comma zero is going to return what 1 plus maximum of 3 and 0 is 3. so what will you return 1 plus 3 okay is it as good as saying Whenever there is right child is not there you are just adding one plus left correct let's say now your right child exists and your left child does not exit if left child not exist what is going to happen because of this Condition it's going to return 0 and your end left is going to have a value of zero that means again when you come down your match dot maximum of 0 comma some right value which will be a positive number so 0 comma some positive number what is the maximum always the positive number so it's as good as saying one plus right so this is like a shortcut okay I hope you got this so if I now you know just simply submit this it should work exactly fine okay so I hope you understand this right and don't be disheartened if in case you were not able to figure out this question on your own that why you know how did I come up with this Condition it's absolutely normal right if you see my submissions also there were certain times I have done you know wrong answers so it's a part and parcel of your coding Journey it is absolutely fine you're learning as long as you understand why each line of the code is written okay once you go through some solved examples you will be good to go your logic will improve and finally you will be reach a stage where you are able to come up with the solutions for a question on your own okay hope this helps bye take care
|
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
|
1,771 |
hey what's up guys uh this is sean here so this time on 1771 maximize palindrome length from subsequences so you're given like a two strings right word one and word two so you need to construct a string in the volume in the following manner so choose any subsequence from word one and then choose another subsequence from word two and then you need to concatenate those two subsequences together to make the new string and among all those kind of possible scenarios we need to return the maximum length of the new string that can form a palindrome right so for example we have some examples here right so let's say we have cacb cbba so the longest we can get is this one is it's a b and the cba okay so this is the set another one right so we have three here so this is the one we should be take a additional care here basically the reason we have zero is because you know so we have like a palindrome in this one which is two right so a is a it's a palindrome same thing for this one there's also a length of two palindrome here but the reason we have zero here is because uh we have to find any subsequence from both the uh we defined uh two subsequence from both word words one and word two so for this example here you know if we pick uh a number or a letter from both word one and word two we cannot make any uh palindrome string that's why the answer is zero okay so we have some examples here so that's a 1000 right i mean so for this kind of problem you know the uh if you try to like a basically list all the possible scenarios from uh all subsequent uh from a from word one word two and then you just uh try to check if the new string has a palindrome that'll be too slow right because that's going to be a it will it'll tle right so the way we should solve this problem is that the you guys pretty much know uh pretty much all know about how can you how can we calculate uh a longest palindrome right the longest palindrome uh a longest subsequent pattern for a given a string right we can use like the dp right dynamic programming to calculate that basically the dpi and j right dbi and j means that you know the string from i to j right from i index i to index j what is the longest palindrome uh what is that what's the longest subsequence uh as a palindrome right uh from i to j so this give us like a hint to solve this problem so if we can concatenate this word one and word two together so let's say we have a word a new word it goes to word one plus word two okay so with the new word we can use this dp technique to calculate all the uh the longest pattern drum for all the other possible start and end point so the only question the only problem we need to solve is that how can we make sure the basically the palindrome or the palindrome has both uh some string or ladders from word one and also from word two okay so assuming we have this right so actually all we need to do there's a trick here we can simply try the uh we only tried the because the is starting point j is the ending point we just need to enumerate all the i's in the range from let's say we have one and n two right so let's say we have a this is this kind of uh string here right so let's see this is the word one and this is a word two right so actually all we need to do is that we just need to enumerate all the uh odd index from both uh from word one and the word two basically which we see as long as we can make sure the i is within the range from zero to this n one right and then the j is within the range of from this n1 to n1 plus an n2 right then because as long as we can make sure that i and jh2b is in this range then we know okay that's going to be uh we can find like the we're sure right so the there will be a like uh subsequence right and then with both the letters from word one and word and one word two so which means that we just need to enumerate all the possible combinations right for uh for both the i and j within this two range here and as long as the word this letter the word one uh word one i and the word two j are the same right so if they are the same and then we can just use the similar logic uh when we tr uh to calculate dp here right basically if the word i word one iron word two j are the same then we know okay we need which the our final answer for this kind of combination for this kind of uh combination is going to be 2 plus the dp of this i plus one and then this one this kind of uh a different one a different index right because this one is j right so we're going to be j minus one uh j minor so actually this one should be an n one plus j minus one and one plus j minus one okay right so because here i mean as long as since we're basically we're saying that you know if the word one i is equal to the same equal to the word to j it means that okay basically we're still we know that there has to be a palindrome right between i and j because that because they are the same even though there's nothing in between right they're gonna be a gonna form another a more palindrome given this only these two ladders can form like a palindrome this number with length two right and then by subtracting these two and all is left is that we just need to we can simply use that to precalculate dpi plus one and this like n one plus j minus one to find the uh if there's any additional palindrome in between these two numbers okay cool so i think that's basically the idea here i mean okay so to do the codings right so we have length of word one lens two it's gonna be a word too right um so we have a word because the word one plus word two and then we have n equals the length of word so for dp right 0 and then for this thing in range of n right so that's how we initialize this dp for this uh combined word here so to start with right since uh in range n minus one okay so again i'm doing this one from the end to the beginning so that i can just use i and j to represent start from i and end with j right so j is going to be from i to n okay you can do it in the different order but i this is how i do it right so basically if the dp sorry if the words i equals the words j right so if that's the case if j minus i smaller than 2 it means that okay so there's no need to basically there's only either one or two uh letters right so in this case we can simply do this i j it goes to j minus i plus 1 because that will be the other the answers else if there's more letters in between then we know that we can just uh do this dpi j 2 plus dp i plus 1 and j minus 1 right this is a remove by after removing this ion j right so if there's anything right in between then we're going to accumulate that okay else right so if the hundred is not the same then we know okay we have to basically look for the max of dp i plus one j or the dp i j minus one right so that's how we calculate the uh the longest palindrome right for all the uh for other the possible uh sub subsequences so now uh which needs to for i in range of n1 right so we're making sure that's going to be the value right for the first uh subsequence and then for j in range of n of n2 right so if the word one i equals to the word to j right so we only need to do this because we only if and only if the i and j's are the same then we know okay there's like then we it's time for us to calculate the uh the values what the substrings right in between otherwise there's no need to consider because there won't be a palindrome right because the palindrome has to be uh basically the left and right so here we're saying that you know i want to know starting with i and ending with j what is the longest palindrome right for that and so i think from my case you know the uh let's say we have some like two this is a word one this is with the word two and so the value is going to be a answer equals to the max of answer dot two plus uh dp i plus one and then n1 plus j minus one right so this one means that you know the uh since the uh remember the dp the length of the dp means the other combined the combined word but here eyes i but for j we're only looping through the uh the second half of the string here so for i we can just use the i plus one but for the j right we have to convert this j to the uh to the length in terms of this the combined word that's why you know the length of the first one is on one right so and we just need to do a plot plus j so that will be the uh that'll be the actual index for the ending point and we do a minus one because we need similarly as this one right because we're removing or uh moving this one away from the current string that's why we do n and one plus j minus one yeah because this one will give us the uh the biggest at the longest sub uh subsequence in between right and actually i'm thinking about maybe there's some there's a corner case maybe we need to consider here i mean since we're moving this one uh closer from both left and right side so for this case if we what if i is this one j is here i think in this case we might for this one if the j is next to i so for this one i guess we this one should be equal to zero right because there's no need to do that and yeah so this is what i mean basically if the i is equal to n one minus one right and j equals to zero so for this one i get so i think the answer should be the max set of answer dot two right else we do this right so in the end i can simply return the answer yeah i think that's it right if i run the code accept it yeah so it passed right um let me see actually you know what so maybe for this part we actually i see so we don't have to separate this one here so basically so if this is the case right so i will becomes i will move to here and j will be moved to here right so which means in this case uh the start is greater than the ending point right so and for that case you know i think the dp since we initiate our audition all the elements with zero so for this kind of for the case that i is greater than j so the value for that dp will be zero so i think that's exactly what we want here so which means that we don't have to separate those two scenarios we can simply use this one it's one because when the i is greater uh greater than the second part right then this one will become to zero yeah i guess this will just work yep um yeah and time space complexity right so we have uh so we have word one and word two here right so that's going to be a uh basically that let's say the m times uh m plus and then of square right that's going to be the time complexity because the total length is n plus n and then to loop through the other possible uh subsequences right where the all the possible start and end events we have a on square and similarly for this uh for this one this is also like a off this one is like all of the uh this one is like n square right or m gram square yeah um right so i think that's it for this problem you know it's not that difficult right it's just that you have to be able to figure out i mean it's going to be hard to calculate the subsequent separately for both this left and right part so right now just combine them together because we after combining those with two words together we know we have a way of calculating all the longest subsequences right for audi the start and end point and with that we just need to do a little bit trick to make sure we only consider the answer when the uh when the palindrome right uh starts across exit across two parts so the way i the way we do it is that you know we just need to find the starting point and ending point for that for the palindrome and then the way how can we make sure the pattern don't start in the first element in the first word and end in the second element right so as long as we have a we have two letters right that equal to each other in both the word one and word two and then we know okay so there must be a palindrome right in between and then we can utilize the pre-processed pre-processed pre-processed dp array to help us quickly calculate the palindrome in right in between cool i think that's everything for this problem how to stop here thank you for watching this video guys uh stay tuned see you guys soon bye
|
Maximize Palindrome Length From Subsequences
|
sell-diminishing-valued-colored-balls
|
You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make the string.
Return _the **length** of the longest **palindrome** that can be constructed in the described manner._ If no palindromes can be constructed, return `0`.
A **subsequence** of a string `s` is a string that can be made by deleting some (possibly none) characters from `s` without changing the order of the remaining characters.
A **palindrome** is a string that reads the same forward as well as backward.
**Example 1:**
**Input:** word1 = "cacb ", word2 = "cbba "
**Output:** 5
**Explanation:** Choose "ab " from word1 and "cba " from word2 to make "abcba ", which is a palindrome.
**Example 2:**
**Input:** word1 = "ab ", word2 = "ab "
**Output:** 3
**Explanation:** Choose "ab " from word1 and "a " from word2 to make "aba ", which is a palindrome.
**Example 3:**
**Input:** word1 = "aa ", word2 = "bb "
**Output:** 0
**Explanation:** You cannot construct a palindrome from the described method, so return 0.
**Constraints:**
* `1 <= word1.length, word2.length <= 1000`
* `word1` and `word2` consist of lowercase English letters.
|
Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum.
|
Array,Math,Binary Search,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
2263
|
98 |
hello everybody welcome to another video on problem solving and today we are going to be solving a problem on lead code which is validate a binary search tree so you can see it's a medium level problem and let's just quickly go through the description and then we'll talk about that approach so we've been given the root of a binary tree and need to determine if it's a binary search tree or not now a valid bst is when the left subtree contains only nodes less than the current nodes key now let's just simplify that and let's see that uh if i am currently at 2 so all the nodes all of the nodes towards the left of 2 need to be less than it and all the nodes towards the right of it need to be greater than it so you can see over here let's see if this is a valid binary search tree or not so one towards the left of five is correct but 4 towards the right of 5 is wrong 4 should also be towards the left of 5 as it is less than it and if we just talk about this subtree 4 3 6 then this is a valid binary search tree but this entire thing is not so this is what a binary search tree is it's let's look at the constraints it says the number of nodes in the tree range from 1 to 10 raised to the power 4 and their values are ranging from minus 2 raised to the power 31 to 2 raised to about 31 minus 1. so that was all in the description now i'll talk to you about the approach so what we're going to do to solve this problem is if you look carefully at a binary tree the in order traversal of a binary search tree would always be ascending so let's just look at this tree for now and if we do the inorder traversal of this tree we start from one in order traversal for those of you who don't know what it is we go left uh first we keep going left then when no left is left we print the current node and then we go right now this is a really small tree to explain it but the inorder traversal would be one two three but as for this tree let's say that four was or anyway let's just do the inaudible of this tree so in order to reversal would be something like this first we'll go at one then we'll go at five then we'll go at three four and then six so that's what an inorder traversal is now in this case one five four three now this is not the ascending order but that and uh that's why this tree is not a valid bst so that's the property of binary search trees that we're going to be making use of to solve this problem now as i'm going to do the in order traversal recursively and i need to keep a variable prev i am just going to use this function provided by the main function because the main function will be calling this is valid bst and i'll just be using this as an initializer function so i'll tell you what that means i'll say in pref or instead let's say struct list tree node star prep and in this function i'll say pref is equal to null now i'll explain to you why i'm doing all this just give me a moment and i'm i'll be defining another function which would actually be performing this task for me which would actually be returning whether it's a binary search so violent binary search tree or not so i'll say bool validate and i'm going to say struct tree node star root and in this function we're going to do the actual work now the purpose of me defining this global variable pref is to keep a track of the last element that we visited the last node that we visited so that i can at least keep a track of whether we are going in the ascending order or not and this is my set this function i'll be using for setup and i'll simply return what my validate function returns so what this is going to do this function will initialize prev to null which will be used in this function now this prev i'm making it null because this function would be called multiple times and the previous calls value would still be stored in prev but whenever we get a new test case we get a new tree to validate we need to re-initialize the values we need to re-initialize the values we need to re-initialize the values we need to realize the value of our prev variable so that's the job of this function so it will initialize prep to null and it will call the function which will give it the answer of yes or no and it will simply return it to the main function so now let's get to the thing that we need to do we need to check if it's a valid binary search tree or not so as i said that we're going to making use of the inorder traversal so i'll just check if root of left and after this i'll say validate root of left and now this is not enough right now because if we validate the root of left and supposedly it is not a binary search tree and this validate functions returns us false then we don't even need to check the rest of the tree so i can just put an if condition over here which says if not validate root of left return false and that's the job of this if block it will ch it will validate the left subtree and now i can check my pref variable so i'll just check if prep is uninitialized then what i'm going to do i'll just say prev is equal to root so if previous uninitialized no problem we'll just initialize it else if prep of val greater than root of val now if this is the case which means the value at prep was greater than the value at root it means that the tree is not a valid binary search tree because according to the ascending order its the value at prep should be less than the value at our root so if this is the case i'll save return false and else i'll say pref equal to root now else means that the value of prev is less than the root and if you look carefully over here the condition said that the left subtree of a node contains only nodes with keys less than the node key now in normal binary search trees as far as i know the left child or right child can be less than or greater than equal to it can also be equal to the current node but according to this it has to be greater than or less than so for that i'm going to be putting an equal to sign over here which means if the value of prev is greater than or even equal to the value at my root then i need to return false so that's that and now we move towards our right subtree so i'll check if root of right and if it is true then we just say we i'll just put a curly brace over here and again as we did over here if validate root of right oh wait a minute i missed or not over here if not validate root of write return false and by default we return true so that's that and this function according to me should work fine i'm going to run the example test cases now and it has worked fine for the example test cases now let's go ahead and run it has worked fine for all test cases one time is 13 milliseconds and memory usage is 9 mb even though it keeps fluctuating then i have made couple of submissions before uh with very minor changes which should not make such a big difference so all that keeps fluctuating that's that and thank you all for watching and if you found it helpful do make sure to like and subscribe
|
Validate Binary Search Tree
|
validate-binary-search-tree
|
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
A **valid BST** is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** true
**Example 2:**
**Input:** root = \[5,1,4,null,null,3,6\]
**Output:** false
**Explanation:** The root node's value is 5 but its right child's value is 4.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,501
|
454 |
Hello friends, in today's video we are going to discuss Net Profit Addition 250. If you have not subscribed our channel then subscribe our channel. You will get good content related to date in easy language on our channel. Knowledge is less problem, Veer. 140 Hey Namaskar Subscribe Now Hey Zindagi This Number Subscribe What else is there that your hatred from name to name melts by consuming the number, watch some of them here, you must subscribe to this channel, subscribe 000 2030 10 quarters before this But there is a very good problem in calling this problem, here you have to do not forget to subscribe the channel, subscribe, do not forget to subscribe the channel, Namaskar, subscribe, definitely subscribe and you can easily subscribe for any channel. Subscribe to That war tentacles should be used equally to keep one length should people go okay after that what will we do if we so nice Vijay Krishna Shri Krishna flexible in 2013 scientists on Twitter should come for this extra work on the topic by combining your temples That's it, so your knowledge is surplus and you have taken something on all the posts, what will you do with the original hope? The benefit from Returns is that you have spent 4 more minutes, but when you are here, you are going to get work energy power from Middleton Ghanshyam Kevat, talk about this earlier. The paste will be specific to this piece. 1 You have not used any vector space but if you talk about message to time here then see what is yours here which is N is Ankita is 200 grams and if you go to perform then overall time limit exceeded Ghaghra this. You will have to optimize it only then to use it, you can think about how to cure cancer yourself, you can use it, you try what we can do, then you try it for 2 minutes and then you again see what we will see. How many entries are there for you and how soon will you get married? Okay, you can do this, what can you do to reduce any complexity? Okay, if you are ever scientific about taking Congress leaders, then if we can take it to both ends. That is, if you have tried to write, then you should request it. Okay, if the job is as per your requirement, then you can subscribe to their Tintin Adhir Veerwati Possible Combinations for Disposal to Graduate President. You subscribe, do not forget to subscribe the channel and also subscribe if You know that your duty is famous, but what are the tips like 10 inches? From here, if you find out its value objectively, you will get this if I told you that the tips should be equal to this, then you will get it for the festival - it is fine, festival - it is fine, festival - it is fine, what should you do? Apna Namaskar Hey Koi Read And Whatever Value You Mean Your Namaskar Whatever I Am - If you get a typical then what will it be, Am - If you get a typical then what will it be, Am - If you get a typical then what will it be, you will collect it from here, in which of these, when or in Ncube, there are many possible to Make Matters Of Pims Awadhesh You Want This You Swear Time 06 So For You Want To Pick A Number So A Number 90 Number Subscribe And Subscribe From Home Where Is The Person Coming From Garlic Why Invite Him We Think If you have all the possible combinations, it is okay at the time of Play Store, if I give you all these possible commissions, then you can generate. What I want to say in this is that if you swear on Play Store, then you will know from this. Your plus two class your what can we call it let's name it's okay if you tell this scooter all one know it all mix the purse then you its Chris Martin carplus miss you this and spread By doing this you can join it with yourself. Minute, I told you like this, X plus star plus insemination, what is it for you know Then you should always remember the habit of remaining to you, Sanam Surya Namaskar, their affair, purchase submission, according to them, as much as you like, taking out the stage time, then if you plus which art festival, whose branch art festival of quote - should be equal to of quote - should be equal to of quote - should be equal to On all possible occasions, if the suitable time is not equal then you subscribe me subscribe do not forget to subscribe the channel and subscribe the channel while leaving quick now remove your vansh group will get - but man shankar shambhu ke will group will get - but man shankar shambhu ke will group will get - but man shankar shambhu ke will get 10 You will get one minute of time to go to the front of the trophy. If you mention this and you will get time in the evening, then what is this 8 plus because all the possible combinations are there to add the meaning and convert it into goods for commercial sports. It is okay, do all the things of RSS as per your wish. If you take it out, you will get employment - One minus point to employment - One minus point to employment - One minus point to cash, if you take out something, it means, yes, you will get it, what will you get, compared to the time of two and 212, please, all groups. What do you say to the PCs you are getting by doing as much as its time? Message send a text message that I, if you like it gas ponting, you mean you should do it, then yours which is Aa 10516 I mean equal to SAT, if its cutting - equal to SAT, if its cutting - equal to SAT, if its cutting - add 101, more than half of yours which is 8 plus, art festival that despite this Their brushes are not artificial - once you have brushes are not artificial - once you have brushes are not artificial - once you have objected, you mean, your mention of Clear has been found, how has it been found, but 10 specifics are fine and from the economic point of view, this is the ideal of the index case, this is your mark Ayurveda India Friends, what will be your aa worth injection, minus plus two, you have a problem with the camera, zero, okay, now I have also said that before. What should we dip here and automatically become their manager or do you have zero question whether your money should be messaged to anyone, Barabani Dhakrani village did not find any crime among themselves, Ghrit himself has welcomed you, one message to you in some way. - 1 tablespoon message to you in some way. - 1 tablespoon message to you in some way. - 1 tablespoon oil 1 - Means so you - do its - you oil 1 - Means so you - do its - you oil 1 - Means so you - do its - you this method manner this present this you here ₹ 1 whose is J1 you got you made ₹ 1 whose is J1 you got you made ₹ 1 whose is J1 you got you made electronics instruments 2.2 plus electronics instruments 2.2 plus electronics instruments 2.2 plus minus 1.2 million and you should have been towards it minus 1.2 million and you should have been towards it minus 1.2 million and you should have been towards it - 24 - notice has been sent and - - 24 - notice has been sent and - - 24 - notice has been sent and - how is it zero snakes in r&d how is it zero snakes in r&d how is it zero snakes in r&d 9800 international school where vitamins are from - on plus minus plus you cameras are from - on plus minus plus you cameras are from - on plus minus plus you cameras passengers and - entry is done and now passengers and - entry is done and now passengers and - entry is done and now we give you pimples and what to do with your a little bit of this Do set a message according to decorates whose blood is famous in alarms and in me straighten all the chords in these times and you get all the forever here whatever you get included here okay Like this is ideal for you here, whatever it means back at that time, do it like what negative - at present is that through do it like what negative - at present is that through do it like what negative - at present is that through your first through angry then you have got from your okay then mix unknown its if you find yourself butter Let's see our team together to remove some simple Delhi, what will we do in this plus because as many Samsung as we all Bhind collector that you press because as many mills will be maintained see this now take horror films will protect you from Northeast and sculpture and From the problems of the victims, we kept it about ourselves, Meerut or what do you do, Adil, your middle of nowhere, you straighten all his personal space, it is okay if you have to overcome the passion of 8 plus admission today, how come you have spent so much time, okay you do this Write money on this thing, what is yours, now we will talk about this by drinking nectar at the time of plus two because one of us said ok and hello to you sad hello to you so keep it if you are around then what request will I make to you at your house If you meet zero then I have set that you will definitely get it, so how to always do negative and plus m0 - 4 minutes negative and plus m0 - 4 minutes negative and plus m0 - 4 minutes against this of children that you have negative for - - - till you have a printer that you spread - - - till you have a printer that you spread - - - till you have a printer that you spread it to your account Video then subscribe to the Page if - 4 - then to the Page if - 4 - then to the Page if - 4 - then add me to your group till he goes on Twitter. Okay, there is a meeting to return from the last one. If we talk about low level after filling, then the company is going to be only ₹ 10, then the company is going to be only ₹ 10, then the company is going to be only ₹ 10, just forensic. Why did the lab generate all the stomach's possible on its permission and also tried to find its cyber space and inches and you can see send your time to talk, meanwhile what is the space weakness of Congress, what is going to be the match All the total wares you had gone to BSP amongst yourselves. Delicate and Sacrifice, through you said that Anurag Muskaan is georgette fabric, so you are possible pace of your fans in the unit, your sixth house is fine, your face has been messaged, it is veins. I will return all my cords to Marathi Chavat Office Collection itself in the year we started the last rites of daughter and shampoo first so if you did not face any problem then comment is definitely a very good plan very stand problem with you. If you like the video then like this video and subscribe the channel your friends this page thank you for watching my video next meet take care by the fact that it is a
|
4Sum II
|
4sum-ii
|
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
* `0 <= i, j, k, l < n`
* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\]
**Output:** 2
**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0
**Example 2:**
**Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\]
**Output:** 1
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `n == nums3.length`
* `n == nums4.length`
* `1 <= n <= 200`
* `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
| null |
Array,Hash Table
|
Medium
|
18
|
55 |
day 25 and the problem is jump game it's lead code problem number 55 and uh we will see at a solution which is order and time and order one space complexity so first let's understand the problem so we have some blocks or you can think of them as an array of numbers and these numbers are non-negative non-negative non-negative and these numbers denote jumps so non-negative jump means non-negative jump means non-negative jump means you cannot jump in this direction so either it can be zero or greater than zero so if it's zero and you are at a particular step then zero means you are stuck here if you reach here you are stuck here you cannot jump any further but if you are at a step and let's say jump size is 2 then you have the flexibility to jump maximum up to two steps so if there is one block here and one block here you can jump till here or you can also jump here so you have the flexibility to jump zero step one step two step all three so zero one two uh why will you jump zero because it may be the last step then you don't require to jump so you will not jump so uh let's see two examples one positive case and one negative case just to uh understand the problem much better so you will always start from first step so you don't need to jump to reach the first step so one direct thing you can uh consider is that if there is only one step then no matter what is the value you will return true so there is just one step and you have reached the last your goal is to reach the last from first to last not cross this even if the last one is zero it's fine you have to just reach here from here so let's say from two we can jump two steps so we can come here and we can also come here now which one we will actually take will depend later maybe that from here there is a direct jump to four but from here it's zero so if we come here we will be stuck so it's not the case that we always take the longer job that is not the case and from here we can jump one step two step three step so in fact we got our answer here itself we will from two i can come to three and from three i can jump to four so there is a way of jumping from two to four there will be multiple ways in fact you can take one jump also here one then again jump by one step from here also you are allowed to make one jump from here also one so there will be multiple solutions but you have to just return true or false whether reaching the last uh step is possible or not now let's look at this negative example so here you see 0 that means if you ever reach here you are stuck so from 3 i can come to 2 1 and 0 from 2 where i can i go i can go to 1 and 0 so you see from 3 as well as 2 i cannot advance beyond 0 so 2 did not improve our solution we are always trying to find the maximum where i can reach so from 3 maximum i can reach till zero from two also maximum i can reach till zero and from one i have just zero or one jump possible so maximum i can reach till zero so we are iterating the array from left and moving towards right and we are trying to find what is the best or farthest i can reach and you see that we are not able to cross this barrier and uh from 0 we cannot take any step so we are stuck here so there is no way of reaching 4 neither from 0 neither from 1 neither from two neither from three and uh how we are keeping track of this when we visit a cell or step we see what is the maximum i can jump so for example let's say we have three and then we have one and one so from three i can go till here obviously i can also go here and here then when we come to one we will see if we can better this solution that if we can reach any further so from one we can reach still here so this one does not contribute anything because wherever we can reach from this one we can also reach from this step so this is not contributing anything and similarly when we come here so the max still remains this zero one two three so we keep track of a max reach when we are traversing this array from left to right so initially to a when we reach here 3 then max reach becomes 0 1 2 3 4 so max reach is 3 when we come to 2 we see that is it better than earlier and how we find so this is the index i the current index or this index i and we see what is the value of this step the value of element at this position and that denotes the jump so from i if we are at is step i and the value is 1 that means i can reach till i plus this array is a i plus a i this denotes jump so we compare if i plus a i is more than existing max reach then only we find found a better solution so in that case we will update max reach equal to i plus a so from 2 it's 3 so we don't update when we come to 1 i is 2 plus 1 is 3 still not better so move ahead and now we see i is 3 so 3 plus 0 is 3 so we are not making any progress and we come to 4 now i is 4 and max reaches less than i so the termination condition will be that after this calculation step we compare if i is equal to max reach that is from ith index the maximum index i can reach is i itself so what does this condition denote you understood it so from index i the maximum further i can reach is itself that is i cannot move even one step further if mac if i can even take one step then max reach would be at least one more than this current uh index i but that is not the case so from i cannot move further and i am stuck so i will stop this iteration whenever we encounter this situation we will not check for further because there is no way to move further from this index and after i stop the saturation i check whether max reach is uh more than this last index or not more than or equal to this condition will also be reached when we are at the last step and the last steps value is zero so if this value is zero then also this condition will be reached so we will stop this loop and finally we will check if max reach is till this index or more then it's true otherwise it's false so let's write the code for this first i will write it in c plus this then uh modifying it for java and python would be very trivial max reach equal to 0 then we loop if nums i plus i this denotes maximum i can jump from the current index if this is greater than the current solution current best solution then we update it else whatever was the previous best will remain there and now the second check we will make if max reach is equal to i that is from ith index or the maximum i can reach is the current index itself that is we are stuck so we break and this loop ends we will stop checking further and if this condition did not occur or occurred at the last step then we are good to go so we will return max reach greater than equal to norms dot size and let's try it and it works for this case let's take the negative case also let's add few more cases one zero so this should be true now let's add one zero this would be false from here i can go to layer and i don't need to take any jump so whether it is zero or more it does not matter and we can confirm that with this both are equivalent so it should return uh true false so let's run it so our expected answer does not match it so let us check y in second it's returning true okay so this is the mistake this should be i not one and still it's wrong for this case third case one zero so let us check uh so it should be greater than equal to num psi minus one not uh index starts from 0 and goes till num size minus 1. so if we reach there it's fine so that was a mistake so let's try again and now it's same as expected so we have checked for five cases we are confident enough and we will submit we also found a few bugs in our code while running test case so this solution is accepted so let me copy it for java and paste it and this we will replace with length and same here other things are same in java so let's go ahead and it works as expected let's submit and the solution in java is also accepted finally we will submit in python 3 max reach equal to 0 and for i in range lin nums and let's try to run it if it compiles then it will be accepted as well so it compiles and works for our test case so let's go ahead and submit this solution in python and this solution is also accepted so i hope you enjoyed the solution you understood the solution and what will be the time complexity we are just making one part of this list so the time complexity will be order n linear time and space we are using only some constant variables order one space complexity
|
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
|
65 |
hello everyone welcome to codex cam we are the 15th day of mail etc challenge and the problem we are going to cover is valid number so the input given here is a string which consists of a number either it can be an integer or decimal we have to return true or false if a number is valid or not so let's understand this problem with an example so there are a lot of conditions given the problem statement to understand whether it is a valid number or not so let's go through the conditions one by one in order to approach this problem the so the first simple rule given here is the valid number can be an integer or decimal so let's start with integer as it is having a very less number of conditions so if it is an integer it should have at least one number so such a basic condition so at least one number means it can be one number or one two three or any number of digits it can have and plus or minus sign is optional so next moving on to a decimal number should have plus or minus sign it is also optional again and the second rule given here is a dot should be followed by any number at least one number or a dot can be followed by a number that is simple a number followed by dot or dot followed by a number so it is not necessary that it should have a number before and after dot so without any number before and after dot is also allowed or it can have numbers on both the ends that is before dot as well as actor dot so now other optional thing is e that is exponential value after the decimal point so now we have seen the valid cases so these conditions says the number is valid we have also need to know what are the invalid cases to approach this problem so here comes the invalid cases so the first example given here is 99e power 2.5 this is invalid because power 2.5 this is invalid because power 2.5 this is invalid because after e that should not be decimal so actually it can be a whole number either can be any of any digits it should not have a decimal or a plus or minus sign so this is invalid so that's why the first case is invalid moving on to a second case which is -6 second case which is -6 second case which is -6 obviously it is having more than one sign either it can be plus or minus it should have only one sign that two at the index 0 and moving on to case 3 again it is similar to the previous example and moving on to case 4 abc it doesn't have any digits or e it just simply alphabets or string so it is invalid moving on to the next condition again only is allowed in case of characters is not allowed moving on to our next example one e so is allowed but it should have digits after e so after and before e as well so it should have at least a single digit after either it can be 7 8 or whatever or any number of digits but as we saw in the first example it should not have a decimal point or plus or minus sign and the next example is e3 again as per the previous example it should have a number before e and finally one e3 it is having more than one e it should have only one e as per the problem statement so here we have seen invalid cases as well so how are we going to approach this though this problem is having a lot of conditions to confuse us but this is going to be a very easy approach by using these two four variables so this four variables are boolean variables which is going to have the values true or false based on the conditions or the characters given in the input string so first variable point present is nothing but if there is a decimal point present in the given string then it is going to be true so whenever we pass the string or i trade the characters in the given input string for the first time it encounters a decimal point it is gonna be updated to true and e present is similar whenever it's c e for the first time the given string then it is going to become true if not it stays false and number present whenever it see the number first it is going to be true and number after e is going to be true for the first time itself i'll let you know why later so now we are going to iterate through a given string character by character and update these four variables and apparently we are going to check if any of the condition is pointing at the invalid number if it is an invalid number then straight away we are going to return false if not if the iteration is completed and there is no false returned in that case the number is true which is a valid number and we are going to return true so what are the conditions we are going to check here is first more than one decimal there should be only one decimal point in the given number so if there is more than one decimal point we are going to return false so how do we find there is one more decimal point so point present is going to be false initially and whenever first it encounters a decimal it is going to be true so when it encounters a second decimal point it is going to check this condition whether point present is true if it is true which means we have already have a decimal point in that case we are going to return false so the first condition is over moving on to a second condition which is decimal actor e it is again going to be an invalid case so how we going to check that so whenever there is an e that is e present for the first time it is going to become true so in that case when there is a decimal point is being encountered it is going to check whether my e present is true or not so if it is true in that case we are having a decimal point after e so we are going to written false again for this case so overall for these two cases whenever there is a decimal point we are going to check whether there is e present already and point present already if any of these conditions become true then we are going to return false so moving on to our third condition no numbers before e so whenever we encounter a number for the first time the number present is going to be true so when we encounter e in our given string we are going to check whether number present is true which means it is having a number before e if not if it is false in that case we are going to return false to this case and moving on to a fourth case which is more than one e so again e present is going to be true when it see a e for the first time so when it encounters one more e in the given string and it is going to check whether e present is true and if it is true then it is going to return false so overall for these two cases whenever it encounters e it is going to check two conditions whether number present and e present if any of these conditions are going to be true we are going to return false so hope you are making it up to this so moving on to our next condition which is plus or minus sign in between so we should have only one plus or minus sign at the zeroth index only so if there is one more sign in between and it is not at index 0 then we are going to return false so plus or minus sign after e so whenever we encounter a plus or minus sign we are going to check whether e present is true which means we already have encountered e in the given string which means we are having a plus or minus sign after e so in that case it is going to be an invalid case we are going to return false so yes we have covered all the invalid cases so finally it's time to return true since all the invalid cases are crossed and we have to return true that the number is valid so i have said number after e is set to true for the first time so we set number after e is equal to true whenever we see a number in the given string so in that case if there is a number 4 5 e 5 so whenever we see 4 5 we update both number present as well as number after e present to true and when we encounter e we check all these invalid conditions and also update number after e to false which means so for whatever it has been updated whenever it saw a e it will be updated to false so when it see a number again it is going to update number after e to true which means there is a number after e so this is going to be a valid case so that is how number after e is going to work so hope you are understanding this approach so we are going to iterate the given string only once and so it is going to run and we go of n constant time so let's go to code now so yes here is our code we have declared all our four boolean variables where we set number after e alone to true so as discussed we have checked all these six cases that is if it is a number we are going to update both number present and number after e to true if it is a dot we are going to check whether already e is present or already uh decimal is present in that case they both are going to be an invalid case so we are going to return false if not we are going to update point present is equal to true same way when e is encountered in the given string then we are going to check whether e is already present or number is not present in that case it is invalid k certain false if not we are going to set number after e to false and e present to true and finally coming to the plus or minus sign if the index is not is equal to 0 then we are going to return false or if the previous character is not is equal to e then we are going to return false and finally we are going to return with the number present and then number after e is true which means number present both in front as well as back that is the reason we set number after e to true at the first line so yes that's it let's run and try so let's submit just let's submit yes a solution is accepted and runs in two milliseconds so thanks for watching the video hope you enjoyed this work too if you like the video hit like subscribe and let me know in comments thank you
|
Valid Number
|
valid-number
|
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the following formats:
1. One or more digits, followed by a dot `'.'`.
2. One or more digits, followed by a dot `'.'`, followed by one or more digits.
3. A dot `'.'`, followed by one or more digits.
An **integer** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One or more digits.
For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.
Given a string `s`, return `true` _if_ `s` _is a **valid number**_.
**Example 1:**
**Input:** s = "0 "
**Output:** true
**Example 2:**
**Input:** s = "e "
**Output:** false
**Example 3:**
**Input:** s = ". "
**Output:** false
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
| null |
String
|
Hard
|
8
|
490 |
hey everybody this is Larry this is me doing week uh three week three of the liquor premium charge hit the like button the Subscribe button drop my Discord let me know what you think about today's Palm I'm going to sneeze give me a second oh man I'm like in between sneezing so give me a second uh or you know fast forward a little bit all right maybe not maybe I lied I don't need to sneeze like now I'm in between anyway this week's bomb is fun I need the maze seems like it's just a maze Farm which uh we'll see if it's you know usually is at this level is breakfast but we'll see there's a boring Maze of empty spaces and Wars as one the book and go through empty spaces one up down left or right but it won't start I feel like I've done this before but maybe it's just another one but um uh but yeah so for this one there are a couple of things you can do um in a war so that's not possible okay yeah you could pass through without stopping that's what I was wondering um there's two things you can do like I said there's uh BFS or you could do uh diystra um and it's just about being careful about your simulation um I mean I think one thing that you have to be careful about is making sure that um making sure that you don't do anything uh expensive uh by accident right like it like I think one thing that I mean I don't know how to construct this exactly per se uh but you can imagine there's a case where you know there's a the boys here there's a long Corridor and the goal is here and then you just go from left all the way to the right uh and then you simulate it but it also simulated for here and then somehow it gets to n Square I know that this is not exactly that case because you have to be you cannot stop but in theory that is something that I would think about right um but yeah for this you can also use breakfast search because you can just use um uh there are two ways to write breakfast search I guess one is by cells where you can use this zero one uh bfsq or you can you know uh do some pre-calculation can you know uh do some pre-calculation can you know uh do some pre-calculation with respect to where the ball goes and then do a BFS on that graph right it's almost like a dual on the current graph um it's just that when you do that like I said you have to be careful that you don't um yeah you just have to be careful about it and I think in that world it's possible that the more use case uh edge cases as a result uh so it's a little scary but not impossible I guess RNC after considering the 100 square which is like ten thousand so that the Dexter is going to be good enough dice yeah so let's do it yeah uh let's see what am I doing I just want to find a ball first now the ball they tell you the boys and the destination okay fine I like my own way of course definitely uh starting n is what I call it but uh yeah so then we can do something like yeah let's just do that I don't know uh and then we're going to hit Q hit push um zero is the distance and the direction will be also zero for no Direction maybe negative one for time I don't know uh because the idea that we I wanted to do is that I keep the direction in the state so that you know if it's moving yeah it has to keep moving so we do it one cell at a time otherwise um yeah otherwise uh you may kind of redo that math because you can think about a way in which I don't know this you could do like a step ladder and then kind of keep on going uh and then that would make it end squared you're not careful so I don't end squared even in this case is 100 I don't know but uh but yeah but what's up directions it doesn't really matter uh the order doesn't really matter is what I want to say obviously we need something like this uh and then uh yeah because I want to think that just has no Direction so maybe just negative one is fine let's see so um so a distance that's why and Direction let's go to this I guess that's a thing we'll just do that uh and we want to set up the thing for the distance right and now what we have to do is uh they stream our way out but first we should check that if distance of x y and then we have to set this a little bit and I forgot a dimension so I guess we're using four makes more sense there this is greater than this oh wait what uh yeah whatever just because this is great and distance if the other way around then we continue if X Y is equal to the end destination then we could also return the D which is the distance uh on behalf of we spot this correctly and yeah oh wait don't this is only if D is equal to four right because otherwise you can change direction uh being very sloppy here um Okay so yeah if it's equal to four we get a new Direction so then now if distance of NX and Y and um uh is greater than D plus one yeah it's plus one because now we're setting a new Direction then yeah then let's put it in uh okay and then we'll put on the Heap uh t plus one otherwise we just keep going forward so uh t x d y is equal to uh directions of d right and I guess we do the same thing they have a copy and paste but yeah I don't know I don't have to go about it and of course you can combine these if statements that uh yeah how can I find let's do it then in this case though it's not D plus one because um because we don't you don't add one you just keep going straight so yeah that makes tea again this is not D this is um now this is the but this is distance okay wow I mixed naming stuff is hard and when you miss name stuff this happens so be careful okay uh yeah and then this is distance because we don't update the distance we don't need to and then we push on the sheep though this is like uh put it on the next thing oops right oh and we have to I actually lied because I forgot to check for uh the words I always forget to check for the words I mean it's a easy ad but I just forget to do it sometimes so it's one right so Maze of NX and Y is equal to zero otherwise we don't go uh and also this as well now this one I needed to do an if statement here I think uh that's why I separated it but I forgot um the reason is because now then we can do else because if it if this constration constraints don't hold they're about to stay where we are and then we choose a new direction right so that means that uh else the distance of x y and then now we have four is greater than distance then now keep in mind doing that right and that's pretty much it otherwise oh I hmm I just realized this is a Boolean question so I kind of overdid it a little bit uh with the distance so we don't even need to return the distance this actually makes it a lot easier because then now we really should have done BFS then uh but I wasn't paying it I just kind of missed it to be honest I don't know why I mean I dismissed in my head I mean I don't know um oh man did I that's why that's the other thing I don't know the other places I did okay just that person uh I always forget about this because it is a really awkward use of um like there should be a first class hip object but it is what it is uh oh I can't do this has to be I didn't know that I had to think about it but uh but then I just forgot as I was doing it all right there you go um but as you can see Easy Flex but as long as you have the right kind of internal modeling for a problem but uh I forget it's true for us otherwise I may have done it the other way anyway let's give it a submit all right well I just kind of oh my God I don't know that's why my time is a little bit slower but that's fine uh just a complexity here right well I mean you know this is just standard dystrom so he's going to have standard day sure uh complexity which is uh was it you like we well technically you like you the way that we're doing it but you know the E gets uh oh no I think I said D because I am confused uh but actually the number of notes is actually R times C which is the size of the grid which is quadratic in that way but it's not quadratic in the size of the input um it's going to be re-log you still uh um it's going to be re-log you still uh um it's going to be re-log you still uh Vlog V depending how you want to Define e because Yi well in this case e only has only up to four edges for each node so you know up down left right and maybe new direction to five edges so G in this case is going to be another read even though even if D is V Square it you know the log takes care of it but for each node we or for each vertex in the original graph there's at most five nodes in the new graph and therefore it's gonna be real argue because we process that you know this Loop Loops once or five times at most for each original node and each of them does you know at most five uh we have near five uh hip operations which is um you know log e um uh yeah but like we in this case perhaps the better you want to say but yeah uh that's what I have for this one let me know what you think this is your standardized straddle uh I took a while typing it out and making silly mistakes but in concept it's not so bad uh yeah let me know what you think I did that I didn't end up sneezing so I don't know uh but yeah uh let me know what you think stay good stay healthy it's a good mental health have a great rest of the week uh I'll see you out later and take care bye
|
The Maze
|
the-maze
|
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return `true` if the ball can stop at the destination, otherwise return `false`.
You may assume that **the borders of the maze are all walls** (see examples).
**Example 1:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\]
**Output:** true
**Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right.
**Example 2:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\]
**Output:** false
**Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
**Example 3:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\]
**Output:** false
**Constraints:**
* `m == maze.length`
* `n == maze[i].length`
* `1 <= m, n <= 100`
* `maze[i][j]` is `0` or `1`.
* `start.length == 2`
* `destination.length == 2`
* `0 <= startrow, destinationrow <= m`
* `0 <= startcol, destinationcol <= n`
* Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
* The maze contains **at least 2 empty spaces**.
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
499,505
|
1,008 |
hey what's up guys chung here so this time let's continue our trade journey unlit cold and so we're gonna talk about this number one thousand and eight right so construct binary search tree from pre-order binary search tree from pre-order binary search tree from pre-order traverse right so what does so you're given like a pre other array coming from traversing the tree so basically eyes for example this one right so you do a pre other favors eight five one right then pre other is the left I'm sorry pre other is the route left and right root left and then right seven right and then ten twelve right so given the pre other traversed way and then your you asked to construct a binary tree based on this pre order traversal a right so how should we do it right I mean so I think it's obvious that we need to catch the node one by one right so basically first we get note eight right so for pre-order we get note eight right so for pre-order we get note eight right so for pre-order that the first one is the first one will be the root node right and then we check the second array on the second element in this array which is five right so the five will be which had where we should put it right so we put it on to the left of the eight or right out of the root right so how can we check that right I mean and then we just keep going down the way right so we just to do it recursively right so we to do five and then we just pass it down here and we do one we do seven right way to ten right oh so it's a recursive idea here so usually when we construct a binary tree we can create the helper functions and then we pass the lower bound and an upper bound right basically we only as and every time we see a node we cut the cartel bound in two to half right into this side and that side inside into that and that's time like this is a lower high right and will and when we see a new node we use the level usually we use the value on this node and we call it to the left side and right side and then with this range here so we only place we only pick the next number right we only pick the next number when the number is busy in the current range otherwise we just skip for example here right so let's say the is eight or so we initialize the lower bound higher bond with the then the smallest number and the biggest number right and then we go we try to we go to left right the left side will be lower bound and plus the to the eight here right we see and then we check oh five HDL okay five is the is in the range and then which so place we just get five and then we had a move this index forward to what right and then we see a left and right so we have another left and right here let me see the left here because we have left version and then right so when we see one okay why is also in the left side so we place one right and then the it's time right so one is the end once the end of the node and then we check right so with one in the end we still want to we still need to cut it into half right on the left side and right side so the right side is bounded at five right here all right it's five and then five here and the next one will be seven right so still we check eleven right if the left side is has the if the 70s and in the lab side no it's not is it in the right side no it's not right because the seven is even bigger than then that an upper bound so this happens right it will hope will both return now right and our index is still pointing to seven and then goes back here check on this side right it's 700 on this side yes it is right because on this side it's bounded at five to eight right to eight here and seven is when Z is in this range so every time when we see the current note the current index value is within the range and then we just move the cursor forward we need to keep going because once the sevens finish right the next is 10 right and then we check Tia and this recursion is done right so seven is done and the we will continue with seven right and the next one will be seventh 11 right so sevens left at ten it's obviously not in is not within any after not within the idea of the range here so it will pause return none and then we'll keep back going back to we'll go back to eight here and then we go to the right side and so on so forth right in the end we'll have this complete binary tree okay so we're gonna have a helper function here like weeds like reset and this wrapper function will have like a lower bound and higher bound right I'll just use it low and high here and we also need to create like define a global index here I mean we can also every time we can just pop these things for the left side but I think which use an index to avoid modifying the parameters here and then and so here basically with three turn the helper functions here right so we have to initialize it to the max size and yeah so okay so first what do we check here right so if the index right if the index is we can also do like a length here of the pre-order because we want to know when pre-order because we want to know when pre-order because we want to know when we reach we have traversed odd other elements in the array all right so if index is equals to the end here right then we know it we already traverse we already process all the nodes what why not a minus one because a minus one is the last node right we still want to continue here right so return now right but basically we just return with the stop right and then like what we discussed and we'll get the current value right so the current value what's the current value that's the pre-order array is a current index right pre-order array is a current index right pre-order array is a current index right that's a current value we have and we check if the current value is not if it's not in the range right so basically if the current value is smaller than the lower bound or current value is greater than the upper bound right and then we know it's not a valid one we just simply return right we return now here because I'm D that means down the on this side left side our life and right side we all will reassign none for both all right so if it if is it is in the range right we just the two basically we just do another chat we just I work will create a note here with the current value here right because then we know we can use this value to create it to create a tree note here and the current value right and then we know since we already use this one the current values to create a node we need to increase the index by 1 here and then we just do it recursively right note this helper right so lower current value right current value goes too high right in the end we simply return the node here which is the current node the logo index here why is empty yeah I'm sorry here should be laughing right so basically what we're doing here we try it for both the left side we tried for both the left array order the right of the right sub-tree and with the updated bound here sub-tree and with the updated bound here sub-tree and with the updated bound here just to see if we can place the next other in the next number in this pre-order array to the left side right pre-order array to the left side right pre-order array to the left side right and then if it is we just stop right and if it's not cannot be placed into the website and then we try to the right side with the update it means the update is bound here right it means because if it is even the place in here rather than the next one it will be try will try it that knows the laughing right with this with the next know with the next number again right and then it skip go to knit and here we are we have consumed all the outnumbering this pre-order array and then let's run it pre-order array and then let's run it pre-order array and then let's run it yeah okay so it passed so basically so what we're doing here to recap what we discussed we use this lower bound and upper bound so many times when we construct a binary tree we always use this lower bound upper bound because we with this lower bound upper bound we basically we know right with the left side we know we can only use the node if that node is a busy in this range right we start with the right subtree we know that the same thing we have to be each node has to be within the same rank with this correct range here right if it's not in a range we just simply do not pick anything from the from this array here right basically and then if it's a valid one node then we just create a free no by using this the next value and then we just keep moving this then we already process the current one we just you know move this induct forward and then we try other possible other possibilities for the left for the right and then skip go to Nate and until we reach the end of the Ring alright cool guys thank you for watching and I think this gonna be no I think I don't know if this is going to be the last three videos or not but I think I'm doing this like this is problems by it by the categories or by tags I think I'm pretty I already done a few of many three problems so I think most likely I'm gonna stop here if not here well maybe there's gonna be another one so and then after that I think I'm going to move to the graph yeah okay cool guys thank you alright see you guys bye
|
Construct Binary Search Tree from Preorder Traversal
|
binary-tree-cameras
|
Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**.
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Hard
|
1021
|
103 |
249 Welcome back to my channel. In today's video, the name of the oath we are going to call is Bionic Pimples and what will we do in it in the previous, we will do the same as we did with the battery level, the objective was sugar, just one more thing and we will maintain the information power level. The name is fine, it is going to be different from everything else, we are changing it accordingly, let me explain to you the meaning of Mukesh, first of all you do one thing by going on the open board, go and watch the videos of 'Em Able To Travel' on our channel, friend. watch the videos of 'Em Able To Travel' on our channel, friend. watch the videos of 'Em Able To Travel' on our channel, friend. Because definitely understand the singer will make a small change and it will also become clear that medium texture is the problem, that was the feedback problem, then watch the subjective video and then come to this video, then you will understand the batter, then without any delay let's go and start. Let's do it, so friend, I have copied the same thing on my wall, I am fine with criminal reversal, I will understand a little, let me tell you the changes, what will happen in it Jack, let's go, what happens that this is park inspector Yudhishthir, then he will do something like CEA wanted so much. According to kilometer 90 butt will be mentioned and vice versa like first straight fruity then straight but reverse then 90 straight then next thought reverse rule also city immuno one and a half children one to-do list also city immuno one and a half children one to-do list also city immuno one and a half children one to-do list till maintenance level is good then like we get the route So Rotan because we will put it in the same level, just assume that we are waiting for the level, come to the room, rule is given, stops and removes the remote, it is okay, when we reach Shimla, there is a new list because I List of Minister of India has to be returned. Okay, so while going to every level, we will create a new list, give the list, select the person in it and run it. 90 next blue members are at level 128 and then this is a little more level, keep it in the camp, Atru. And then the phone will go to the office, we are coming in reverse, okay, so what will we do if we come to the level, remove 9, select that one, if there is no chillum, then remove one, go on it, network security question leads 07, okay. And let's put these nine in it, A bell is also smart with the idea of butt level, so if A bell is also smart with the idea of butt level, so if A bell is also smart with the idea of butt level, so if we do research in it, then what else do I react, so Anti and North, one more Noida Bheem, okay, then we will move to the next Bluetooth setting. Remove that light, there is no question, subscribe the channel, there is a question, how did we continue to grow together, 15471 was taken away, the reader was taken tow, took the proof of address and got subscribed, so what will we do now, turn off the gas flame. If you give then this is going to be some answer, I hope you guys are being sensible and are running basically alternate, first handing over the level petrol to the batter from phase 3, then the force will maintain the level of the engine type and accordingly we will reverse the rest of the exact dates in The plural traversal is this portion, so without further delay let's go and see the complete CCR. If you my old binary level roadways driver absconding from the spot, you will feel like a big person. Look at the play list. Play list. American had to do it. We made one. Lee, then after checking, if there is no bread tomorrow, then make a blank list in it. Why, because we start, because we put it, and then why are we not making the list by putting it through the sea, then why do I get routed out and in the form of teenagers. It was happening that you had started it in the road, this also sir took a poor level, started from the fall, will start by posting the post, then the investors then put the loop till the size of why, took out the size of the particular level and got the particular red fort. I flopped, then what to do, luck is better and then placement is done, today we are ready to remove and after making the list, started checking the level, it is 1182, so reverse, if there are poles, then I will not reverse, okay, by going to the last, which is done by Laxman. On double, we used to add it to the laptop interior and change the level, see this, pause it, take the result, friends, if the nation of level is uncertain in the last and last, then in this arena and if the level is maintained, if you have done it then exactly this. I was asking with affection of Banerjee level product reversal that if you want level travels at that time, then you will get this halwa, I will show you the food by throwing the sun's frustrations, after doing time, I will show that solan sound science experiment tikulia code accused match gets a draw. Next video trick from you guys, I have checked a lot of videos and many more are yet to come, so what is the wait, subscribe the channel and like the video, it will come in the next video.
|
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
|
871 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 871 minimum number of refueling stops before we read the question prompt i would just like to kindly ask you to subscribe i have the goal of reaching a thousand subscribers by the end of may and i need your help to get there the more subscribers i have the more videos i can make and the easier i can make it for you to get into fang so please subscribe it helps everyone now let's read the question prompt a car travels from a starting position to a destination which is target miles east of the starting position there are gas stations along the way the gas stations are represented as an array of stations where stations of i equals positions of i fuel i indicates that the ith gas station is positioned i miles east of the starting location and has fuel eye liters of gas the car starts with an infinite tank of gas which initially has start fuel liters of fuel in it uses one liter of gas per mile that it drives when the car reaches a gas station it may stop and refuel transferring all the gas from the station into the car return the minimum number of refueling stops that the car must take in order to reach its destination if it cannot reach the destination return minus one note that if the car reaches a gas station with zero fuel left the car can still refuel there if the car reaches the destination with zero fuel sorry yeah if it reaches the target destination with zero fuel left it is considered to have arrived so how can we do this let's look at an example and then we can think about what algorithm we want to use okay so we read the question prompt now let's figure out what a solution might be so we have this problem where we're given that a target is 100 miles away we've started with 10 liters of fuel and we have stations where the first station is 10 miles away or 10 yeah i guess it is miles and it has 60 liters of fuel the next station is 20 miles away and it has 30 liters of fuel the next station is 30 miles away and this is 30 miles from the start point not from the last one um and the last station has 60 uh miles away from the start and it has 40 liters of gas so what can we do here well we start you know say at this is where our start is uh so this is really like zero and then we're going to end here at 100. so what we can do is we know that the gas station here at 10 there's a gas station here at 20 there's a gas station here at 30 and we'll say 1 here at 60. so we use our 10 liters of start fuel and we arrive at the first gas station at this point you know we started with 10 liters of fuel but we used 10 liters to get to that first station so we have to fill up here so we're going to take all of the gas here so now we're going to have 60 liters and what is this going to do obviously we can't reach 100 because we would need still 90 to go so at some point we need to fuel up so that means that essentially what we can do is we can go all the way over to the 60 which is going to consume 50 liters of gas so we'll be left with 10 and then to get the last 40 what we need to do is we need to fuel up at the 60 get its 40 liters of gas so we'll get 40 extra we'll now have 50 and we can arrive at our 100 and we'll be good so essentially we'll have fueled up twice we fueled up at this 10 and we fueled up at this 60 so that would give us a total of two and that's what we expect for this one so how might we actually solve this well in the real world you can't go back and refuel after you've you know passed the gas station if you're already out of gas you know theoretically if you still had gas you could kind of go back to the gas station but in this example um we're gonna get to a point and we run out of gas so we can't go back but since this is elite code problem and not real life what we can actually do is we're going to use a greedy approach here and we're going to try to go as far right as possible and hope that we can reach the end with our current amount of gas that we have and if we ever hit a point where we actually are out of gas completely well we don't have to worry what we can actually do is we can just keep track of the largest you know gas stations that we've seen so far and we're going to pretend as if we had fueled up there so we'll just take them in a greedy manner so we'll try to go as far right as possible greedily and if we find out that we can't do it then what we want to do is essentially just pretend like we had fueled up there and then continue pretending like we had so basically we'll just exhaust um our fuel ups as we go and we'll take them kind of like in a greedy manner and the data structure that we're going to want to use here is actually going to be a heap and the reason that we're going to use a heap is that way we can have access in constant time to the largest gas station in terms of you know liters of fuel that it has so we can take it greedily so for example what we want to do is let's build a max heap right so we'll call this uh heap and it's initially going to be you know initialized to guess an empty heap so what we want to do is we want to go through our you know uh i guess input here from left to right and what we want to do is we want to you know basically see how much of our tank it would cost to get to the next station so we start at zero and to get to the first station it's obviously going to take 10 miles so our tank which is starting at 10 we're going to use 10 so minus 10 we'll have zero so at this point since we have zero but we're also at a station what we can do is actually just refuel there so we can take the 60 and continue so in this case we actually don't need to add anything to the heap because we got to a station we were able to refuel there the only time we want to look into the heap is actually when we're between stations and we should have refueled at some point in the past so now we're here and we've gotten 60. so we get to this station and we don't need to refuel yet because getting to 20 would have taken you know only 10 liters of fuel so we have 50 left but remember we want to keep track of all the gas stations that we've passed because we want to in the case that we need gas go back so we're going to add it to the heap and say that we had the option to take 20 but we didn't so now we go to the next gas station and essentially we're just iterating over all the gas stations here so we get to the next one and we see that it was only 10 miles from the last one so that means we use 10 liters of fuel and we're still good on fuel we haven't run out so we can refuel here if we want but again we're doing this in a greedy manner so we're just going to try to go as far right as possible but we can also add to our keep the fact that we've seen a gas station with 30 liters so obviously when we try to add 30 to this heap it's a max heap so the 30 is going to come first because obviously the top of the heap is always going to be the largest element so now we have 30 and 20 in our heap now what we do is we get to this 60 gas station which was 30 from the last one so we'll use another 30 here and we'll be left with 10 liters of fuel so we're still good on fuel we haven't had to refuel yet so what we want to do is we want to add the 60 because it's an option for us to take for refueling but we don't need it yet remember we're doing things greedily so we need to add the 60 to our heap in case we ever run out of fuel so when we add it to the heap obviously it's going to be the new biggest element so we can consider it as 30 sorry 60 30 20. and then we go and remember we have 10 liters of fuel so we're going to end up here at 70 right and at this point we're going to have zero liters of fuel left and we're not at the end right we still have a gap of 30 to the next station so at this point this is when we start needing to go into the heap so we can see okay if we had refueled at you know the biggest gas station that we've seen would we have enough fuel so basically is zero plus 60 is that greater than the distance that we still have to travel 30 yes so essentially if we had fueled up at 60 then we would have enough fuel in total to make our journey so we basically just exhaust the 60 and then append that to the total number of fuel up fuel ups that we've had remember we had to do the initial one at 10 because we got there with zero gas because it took us 10 to get there and then this is our second fuel up that we should have done at 60. so this is kind of how we're doing it like traveling back in time um although you know in real life you can't do this but this is a leak code problem so that's how we do it and then obviously if we had fueled up there then we would have what is that so we would still have 30 left and we obviously reached the end with gas in our tank so we've reached our destination so that's essentially how we want to do the problem of course this explanation is a little bit hand wavy but once we go into the code editor it's actually really simple i think it's only about 15 lines of code and it's super easy essentially what we want to do is just iterate over the stations build that heap if we need to look into it because our i guess fuel is ever at any point negative then we just start popping from the heap until either the heap runs out in which case um if we're still negative after the heap has run out that means it's actually impossible to reach the end or we'll have gotten enough fuel to actually reach the end in which case we're good so that being said let's actually go to the code editor write this out i'll explain it line by line and it should be really clear this is a hard level problem but to be honest i think that once you kind of see the solution it's more of a medium i think probably coming up with this on your own is hard but once you've seen it's not that bad so i'll see you in the editor we are in the editor and it's time to write the code so let us define our heap and here we're going to be just using a standard min heap but we're going to use negative values to get a max heap property the reason that i'm doing this is because python's max heap api is really confusing i don't remember the method names and we can get a min heap by just using negative value sorry we can get a max heat by using a min heap with negative values so let's set that up so we'll say heap is just going to be an empty list to start and remember that we're always backwards looking in terms of how far we were from the last station and whether or not we were able to account for you know the distance traveled and how much gas we have the reason i say this is because we actually need to modify our input here to take account for i guess the distance between whatever the last station is and our target and the reason that we need to do that is because we need to do some processing on the last one to make sure that we actually had enough fuel from the last station to wherever um we need to go so what we're going to do is we're going to say stations append and we're going to pen to it basically the target destination i'm sorry this should be a list uh target and just some arbitrary values so we'll just say float infinity it doesn't really matter what we choose here but essentially what we want to do is just add that in there so we can pretend like the last uh like the target is actually a station and remember that we're processing all the stations here so we need to do that final processing uh if you don't believe me that we need this i suggest removing this from the final solution submit your code and you'll see an example of why it doesn't work if you don't have this so we actually do need this line so what we need to do is we need to keep track of basically how many refuels we have right because that's what we're actually doing here so we're going to say refuels is going to be equal to zero and we also need to keep track of the previous uh gas station that we were so we can calculate the distance between our current gas station and the previous to figure out how far we've actually traveled so let's say previous is also going to equal to zero and now we need to iterate through our stations like we did before so we're going to say for i guess the location of the station and the capacity that it has uh in terms of liters in stations right because that's how it's given to us right position i fuel of i um we're going to say okay well the amount of fuel it took to get here from the last station is going to be what it's going to be our tank minus you know our current location uh location minus whatever the previous one was remember that locations are given in i guess miles from the start not miles from the last station so that's why we need to basically have this minus prev to account for the fact that the distance is given from the start not from the last station so we need to normalize that distance so we're going to subtract the fuel that we've used here and now what we need to do is essentially if our fuel is negative that means that we should have refueled somewhere in the past and we didn't remember we're doing this in a greedy manner we're kind of just going as far right as possible if whatever point we run out of gas then that means that we should have refueled in the past so we need to look into our heap and try to get fuel from those past stations that we were at so we're going to say wild heap so while we have something to pull out of the heap and the tank is negative so essentially when we don't have gas we need to pull things out right so we're going to add to our tank whatever's at the top of the heap so remember that we're putting into our heap minus values we now need to undo the negative so we're going to say minus keep q dot heat pop so we're going to pop whatever's at the top of the heap and we're going to add the negative of it to i guess negate the negative that we put it in the heap in the first place and if we had to do this that means that we had to take a refuel right doing this indicates that we've refueled somewhere so we're gonna say refuels we're gonna see plus equal to one and now we can continue and essentially what we're gonna do here is we're gonna keep doing this until either our tank is now greater than zero which means that we can continue going forward or our heap is actually out of gas stations that we could have refueled at and now what we need to do is we need to say if tank is less than 0 then we're simply going to return -1 because it's not going to return -1 because it's not going to return -1 because it's not possible to reach the end if we get to this if tank less than zero that means that we must have gone through the entirety of our heap and the tank is still less than zero which means that there's no possible way even if we refuel that every single stop it wouldn't matter we don't have enough fuel so that's why we return -1 here that's why we return -1 here that's why we return -1 here now what we want to do at this point if we get to this point then we know that we can actually continue going forward so we need to add our um station to the actual um heap so we don't actually process it now we're going to process it in the future if we need it so we're going to say heap cue dot heat push so we're going to push on to the heap and remember we're using a mini heap here as a max heap so we need to put values in as negative so we're going to say minus capacity and then remember that we need to keep track of our previous location so we can do that nice normalization of the distance so we're going to say prev is just going to be equal to our current location and that's all we have to do either we're going to return -1 here or either we're going to return -1 here or either we're going to return -1 here or we can actually reach the final station and you know it'll have taken some number of refuels and all we need to do is simply return the answer here so refuels cool so let us just double check we haven't made any buck tank oh god damn it's called start fuel uh let's see tank so this is start fuel start fuel uh start fuel sorry about that okay i guess that's why we uh okay cool that's fine and let's submit this tank is not the oh my god leak code why okay yeah they've changed it and since the last time we did this okay cool so we finally got to work after some stupid naming bugs by leap code anyway the code was fine just the variable names were a little bit off so what is the time and space complexity for this algorithm well we're using a heap here and typically heaps are i guess um n log k where k is the size of the heap and in this problem we can if we don't actually need to refuel anywhere let's just say that our start fuel will actually take us to our target um then we don't actually need to you know pop anything from the heat but we're gonna have to put everything into the heat because we won't actually you know process any popping of the heat but we'll still have to populate it at each time um so essentially what this means is that we're going to do n times you know log and operations so we're gonna you know for every basically station that we have we're gonna have to put it into our uh heap here so that's why our space complexity is going to be big o of n log n uh because essentially we would just be putting all of the elements into our heap in the worst case um actually i think in every case we're gonna have to do that so what is the space complexity obviously a heap is just going to be big o of n uh you know in the case that we put every single element in there so that's going to be your time and space complexity for this problem like i said once you see the solution for this it's actually really intuitive and makes a lot of sense i think that it may be a little bit tricky to figure out that you can just do it greedily and just you know take phillips retroactively but once you've seen this once to be honest this is not really one that you're going to forget or you're going to be confused about i think once you've seen it to be honest like after you've watched this video if you get this question you should be able to just blow through it because you'll already know the trick to it so hopefully this helps hopefully if you know if you get this on like a google interview or whoever is asking this these days um you'll be able to just blow through it if you enjoyed the video please leave a like comment and subscribe if there's any videos you'd like me to make please just leave them in the comment section below and i'll be happy to get back to you guys otherwise thank you for watching i hope you enjoyed this i hope you find this helpful and have a nice day bye
|
Minimum Number of Refueling Stops
|
keys-and-rooms
|
A car travels from a starting position to a destination which is `target` miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.
The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.
Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.
**Example 1:**
**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.
**Example 2:**
**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).
**Example 3:**
**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
**Constraints:**
* `1 <= target, startFuel <= 109`
* `0 <= stations.length <= 500`
* `1 <= positioni < positioni+1 < target`
* `1 <= fueli < 109`
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
261
|
476 |
hello friends welcome again to my youtube channel today the problem that we are going to discuss is number complement uh it's problem number 476 let's go through the problem description first so given a positive integer output its complement number and the complement strategy is to flip the bits of its binary representation let's look into the example so input is five and the output should be two uh how two is the output so we all know the binary representation of five is one zero one and when we do its complement so this one becomes zero this zero becomes one and this one becomes zero so the decimal representation of 0 1 0 is 2 right so our output should be 2. let's jump to the blackboard to understand it so here you can see what we have to achieve is this thing we have to flip every bit of the number so here when we see the number is five and its binary representation is one zero one when we flip each bit it becomes two all right now there are number of ways to achieve this to solve this problem but i will cover one of the technique which is bit masking so i will be covering bit masking concept in this video so what is bitmasking if you know the xor concept so when we do one xor of one it will give us zero when we give when we do zero x or of zero it will also give zero and when we do xor of zero it will give one and zero xor of one will give us one now if we see this first case and the last case here we can see with the help of one xor one this one is flipped to zero right so here flip is happening and similarly if we see here zero xor one zero is flipped to one right so here basically flip is happening with the help of xoring with one right so in both the cases if we see when we are absorbing with one we get the flip bit however if we do xor with zero the bit is not changing right so what we get an idea from here is when we see one zero one and when we take a mask of one so this 1 and 1 xor will become 0 and 1 xor will become will be 1 only and 1 xor will be 0 so we got this right and this is basically 2 right so this is our mask right so with the help of this mask we are able to achieve our solution all right so our main task is to find this mask value now we will see how we can find this mask so if we see one is basically seven right in decimal format and 7 is 2 raised to the power 3 minus 1 right so there are how many number of bits are there 3 so that's why this three comes from and when we do tourist power number of bits minus one we will get our mask right which is one all right and so our first task is to find the number of bits then we can find the mask using two wrists for number of bits minus one right and this we can easily achieve using uh math dot bow to the to rest of our power right or we can also do uh we can also use one left shift the number of bits so here number of bits is three and we do minus one so that will also give seven right so now our task the now we have to see how we can find the number of bits so our original number is 1 0 1 right and when we do this right shift first time it will become 0 1 0 all right so what left shift will do sorry uh what right shift will do this will goes to the right this will come here and here will be one zero so zero will come here right so first time when we do right shift it will become zero one zero the second time it will be zero fun and at last it will become zero right so here we will do counter which will be counter one plus one here will be plus one and here will be plus one so our count of bits will be three ultimate so let's see how we can solve it using from the code so first we will quickly write one method which will give us the number of bits right and it will return and get number of bits and it will accept the number okay and it would finally return the count which is initially zero and while our num is not equals to zero right so we are seeing this condition and our num will be num right shift 1 right now we'll do count plus and at last we will return our count which will be the number of bits and here we will be having one and num of bits which will be this one and we'll be having one mask which will be one left shift of num of bits minus 1 and finally we will be going to return the xor of number and our mask right try to run this code so this method let's try to submit this code what i was saying this method we can use to find the number of bits and yeah you can see this code is successfully submitted so yeah friends that's it for today i will be providing the problem and solution link into the description and i hope you like this concept of bit programming it will give you like basics of bit manipulations so thanks friends you
|
Number Complement
|
number-complement
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
| null |
Bit Manipulation
|
Easy
| null |
72 |
72 that says edit distance so in this question you are given two strings word one and word two you need to perform some operation like inserting a character deleting a character and replacing a character on word one to make it similar to word two correct and in the end we need to return minimum number of operation required to convert word one to word two okay so if you take a look at this example we have horse as a word and Ros as a word too so in this ah the you have they have given one solution this that if you replace H with r then it will become Ro RSM so this is one operation in uh if you remove uh R then it these are this between one R then it will become Ro as in and in the end you will remove this e it will become Ros so here in three operation you can convert this HRS into Ros okay got it uh one another they also you can have you could have do this uh is if so you have hyd initially then you have deleted this Edge then it become o r s e then again if you have deleted this so then it will become RSC you have deleted this e you it will become RS and you have inserted this what here oh then it will become Ros but this will take how many steps one two three and four this will take four operation or four steps so yeah it is not efficient three is efficient here so we did this way got it here in this example also uh if we have word one uh int and t i n intention and execution in is about two so these are the steps they have shown in the explanation uh that firstly we remove T from this uh this t okay then what we are doing we are simply replacing I with e so this initial I is replaced with e then we are replacing n with x the second and this and is replaced with X then we are replacing n with C so here is and there is replace with c and at the uh and all at the end in the last step we are inserting U so after this say we have we are inserting U so these are the five steps uh that we perform in this word intention to make it similar to execution so I hope you guys understood the question here that we have to perform this three different operation on different characters of the word one to make it similar to word two so some things are clear from here that uh here we have choices right choices at every step and what choices are they are simply these three that is insert delete and replace let me write it simple as I comma replace comma delete these three choices you have so based on the choices what we can do we can write a recursive code okay so but before that let me explain you that how the decision tree or this recursion tree will be at formed so for an example let's assume that if you have word one as a b and e and word two as let me take it as b c ah sorry c b okay you have something uh NCB uh EF something like this okay let me keep it as simple so let's okay and if you have word to like CB now you want to convert this word one to word two okay so uh we will take this word one we will take this first character we have three choices insert then replace then what delete so if you what uh so now in order to make this word one equal to word two what we will do we can either insert this for character C then it will become c a b e if we replace a with C it will become CBE and if we delete this a it will only be remain b e okay now from the c a b here also we have what three uh three choices like that is insert replace and delete so if you are here we are comparing just the first character now whenever the first character will match so a character match whenever the first character will match what we will do we would check for the second character for each word so for any word that we are checking if the character match so if we are here if both the character matches then we will try to check for the second character so here the second character you see a and C doesn't match then what we can do we can either insert and second character of B also so A and B we will compare okay second character of word one and second character of word two we will compare A and B so either what we can do either do you we can insert P then it will be c b a b e we can replace a with P then it will be c b e or we can either delete this a then it will be C uh b e okay got it yeah and here also now as you can see the first character of both this word are same then we will compare the second character of word one second character of word two simple as that so now as you can see that both the characters of the second word is also the same right this here it is B here it is p there will be check for the third character right this third character e now is there something like that there is something Beyond me no there is nothing Beyond B so in that case what we will do we would uh we would return remaining characters because on the remaining characters we can't insert we can't replace only we can delete and what we will delete remaining characters so we return remaining characters as our answer got it okay now for this B we have again three choices we have we compare first the first character here and first character here they are same then we have three choices insert replace delete any this way completely our answer goes on until we find the efficient solution correct so this is how our decision tree or this recursion tree keep on building until all the possible answers are formed got it so if you try to write a code for this recursive solution the total number of subscript possible for this recursive solution would be 3 to the power of n is the size of the word right this is a very large number so we cannot write this recursive code so what we need to do recursion plus memorization using help of DP and this will reduce our time complexity would to Big of n to the power of 3. see you might be seeing y 3 Because at average stage we are performing three operation insert replace and delete and that's why we have three in this time complexity here 3 to the power n and Cube so yeah by using recursive plus memorization our time complexity would be much reduced so now let's move on to the core part where we will understand this see this question is pretty much simple that since we have a direct three choices like insert delete and replace we will do the same thing as told in the question right we don't have to do or think any much further see initially I we have this DP we store minus 1 into DP and call the function solve so in the solve function if I one equals to 0 that means see we are here I am traversing from the back from the n and the m so I 1 equals to zero that means there are no elements left then we return I2 because these many numbers of characters need to be deleted these are all remaining characters that need to be deleted similarly if I two equals to 0 then these many characters need to be deleted correct okay as I have already told you that the remaining characters I would be deleted as you can see this e was the remaining character and it must be deleted there is no other option like you cannot insert or replace that it has to be deleted so yeah we simply Returns the number of characters that are remaining then this is the DP uh code that we if we check that if we have some solution then we return that our answer then we check that if uh the character matches so if a character matches then we don't have to do anything we neither do insert no delete no replace operation we do not do anything and if nothing of this if condition uh works then what we will do our core will reach here and we would perform all these three recursive see we are calling the function again and this is where recursion occur got it and each time we are doing I minus 1 minus one uh mistaking the front character and only in the replace part you can see we are doing uh we are extracting one character from both because let's say uh let's say here I is replaced with E that means I and E will certainly match I is replaced with e so that means this first this character will be has become and this is already e so this way e both will already match yeah so that's why we are doing minus one from both because by replacing we have matched the character right so yeah no need to check for that character again correct so yeah this is how the replace work delete is as simple that we have some extra character and we delete from that word one correct simple as it is and insert is an insert is we are just doing from the word two and you and if you are confused that y only y i two minus 1 so because in insert what we are doing let's say we have word e f g here this first and here let's say a b this is first and now if you at this point you are inserting see both the character don't miss you are inserting that it will become AEF D you have inserted this so our i1 will all will point to this e it will point to this e but here for the second word it will point to next right it will point to next so our next is what I two minus 1 I 1 it means that it is Vitamin X is I2 minus one so that's why in insert position we are just changing the index or for the word two so this ah clears that what we are doing here right and in the end we are simply taking the minimum of all these three operation there is minimum of insert and minimum of delete and replace and storing it to this DP so this is a simple recursive code that is memorized with the help of this DP and the size is 501 into 5001 because the total length is 500 so yeah V2 501 and 501 as the size already being it is 2D DP because we are using two variables here in the circle got it so yeah I hope you guys understood the recursive solution how this recursive tree is built and yeah if you have still uh difficult in understanding the recursive tree then I advise you to build this requisite Tree on your own so once you try to build this then you will get more idea of how recursion work overall it was a simple question of recursive plus memorization also it is very much standard equation for the interview so make sure you go through this question very well you must have complete understanding of this question of all this three function right so yeah that's all for this video from my site any further time complexity I have already discussed the time complexity here and the space complexities big of n Square as you can see this DP we are using and some space complexity will be also used in this stack but yeah overall you can say if the space complexity is Big of n Square so yeah that's all for this video from my side make sure to like this video subscribe to our Channel thank you
|
Edit Distance
|
edit-distance
|
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
161,583,712,1105,2311
|
191 |
today we are going to solve number of one bits we are given a number and we need to return the number of ones in its binary representation so for example if we are given 6 so that is 1 0 in binary representation and the number of ones in this is 2 so we are going to output 2. so the one way of solving this problem is to convert the number in its binary representation after converting in binary representation we are going to make this binary presentation as a string and in this string we are going to count the number of 1 but we are going to solve this problem using bit manipulation so we need to check for each bit whether it's 0 or 1 if it's 0 we're not going to increment our count if it's 1 we are going to increment our count so we'll take the first bit and check whether it's 0 or 1. so it's 0 so we are not going to increment our count so count will be 0. now we shift to our next bit so it's 1 so we are going to update our count by 1. now again we are going to shift to the next bit so it's one so we are going to increment our count by one so it's two so we are going to output our two so here we need two things firstly we need to determine whether it's a zero or one at the right most position so this is simple this we can do by ending with 1 when we end a number with 1 if it 0 this means that the right most bit is 0 if it won that means the right post bit is one so we are able to determine whether it's a zero or one at the right most position after finding for this right most position we need to sift for the next bit so for sifting to the next bit we need to sift to the left and we need to discard this right most bit so for that we can do our right shift so we are going to right step by one so when we write shift by one it will discard our right most bit and this left bit will become our right most bit so we'll keep looping this process until our input is become zero when it's become zero we are going to return our count so it's a very easy problem let's code this problem we need a count variable to keep the count of number of one in our binary presentation of the input initially it will be zero now we are going to loop until our number is greater than 0 so while 10 so firstly we need to find whether it's 1 or 0 at the right most position of the number so if it's 1 we are going to increase our count by one and now we need to right shift our n by one so that the right most bit will be get discarded and the bit before the right most bit will become the right most bit right shift our number by one and at last we are going to return our count so let's run our code okay so it's giving us correct output let's run for example test cases yeah so it's giving this correct thing let's submit our code so it's got submitted a deficient and space complexity is also good so the time complexity will be 4 1 because our number could be 32 bit long so we're going to run our loop 32 times at max so that's why our running time will be o1 and the space complexity is one so yeah that's it for today i hope you found this video useful please do like and subscribe see you next time
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
922 |
That my become I am Anand and today we will see by listing the question shot dead by parity come in simple tense that the center is intense and being this recipe which will be the last bullion is one it is zero it has positive sign now question What is there is that we are given an interior in the input and what we have to do is to use it and do that which will be my result tab, its even index on it should be these values like index on it should be these values like index on it should be these values like 202 in these positions and index like 13151 should be the constraint. If you are interested, it will have sufficient number of even and odd numbers, then we have been given another liberty to write any Android device in this condition, any position, environment, now it should be strong, I am on the fourth, their order is anything. Maybe that condition should be fulfilled that there should be one position for Indian values, he can be anywhere in the front or back, he does not have any girlfriend because then how are we going to approach this, okay here one thing and you see the code you solve. It in place i.e. can you do this so you solve. It in place i.e. can you do this so you solve. It in place i.e. can you do this so that you do not use any additional SP and make it soft that this is what you are going to do, we will return Namaskar only to this one, after modifying it is going to be my daily habit, okay so we Let's see my approach, what will we do using that point, we will travel all this, the second thing that came with me is which is my country where subscribe and its value and it is there while searching and it is on top. I am here and then like this, is there any value on my position and here I am busy, here I have value on five percent i.e. hot position, so I will value on five percent i.e. hot position, so I will value on five percent i.e. hot position, so I will put it here. Now first we have found this point, now we will simply slide it. If we do it, then this position of ours has started till now and we will keep subscribing till here and will give it again here and if we find their mismatching, then here only and only genuine and subscribe, so let us show you easily how to do it. Can but have taken its size and this position which has been subscribed and will be stacked till the time I am inside the subscribed, there is no such position for I where he should not keep value to China unless he is doing and Where will we be, where the position is ordering, then it is better that we have reached the place where if we get such a guarantee before this match, then we have got it from here, so it is assured without question. We did simplex and increased G again to next and Patel Inter will keep doing this work then after this my start will be done then we will return to simple firms and we submit it then we get that accepted and if its See the complexity, yes then it is ok, complete, this is our scope for further improvement, so thank you for watching this video and I wish you all that if you want solution of your according from platform like WhatsApp code for a better liquid questions in Hindi and If you want explanation please consider subscribe my channel thank you so much for watching this video thank you
|
Sort Array By Parity II
|
possible-bipartition
|
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**.
Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**.
Return _any answer array that satisfies this condition_.
**Example 1:**
**Input:** nums = \[4,2,5,7\]
**Output:** \[4,5,2,7\]
**Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted.
**Example 2:**
**Input:** nums = \[2,3\]
**Output:** \[2,3\]
**Constraints:**
* `2 <= nums.length <= 2 * 104`
* `nums.length` is even.
* Half of the integers in `nums` are even.
* `0 <= nums[i] <= 1000`
**Follow Up:** Could you solve it in-place?
| null |
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Medium
| null |
205 |
hey good to see you here so today we are going to solve a really good problem which is uh isomorphic strings so given to string s and d we have to determine if it is isomorphic or not so the question arises what is isomorphic so we can say that if two string s and t will be called isomorphic if the character and s can be replaced to get t that means let's say we have this s string as egg and d string as add so what we are doing is we are replacing this e with a and this g with d so after doing all this we get true because we are able to map this right and in the second example let's see we have f o and then bar so what we can do is if we map f to b uh it is mapped right but when we map o with a it will again map but the problem arises there is again an o which we can't map to r because the same element cannot map to two other elements that's why here the answer is false so let's see how we can actually approach this problem so here let's say we have this string s egg and d s and so what we are doing is we are mapping each element of e with a so let's say we have two string s and d so what we are doing is we are replacing uh like we are math okay so let's say we have two strings s and d s is egg and d is add so what we are doing is we are creating a map in which e mapped to a and g mapped to d again there is a g so hence the element g is already in the map that's why and it's already mapped to d that's why our whole function return true and here also what we are doing is we are taking a set which contains all the element which we have already added in the map of the t string so let's say if we are mapping e with a then the set contain a here again and then again if we are mapping the g element with d then the d comes here so now the question arises how and what are the cases where we are going to have false as an uh output so let's see let's say we have a string s that is egg and then a string d that is adc so what we are doing is firstly e map to a right and then g map to d again then again there is a g so hence what we have to check is this g is already mapped to something and it can't map to c again or we can say if it already mapped to d then we cannot map it to c right so what we are going to do is the function here should be return false because this is not the case because we cannot replace all the element of s with t okay so this is the whole idea about the how we can approach this problem now let's see the coding part of it so here what we are checking is the first corner cases that if what if the size of the string didn't match right let's say we have the size of ss 3 here and the t also has 3 here that's why it's obvious that each and every character should correspond to some other character in both the strings but if the uh size of the string didn't match then obviously it should return a false answer now this will check uh the first condition now let's uh move ahead so what we are doing is we are creating a map consisting of character and also a set which consists of character now we are traversing throughout the string yes so what we are doing is we are putting uh the element each an element of s in the map and we are mapping it with the element of t so let's say what happened is if we find like if there is an element already uh present in the map then what we have to check is if the element if the mapping element match with the element we are having right now so we can this understand this like let's say there is eg so e is mapped to a then it's inside the map and then g mapped to d then it's inside the map now this case again there is a g occur that is uh this s i doesn't like uh already exist in the map so what we are checking is if m of s i so this gives the value corresponding to this key and if we are getting the same value that is in the first case the value for key g is d so again if we vc there is a g and if we type m of let's say g then we will get d again and this d match to this d that's why it's uh it's correct in this case but if this doesn't happen then we should return false now the second case arises that is if whatever the uh whatever the element we are putting in our set that is if the count of the set uh goes up then we should have to return false and otherwise we have to append or whatever the element of t we have in the set and then we are just mapping e with a and whatever the element of s with the element of d so this is basically the condition arises when we got a duplicate that is let's say uh there is a b c as s so let's say this e g and then here again a let's say we have a here so what it does is g is um g is mapped with d and it didn't correspond to the element so this come here in this condition right but for this we can just simply say it like if there is an element already in the set and if again comes uh that means it shouldn't be the case because two element of s map with a same element of t so that is also a case where it should return false and if all the cases are covered then at the end we have to simply return true because this if none of the other cases will return false then obviously both the string can be isomorphous so this is the solution or the problem isomorphic string and you can find the code in the description which is a github link so you can directly access the code from there okay so this is it for this video thank you
|
Isomorphic Strings
|
isomorphic-strings
|
Given two strings `s` and `t`, _determine if they are isomorphic_.
Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
**Example 1:**
**Input:** s = "egg", t = "add"
**Output:** true
**Example 2:**
**Input:** s = "foo", t = "bar"
**Output:** false
**Example 3:**
**Input:** s = "paper", t = "title"
**Output:** true
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `t.length == s.length`
* `s` and `t` consist of any valid ascii character.
| null |
Hash Table,String
|
Easy
|
290
|
1,713 |
hey what's up guys this is sean here again so this time uh 1713 minimum operations to make a subsequence pretty cool problem okay so you're given like an array target that consists of distinct integers and another integer array that can have duplicates so in one operations you can in one operation you can insert any integer at any position in this array here for example right you can insert a three into any locations here and you need to return the minimum number of operations needed to make a target a subsequence of array right so a subsequence you guys all know right subsequent has to be maintaining for some of the subset of the numbers that has also maintained the same ordering and two examples right so the first one is like this one so we have five one three and this is the array here and we can we need to insert since we only have three in the target in this array here so which means we need to insert five and one that's why the answer is two and for this one uh it's three basically which we need to insert three numbers to make this target a subsequence of this new array here and the constraints is like this 10 to the power of 5. here target contains no duplicates this is the key this is a key like hint to solve this problem so i think the first observation is that you know the since we can insert any integers at any position in this array here so the problem will actually comes down to what comes down to the what's the longest common subsequences between these two arrays here because if we can get the longest common subsequence between those two arrays here and then all is left is that we just need to insert the uh the difference right the difference between the target and the uh the length of the target minus the uh the length the lcs so the n is the length of the target so for example this one right so the uh the longest a common subsequence for the between those two array is three which is one and that's why since n is 3 n minus 1 will becomes to 2. same thing for this one so this one is a little bit more complicated but the longest common subsequence between those two array is what is six uh six to maybe four uh is actually six eight and one that's the longest common subsequences between those two arrays which is three that's why the answer is 6 minus 3 is 3 because you know i think it's kind of obvious because as long as we find the longest common subsequence between those two arrays we just need to insert the remaining parts the remaining three numbers the remaining numbers into this array at any locations right for example we have 6 8 1 here that's why we have 6 8 1. since we can insert any numbers in any of the locations all we need to do is we need to insert the remaining parts 4 3 and 2 at the correct location which is the we're going to insert 4 between 6 and 8 here and then we insert the 3 and 2 after at the end of this array which is going to be here that's why we only that's why the answer is three so now the problem is the question is how can we calculate the uh the longest lcs right longest common subsequence so a traditional way of doing the of calculating the lcs is by using a two-dimensional dp right so dp two-dimensional dp right so dp two-dimensional dp right so dp i and j right so i think there's another like lethal problem only just for this lcs i may be able to also make a video for that one basically for dpi and j right so i means the uh this first uh ice character in the array one and the first js character in the array two what's gonna what's the maximum like common answer common subsequences so here we just we have like basically check if the i and j are the same if they are the same then we uh do a plot do a plus one otherwise we do uh the maximum of i minus one j uh dp right i minus one j or i j minus one nice yeah actually this is what this one is quite similar is the uh the added distance right so dp this settings i uh so dpi minus 1 j minus 1 right and then we plus one right that's the uh that's the traditional way of doing this uh lcs but as you guys can see here so the time complex there for this one is going to be what it's going to be uh m times n where m is the length for the first array and second n is the length for second array and since we have like this kind of target this for they're both like 10 to the power of five so if we do it if we calculate the lcs in the traditional way we're going to have a tle so which means that we need to have like a better solution right and here's the key point here you know the first one is like they're all distinct so what does this one change so what this one changes that you know for this one we can actually convert this lcs problem sorry lcs problem into a lis which is the longest increasing subsequence and the out i s can be solved in the o of n log n time by using a binary search and that's the key point to solve this problem and so how can we convert this lcs to ios since each element each number in the target they're all distinct which means that we can update we can create like a new array by using the index of from the first from this uh this thing from the first target array here which means that we're going to have like 0 1 2 3 4 and 5. and then we're going to replace the array with the index from the first target if i mean of course if the rate if the number does not it does not exist in the first target we simply we just simply skip that so then what we have from the tar from by replacing the index we have well one right first one is one and seven is not there we skip that and then we have zero and then we have two is five we have five and then we have three is four right and then we have eight is two six zero again right six is zero and one is four yeah so with this new array here we can if we have if we now the if we get the lis then the answer is the same and the answer is wait what we have zero 2 and 4. that's the hour s right the longest increasing subsequence for this one which is 3. and why this thing works right it's all because the uh and it's this is because the since the numbers in the first array they are all distinct and by using the uh the index right because since the index is always increasing right and if we can find the longest increasing subsequence right from the second array that means that we are we have find part of the subsequence right basically we also find the subsequence from the target array because like i said they are they're like they're all increasing that's why as long as we find that in any increasing subsequence from the second array is also going to guarantee to be a subsequence of the first array that's why we can make this com uh conversion yeah and that's what exactly we're going to do here so to make the conversions i'm going to create a like index map right for like the nums of i right for each of the numbers uh in the first target array so in enumerate right and the target and then uh with this index map we can create a new array here outscored a2 maybe so the new array is gonna be the what so we're gonna have like four nums in the second array right if the num is in the index map otherwise i'll just i'll skip that here i'm just simply using the values for from the index map which is the index for that okay and now we can supply the ls on top of this a2 so you know the way we're doing that is by using a binary search so we're going to have like dp for that so and not for num in the a2 and then we get the index we do a binary search right bisect left equals to dp dot num and then if the index is smaller then the length of dp right we update updated the dp by the current index sorry by the current number uh otherwise if the current one if card number is greater than all the previously right numbers we just append right and to the num to the dp and in the end the length of dp is the loss and so that we can just simply return the length of the target right that's going to be the total minus the length of the dp which is the ios so run it and so the time complexity for this one is kind of obvious so we have a n and then here that's unlocked all right that's why the time complexity is unlocked n and space complexity is all of it cool i think that's it for this problem i mean this one is i think it's kind of a classic one you know as long as you can find you can convert this problem to a lcs problem you know and the next thing is that you have to be insightful enough to find this like constraint which is going to be the one of the target one of the array is like it's distinct numbers and from there you just need to know you can convert this lcs to lis if any of the array has like distinct numbers distinct or distinct arrays or strings and then from i lis you can we can do a unlock and yep i think that's it and i'll just stop here thank you so much for watching this video guys and stay tuned see you guys soon bye
|
Minimum Operations to Make a Subsequence
|
dot-product-of-two-sparse-vectors
|
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates.
In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array.
Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\]
**Output:** 2
**Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`.
**Example 2:**
**Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\]
**Output:** 3
**Constraints:**
* `1 <= target.length, arr.length <= 105`
* `1 <= target[i], arr[i] <= 109`
* `target` contains no duplicates.
|
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
|
Array,Hash Table,Two Pointers,Design
|
Medium
| null |
1,672 |
foreign so this is the 1672nd episode or an episode the question of click so here we are given an M into an integer grid accounts so it's essentially a matrix it's a fancy way of telling a matrix okay so this account or a matrix has obviously i j a 2 row and a column index is the amount of money the ith customer has in the jth bank so essentially in this Matrix the rows represent the customers and the columns represent the banks and essentially what banks mean itself the customer I has certain amount in each of these Banks so those are stored in the column respectively okay so I'll give you a sample look at the Matrix that is given to us here so this represents the row represents the customer and the column represents the amount that is present in each of these Banks under the customer's name okay so two rupees are 2000 rupees or two rack rupees whatever it's your wish so two units of money is present in bank one for this person and uh eight rupees under Bank two and seven rupees under Bank three and similarly for each of these customers we have these many units of money under their name in each of these punks so this is the Matrix that is given to us and the name of this matric is accounts okay so with this information return the wealth that the richest customer has so we have to return the wealth the richest customer has so how do we determine the wealth and that who is the richest customer so the customers wealth is the amount of money that they have in all their Banks okay so a customer a has 5 and bank one five and Bank two five and Bank three so the total wealth is fifteen five plus five so similarly the customers well can be calculated just by adding up all their wealthin or balance in each of these bunks okay so there is just customer is the customer that has the maximum wealth okay so in plain sight each row represents the person's width so 2 plus 8 plus 7 represents the wealth of this person and 7 plus 1 plus 3 represents the wealth of this person and the one with the maximum wealth is the value that we want okay so the value of the maximum wealth okay so how do we do that so we need the values of each of their wealth so for that we'll just add these values so 2 plus 8 plus 7 that gives us 17 and that is the wealth of the first person now we have to find the maximum width right so we have a value called Max and it is initially set to integer Min okay now we'll compare integer Min with 17 which is bigger 17 is bigger or 17 is maximum and hence our value gets updated to 70. Now we move on to the next customer so 7 plus 1 8 plus 3 is 11. now we compare 11 and the maximum 17. so our current maximum is 17 and the current value or the current rows sum or the current person's wealth is 17 oh sorry 11. we compared these two we already have the maximum person's wealth here so if we compare we do not get the maximum value and hence we don't update the value 1 plus 9 plus 5 in this case we get 15 We compare 15 with 17 it is not greater than 17 and hence we do not change the value so essentially what we are doing here is we're calculating the row sum of each of these persons and whichever one has the maximum rho sum has the maximum wealth so our question becomes first find the maximum row sum okay so the raw sum denotes the belt and in those raw sum whichever is the maximum so the maximum rhosum is our answer so this question when simplified is just to find the maximum erosion so find the rowsome for each of these customers and then find the maximum out of it and that is our answer so here we have the algorithm for this first use an instant Loop of course because we have a matrix we of course need a minister Loop in order to get through all of these values so the next point is to find the row sum of all these values like PSI in the demonstration we need to find the row sum of each of these customers which represents the wealth of these customers so the third point is to compare whether the row of sum is greater than the already existing Max because if it is greater then we have found a new maximum or a new built person wealthier person then in that case we would update the value of Max and we'll repeat the loop so for each person we find the row sum that is their wealth we compare it to the already existing maximum weld if it is greater then this is the New Wealth or the new maximum well we updated to Max if not we just repeat the loop okay and last at last after all these for Loops we'll have a value stored in Max and that is the richest customers well and that becomes our answer so this is the logic that we have in order to solve this question now we'll move to lead call and solve this given question while I explain you this function go around to the YouTube subscribe button and just click it okay so here we have the maximum weld function so this takes the Matrix accounts as input and Returns the integer which is the maximum customers wealth okay so wealth of the richest customer whichever way you want to phase it okay so first how do we get started with this first get started by declaring the max value to integer Min so integer dot Min value so this is where we start now what do we do next we have the nested for Loop right so for end I is equal to 0 I is less than accounts.length accounts.length accounts.length I plus and similarly for INT J is equal to 0 J is less than a cones of I dot length J plus space so we are essentially travising the whole Matrix before we do that what we do we need to find the row sum so how do you find the raw sum for each row we first declare the row sum is equal to zero so initially the row sum is 0. at each iteration we add the given number into the row sum so row sum plus equal to accounts of I of J so this for Loop calculates the row sum for each of these person and now what we do we compare it with the maximum value so if the row sum is greater than the already existing maximum value we update the value so maximum is equal to corrosion else we just move on to the next iteration we move on to the next customer and find their row sum or their wealth and then if their wealth is greater than the other existing maximum and then we update the value move on to the next customer similarly we check for each and every customer calculate their wealth check whether it's created with an already existing maximum if so make this person's wealth the maximum move on to the next iteration so after the end of this for Loop we'll get something stored in the maximum and that is the richest customers well so return Max that completes our code now let's run this code and verify whether we have successfully completed it yeah so this runs perfectly now let's submit this code and verify our output okay so congratulations on solving this question with this now with this come to the end of this video if you love this video please drop a like and comment down below if you have any queries and don't forget to subscribe we'll see you in the next episode delete code until then bye foreign
|
Richest Customer Wealth
|
find-the-index-of-the-large-integer
|
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `ith` customer has in the `jth` bank. Return _the **wealth** that the richest customer has._
A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**.
**Example 1:**
**Input:** accounts = \[\[1,2,3\],\[3,2,1\]\]
**Output:** 6
**Explanation****:**
`1st customer has wealth = 1 + 2 + 3 = 6`
`2nd customer has wealth = 3 + 2 + 1 = 6`
Both customers are considered the richest with a wealth of 6 each, so return 6.
**Example 2:**
**Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\]
**Output:** 10
**Explanation**:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
**Example 3:**
**Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\]
**Output:** 17
**Constraints:**
* `m == accounts.length`
* `n == accounts[i].length`
* `1 <= m, n <= 50`
* `1 <= accounts[i][j] <= 100`
|
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
|
Array,Binary Search,Interactive
|
Medium
|
786
|
1,406 |
hey everyone welcome back and let's write some more neat code today so they'll solve the problem Stone game three and to be honest I don't know what leak code was smoking when they made this a hard problem and they made Stone game 2 a medium problem in my opinion this problem is definitely easier I mean there's some small things that make it more difficult but I guess you can be the judge of that the premise of the problem is pretty simple but instead of Alice and Bob taking up to M stones from the beginning of the input array they can choose either one two or three stones so instead of having a variable M we're pretty much just taking M and fixing it to be a value of three so that's why I think this problem is just a lot easier now there's a slight difference and it's that we want to return the name of the winner so if Alice wins we return her name if Bob wins we return his name if there's a tie then we return that string and again both players are going to be playing optimally so in a sense we are going to have to kind of brute for course everything and it's going to be alternating so at first it's going to be Alice's turn and then it's going to be Bob's turn and then it's going to be Alice's turn etc and depending on the return value of our recursive function for Alice assuming that we're returning her score Alice would want to take the maximum if the function is returning Alice's score then probably Bob would take the minimum of the return value and you definitely can solve it that way similar to how we did yesterday it's pretty much nearly the same solution now one Edge case here though is that in our list of values before we were just dealing with positive values but in this case we could actually have some negative values we could have negative two maybe a negative 3 and a positive 7. so that's going to make things a tiny bit more tricky but it's actually not as bad as you would think basically when for Alice we're trying to maximize her score and we initialized her score previously to zero so that we could then try to maximize it if we can have negative values though it's possible her score might be less than zero so basically the difference is that we just initialize it to negative infinity or whatever like minimum integer you have in your language so literally that's the only difference that's how you can handle negative numbers it's that easy now because this problem is so similar to yesterday's problem I'm actually going to show you a slightly different way to solve it let's instead set our return value of the recursive function not to be Alice's score and also not to be Bob score either we're going to change the sub problem to basically be when it's Alice's turn we're essentially going to be calculating Alice's score minus Bob's score when it's Bob's turn we're pretty much going to be calculating Bob's score minus Alice's score now with this way we don't necessarily know the score of each player but do we really need to know the score if Alice minus Bob is equal to zero that must mean they had the exact same score therefore it was a tie if Alice minus Bob is greater than zero it's a positive number that must mean Alice had a larger score so therefore we would return Alice obviously if it's a negative number that means Bob had a higher score and then we would return his name so we do get all the information we need by setting this to be our return value but my question is does this actually work and why does it work suppose this is our input array and we know Alice is going first and therefore our I pointer is going to be starting at index zero so she can either choose the first stone the first two stones or the first three stones so there's going to be three branches here I equals one or I equals two or I equals three now from here it's going to be Bob's turn and Bob can take one stone or two stones or three stones and that would take us all the way out of bounds and that is valid so here we could get to I equals two I equals 3 or I equals 4. now let's consider this case just because it's like the only base case here and I don't want to draw like a super large tree so by the time we get to I equals four we know Bob was here we were at index one and then we took our pointer all the way over here therefore Bob took these three and we know when we go out of bounds we should probably just return zero that's the base case here so now from this recursive call over here we're gonna return zero up to Bob but remember what does this zero represent from Bob's perspective it represents Alice minus Bob that's what's going to be returned up to Bob and since we know Bob took these three stones Bob score so far should be negative five plus two which is going to be negative three so this negative 3 applies to these three elements and whatever here which is zero in this case it was the base case that represents Alice's score minus Bob's score in this case it is zero but you can imagine that there would have been some real numbers there so if we take negative 3 minus this notice what that's doing mathematically this was just a subset of the values that Bob could get and this is Alice minus Bob for the remaining portion of the array so I'm going to redraw this to make it very clear so remember this negative 3 just represents this portion of the array that Bob chose and this will in this case is the base case but it could represent part of a real array but notice that when you put the subtraction here you don't want to add like an addition because at that point we'd literally just be accumulating the entire array but if we put a subtraction here you can see that this negative sign and this negative sign will turn Bob's portion into a positive portion and Alice's portion will be negative so basically this formula does simplify to Bob minus Alice for this portion of the array both of them together so remember that is what we're trying to return from Bob's perspective we're trying to return Bob minus Alice and then from Alice's perspective we're trying to return Alice minus Bob and this is going to work very similarly now we're going to use that same portion this portion over here we know represents Bob minus Alice as I just showed and now this value is going to be returned up to index 0 where Alice initially just chose the one value so one and again we're gonna say one minus this part bob minus Alice and again you can see the Alice portion becomes positive because these two negatives cancel out but the Bob portion stays negative so this again condenses to basically be Alice minus Bob for this entire portion now I know that this is not super intuitive it's pretty clever but this is kind of a pattern called the min max pattern where Trying to minimize the value and maximize the other but I hope it kind of makes it clear that if we do it this way we are going to end up returning Alice minus Bob from The Root when we call this recursive function and this way we only have to take the maximum every time we make a recursive call because from Alice's perspective of course we're trying to maximize this value from Bob's perspective we're going to be trying to maximize this value so that allows us to just take the maximum on each iteration now lastly I want to mention why is it that we only need to keep track of one variable I at this point doesn't it matter if we got to like this sub problem with Bob or this sub problem in this case with Alice doesn't it matter not really for the calculation of the sub problem it only matters from the root because what we're trying to return from here is Alice minus Bob but whether we get to this subarray for example and at this point where Alice or were Bob it doesn't matter the result of the sub problem is going to be the same because remember what we're calculating here is no longer the score of Alice nor is it the score of Bob what we're calculating here is going to be the difference between Alice minus Bob or Bob minus Alice so again you might wonder well these two formulas are different aren't they yes but the result of that sub problem is going to be the same whether we started with Alice or we started with Bob from the beginning of the subarray the result is still going to be the same isn't it's going to be some integer value so technically these two values these two formulas starting from this position would be the same number regardless of who we are at that point again these are some pretty abstract Concepts that's kind of why in the previous problem I went with the I think more intuitive solution but maybe you found this solution more intuitive this solution is more easy to code up thankfully but I personally think it's harder to come up with and in this case we are going to do this cursively but as you see there are some repeating sub problems so again we can apply the idea of caching and in this case we just have a single variable so the overall time and space complexity is going to be Big O of n because that's the number of possible values our I pointer could have where n is the length of the input array and with caching we are going to have extra space as well Big O of n so now let's code it up the first thing I'm going to do is create our DFS and we're going to just have a single parameter and remember what this is going to be returning is either Alice minus Bob or Bob minus Alice then first thing we want to do is the base case if our eye pointer is the length of the input array and in this case they called it Stone value I'm just going to call it values because if we call it Stones it kind of makes it seem like they're always going to be positive but I think values makes more sense so here when we execute the base case we're just going to return zero and remember we're going to be trying to maximize each time so we don't even need a ternary operator in this case when we initialize is our result but we do need to set it to negative Infinity we can't set it to zero because there are negative values in the input array remember we have three choices that's how many times we want to loop I guess you could just put three function calls for DFS three recursive function calls but I think it's probably easier to use a loop and this makes it a bit more extensible as well so we know we have three choices starting at index I going up until I plus three but it's possible that I plus 3 could be out of bound so we could have an if statement inside of the loop to check for that like I did yesterday but in this time I'm just gonna use the Min function so I'm going to take the minimum of this and the minimum of the length of stones and the reason I'm doing length of stones and not length of stones minus one is because remember the second value in a for Loop in Python is non-inclusive just like the I plus three non-inclusive just like the I plus three non-inclusive just like the I plus three will be non-inclusive so then in here we will be non-inclusive so then in here we will be non-inclusive so then in here we do want to make our recursive DFS call and if our last value is at index J that's the last value you that we're choosing we're either choosing I or I plus 1 or I plus 2 like that's where we're going to be stopping so then we would want to continue right after that at J plus 1. now how are we going to maximize our result well we're going to set it to the max of itself or the recursive call but this is a bit incomplete remember to calculate the score of whoever is playing right now we want to get the sum of the stones that they chose so we can say values and here I should probably have said values as well here we're going starting at I going up until J but we have to do a plus one because again this part is non-inclusive in Python so this is the non-inclusive in Python so this is the non-inclusive in Python so this is the subarray but we want to take the sum of that subarray you don't have to do it this way you could also just have like a separate variable here to like tell you the total and then on each iteration of the loop you could increment the total like this if you want to do it that way you can I guess this is just like a slightly less code way of doing it and since the maximum size of this will always be E3 it doesn't really affect the overall time complexity either but when we're calculating the score here we're not going to take the sum of this and the recursive call because what that would do is pretty much just give us the sum of the entire values array we're trying to return not Alice's score not Bob score we're trying to return the difference between them so if this is going to return to us Bob score now we want to subtract so if this is returning now Bob minus Alice we want to subtract that which will give us Alice minus Bob and now we would just return the result after we have maximized it and then out here what we would do is possibly have like three if statements because whether this returns zero we want to return tie if it's greater than zero we return Alice if it's less than zero we return Bob and you can do it that way but you probably already know how to code that so I'm going to show you maybe a slightly clever way to do it's basically using a ternary operator if DFS of zero is greater than zero that's when we return out us else we don't just have to put a single value here we can have a nested ternary operator which usually isn't good practice in this case it makes our code a bit shorter so I might as well show you how to do it so here we're going to return Bob if the DFS call is less than zero and else we would just return tie because at that point we know it's equal to zero but you notice we're calling this twice isn't that going to affect the overall time complexity yes and right now the time complexity is exponential we haven't applied caching yet so the first thing I'm going to do is apply caching and we know after we apply caching calling this a second time is not going to be expensive because the value will already have been cached so let's do that if I is in DP already we've already solved the sub problem therefore just return the result otherwise let's compute the sub problem and then store it in DP before we end up returning so set it to result at index I just like that it took us I think what 2 three four lines of code to add caching to that's the entire code and I think I shouldn't put a d over here now let's run this to make sure that it works and as you can see yes it does and it's pretty efficient you can make it slightly more efficient if you used a one-dimensional array if you used a one-dimensional array if you used a one-dimensional array rather than a hash map and probably slightly more efficient if you went with like the tabulation approach but I think this is easy enough though I will mention with the tabulation approach you can optimize the space complexity because as you can see in this case we only need to go up until I plus three so we don't necessarily need to have more than three values in our data structure at a time if you have questions about that approach feel free to comment I'm sure I can answer it or maybe other people can answer it if you found this helpful please like And subscribe if you're boring for coding interviews check out neat code.io it has a ton of check out neat code.io it has a ton of check out neat code.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
|
Stone Game III
|
subtract-the-product-and-sum-of-digits-of-an-integer
|
Alice and Bob continue their games with piles of stones. There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take `1`, `2`, or `3` stones from the **first** remaining stones in the row.
The score of each player is the sum of the values of the stones taken. The score of each player is `0` initially.
The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.
Assume Alice and Bob **play optimally**.
Return `"Alice "` _if Alice will win,_ `"Bob "` _if Bob will win, or_ `"Tie "` _if they will end the game with the same score_.
**Example 1:**
**Input:** values = \[1,2,3,7\]
**Output:** "Bob "
**Explanation:** Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.
**Example 2:**
**Input:** values = \[1,2,3,-9\]
**Output:** "Alice "
**Explanation:** Alice must choose all the three piles at the first move to win and leave Bob with negative score.
If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.
If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.
Remember that both play optimally so here Alice will choose the scenario that makes her win.
**Example 3:**
**Input:** values = \[1,2,3,6\]
**Output:** "Tie "
**Explanation:** Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.
**Constraints:**
* `1 <= stoneValue.length <= 5 * 104`
* `-1000 <= stoneValue[i] <= 1000`
|
How to compute all digits of the number ? Use modulus operator (%) to compute the last digit. Generalise modulus operator idea to compute all digits.
|
Math
|
Easy
| null |
269 |
hey guys it's offi1 here and today we're going to be solving alien dictionary now I'm sure you can see that the interface is a bit different and that is because I don't have Lee code premium so I'm solving this problem on the website called lint code the only difference for this problem is that they have extra requirements here number four and five but we can just ignore them for now because they're not really important so this is a Lee code heart problem but once you actually look at the problem it's not that hard I think the hardest part is actually try to read the problem and dissect what they want so let's do that so we're told that there's a new alien language which uses the Latin alphabet and this part right here is irrelevant so I'm just going to cross it out next we're told that the order among the letters are unknown to us so that means that instead of our alphabet going a b c d we don't know the actual order of this alphabet here and that's what they're asking us to find and in order to help us find the order we're giving a dictionary here that is guaranteed to be not empty so we don't have to worry about that edge case now we're told that the words in a dictionary are sorted lexicographically by the rules of the new language and all this word means is that let's go back to our English language if we look at our dictionary we're going to see the word r come before the word art the reason is because e comes before the letter T in our English alphabet so for example we can have let's say this was a word the dictionary will be in this order because e comes before t and t comes before Z so now that we understand this part let's look at this alien dictionary and see what their relationship is so we have the word wrt and wrf and for this language we can assume that t comes before F because that is the way it's sorted in this dictionary here and that's what lexiographically means so basically all this means is that the words in the dictionary are sorted the same way that it would be in a regular dictionary okay so now that we understand that let's take a look at these three statements here so first they tell us that we can assume that all letters are lowercase so that's good because we don't have to worry about any uppercase or lowercase and next they tell us that the dictionary is invalid if string a is a prefix of string B and B is appearing before a and I think this was just a misranslation because lint code is a Chinese website and I think what they mean here is let's say we have the word Apes if the next word in the dictionary is ape then the dictionary isn't valid because in a regular dictionary Apes would come after ape so if you have an invalid dictionary then that means we have to return an empty string because that means there's no actual way to derive the order of the language okay so now let's take a look at these two requirements here and to be honest with you I have no idea what number five means so we can just ignore that if anybody knows just leave it in the comments below but I couldn't figure it out and it doesn't really seem to affect the solution but number four does and we're told that there may be multiple valid orders of letters for example let's say we know that t comes before F and we also know that e comes before D but we don't know which one of these comes first or in between so for example our order could be e t f d or it could be t e d f we don't know and we're told here for link code to return the smallest and normal electrographical order so that would mean we would want to return the alphabetical version of it in the English language on Lee code I'm pretty sure they say you can return any combination so I'm going to approach the problem like that and when we get to the code I'll show you how to fix this part so I know that was a lot of explaining but I think if you understand what the problem is really asking then this problem goes from a hard to a medium so here average on the problem from the example and we're just going to solve it by hand so how do we know what letter comes before which letter in the alphabet well if you remember our English alphabet we know that r comes before art in the dictionary and because of this we know that the letter e comes before the letter T because of the way it's sorted so if we apply that principle to this example here let's take a look at our wrt and wrf well now we know that the letter T is supposed to come before the letter F in this alphabet so we can start a graph and the reason we're using the graph is because we want to know relationships and normally when you want to figure out some kind of relationship in a problem you're going to use a graph so let's put T in the node and make it point to F so that way when we Traverse the graph we start at T and we can map that in our output and then we can go to his neighbors and we can see that f is supposed to come afterwards okay so now we have this relationship here now let's go to our next two words we're done with wrt so now let's compare wrf and er what we're going to do is look at the first letter that's distinct between these two and we can see that W and E are the first distinct letters so we know that W comes before E so we're going to map w to e so the current relationship between the letters is W comes before e and t comes before F but we don't know anything else we don't know if e connects to T or if any other relationship happens here okay so now let's look at our next word so now we're going to compare ER to e t so now let's see the First characters are the same so that doesn't tell us anything new and now we have R and that comes before T so what we can do is say R comes before T but as you can see we already have a t node up here so we can actually just put this R before the T so now this is our current graph we have two different graphs that tell us R comes with 4T and t comes with 4f and the W comes before E so now let's take a look at these last two words here so if we take a look at the first distinct character policy we started the first character and we already see that e is different than R and what we can assume here is that e comes with four R so now we can map e and say it comes before r but as you can see we already have an e here and an R so we can actually just connect these two graphs here like this the final step is just to Output this as a string so our output has to be w e r t f because that is a valid order so we have to somehow Traverse this graph and get this output and there's two ways to Traverse this graph you can use DFS or you can use BFS and I'm going to be using DFS because I feel like it's simpler with BFS there's a lot of extra stuff you have to do and I don't feel like doing that I want to keep this code As Nice and simple as possible so you guys can understand it the only problem with doing a DFS solution is that if we do DFS starting from here and print out the output we're going to go all the way down to the very bottom and see this F here so we're going to print out our F first and then we pop back up to T so we print out T and then we do r e and w so our output would be this which is just the reverse version of this so in the end before returning we can just reverse this string and then DFS works just fine and this is also a cycle detection problem so for example if we had WF here then our e would also connect to the W and if we do DFS we're going to end up going into Loop so to detect that we have to keep track of what nodes we have visited so far so let's say we started w we will Mark that as visited and then we go to E and then we Mark that as visited when we go back to W we're going to see that we already visited it in our current DFS call and we can just return that as an invalid dictionary and that's basically it for this problem so basically this problem just breaks down to a DFS and cycle detection problem and there are a few other edge cases for example W can connect to F and this will be taken care of in the DFS call by itself we don't have to do anything special for that so now let's discuss the time complexity the tie complexity depends on the number of words we have and the characters in each word so for example our worst case could be that we visit every single character in every single word so we can say that the time is O of C where C is the number of letters in every word our space complexity would be o of V plus e where V is the number of nodes we have and E is the number of edges so now that we know that let's get into the code so first I'm going to separate the problem into different parts so it's easier to follow so the first thing we're going to do is make the graph then we're going to populate the graph next we're going to write our DFS function and then at the end we can iterate through our graph using rdfs and then at the end we can just return our result so what we're going to do is create a character graph and what we're going to do is initialize a empty hash map and our goal is going to be to have our hash map look like this so we're going to have our character let's say we are at B first and that's going to be mapped to the characters that come after it so for example let's say a comes after it and also C comes after it so our map would look something like this where we map our character to an array of characters that come after it so we're going to do for every word in words and for every character in that word what we're going to do is initialize our character graph at the Key C and give it an empty array the next thing we're going to do is populate our graph and the way we populate the graph is by taking word one and word two and seeing which character is different and then whatever character is different from word one goes into the key and the character that is different from more 2 comes after it for example we would have a and that would be mapped to B in our English letters so we're going to do for I in range of the length of words minus one the reason we're doing -1 is because one the reason we're doing -1 is because one the reason we're doing -1 is because we're going to be looking at the word afterwards and to not get an auto range error we need to do a minus one and you'll see why in a second so let's say word one is equal to words at I and where two is equal to words at I plus one so this is why we're doing the length of words minus one from here we're going to find our minimum length because we don't want to go out of bounds so we only want to look through as many characters as there are in the smallest string so we're going to do Min length is equal to the Min between the length of the words and then from here we can iterate through every single character and see which one is different so we're going to do 4J in range of Min length because that is the length of this model squared we're going to check if word one and J does not equal where two at J then that means they are different and if they're different then we want to add them to our hashmap so we're going to do character graph at the key word one at index J and then we're going to append our where to character to it so for example if we had ape and art then our key would be p and we're going to put r as its neighbor and if we find a character that doesn't match then that means we can just break this Loop so we're almost done populating the graph we just have to take care of the one Edge case where let's say word one is apes and where two is ape then that means the dictionary is invalid because Apes should not come before ape and to do that we just want to check if the length of word one is greater than the length of where two and the prefixes are the same so we would have word one from the beginning all the way up to the Min length and that should equal where two from the beginning all the way up to Min length so that means we have the same initial letters and word one is still bigger if that's the case we just return an empty string okay so at this point we have made our graph and we have populated the graph so now we can just iterate through the graph and then afterwards we can come back to our DFS and make that function so to iterate through the graph we just want to iterate for every character in our character graph and we just want to do our DFS function and I'm going to be calling our DFS function is cycle because that's what we're looking for so we're going to check if the graph is a cycle then we want to return an empty string because that means we found a cycle and that wouldn't be a valid dictionary so I'm not about our DFS function before we write the DFS function we want to initialize two things first we want to have a hash map and in this hash map we're going to keep track of our visited nodes and we also want to create a result array and in this result array we're going to store the letters revisit and then reverse him at the end so before we return the result we want to reverse the array and then at the end we can just convert our array to a string and the way to do that is by returning an empty string and then we join it with our result array so now all we have to do is make our DFS function so we're going to Define is cycle and we're going to be passing in a character and from there we want to check if you visited this character so if our character is in our visited set then that means we already visited it and we can just return whatever is stored in that value so we can return visited at the Key C so that way we don't have to do repeated work if we already visited a cell then we already know that there's either is a loop or there is not a loop at that point and the way we can break up this DFS call to make it make more sense this is going to be our check and if we pass our check then we can Mark our node as visited and after we do that we can just call DFS again on the remaining neighbors so we're going to do visited at the key c is now true because we're visiting it currently and now we want to do our DFS for all the neighbors we're going to do for neighbor in our character graph at the key CE so that means all the letters that come after it you want to iterate through those and create a graph now we want to check if those are a cycle as well so if is cycle for our neighbor then that means we can return true here because that would be a cycle and if it's not a cycle we can just Mark our notice not visited now because our DFS would be over and then at the end we can just append whatever character we're visiting to our Ray and return false down here because we did not find a cycle and that's our whole code and this would work on leak code but the problem is that on link code you can't just blindly iterate through the character graph you have the sorted by the keys so we're going to do character graph sorted by the keys and we also have to reverse it the reason we do this is because they want us to return it lexographically which means they want us to return it in English alphabetical order for some reason but either way for lead code you don't need this part you can just iterate through the character graph and that should work but just so you can see that it works on link code I'm going to submit it now and as you can see the solution is very fast and efficient and now I'll go through the code manually so because the code is huge I can't go through the whole code for every single word so I'm just going to give you the main idea from each block so the first thing we're doing is making a graph and what we're doing is actually just making a hash map and giving every character an empty array so all it looks like is like this for example let's say we have W R and T all of these would be mapped to an empty array from here we would populate the graph so let's just take the first two words here wrt and wrf we would check if these are valid dictionary entries and that's what the if block does here so for example I mentioned it before but if we had apes and ape in this order then that means this would be an invalid dictionary because the word Apes cannot come before the word ape but that's not the case here these are valid dictionary entries so from here we would iterate through every character in the smallest word and as soon as you find a different character then we want to append a different character from where two onto the word one key so for example here we have W and w u the same R and R are the same and then you have t and F so now we're going to map f as the letter that comes after T so this would be in the array here so here I've just populated the map but there is one difference compared to the normal example where F has a neighbor W so there's a graph here instead of just being one direct line F not conducts back to W and the reason I'm doing that is to show you what is cycle does so here I've drawn a visited hashmap and now let's do our DFS so let's say we started this W here just to keep things simple so we start at w and we check if it's in our visited set well it's not so we can go on to here and Mark it as true that we have visited it and now we go through every neighbor and for w and the only neighbor is e so now we're at e and we'll do the same thing we check if it's in our set and it's not it'll be mark it as true and we do that all the way through r t and F so now R is true T is true and now we have F so once we go in our cycle we see that it's not in our set so we can mark it as true and now when you visit all the neighbors for f we're going to see that we're going to go back to w and now our c is going to be equal to W and we check if C is in our visited set and we see that W is and we're going to return true here and once we return true there this is going to return true so that means this if statement here is going to get triggered and we're going to get an empty string and that's how we detect the cycle so that'll say it's not a cycle and we start doing DFS at w well what we're going to do there just go to the deepest node and then add that to the result array so we're going to add F to our result array we're going to have F and then we're going to put t r e and w and then from here we're going to reverse our array so we're going to have w e r t f I'm going to convert it to a string down here and this would be our final result and this would be correct if this video helped me in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
|
Alien Dictionary
|
alien-dictionary
|
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.
Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.
**Example 1:**
**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:** "wertf "
**Example 2:**
**Input:** words = \[ "z ", "x "\]
**Output:** "zx "
**Example 3:**
**Input:** words = \[ "z ", "x ", "z "\]
**Output:** " "
**Explanation:** The order is invalid, so return ` " "`.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.
| null |
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Hard
|
210
|
205 |
here is Misha winter fashion high five rings snt morphing with interest mafik tongue with Andryukha students here are the men's guys in bed with VAT yes targa sing se and the sun and the wind blows and for a little mary kay sensor ceramicas secret incantation induction and markers charge handed over Crimea from where charger years makes any one game about Dima's studio study in safe and ladies to get here i and ii maps a whole pud map studios per year language house and imaging with the IMF beat all in one ou hey ou HIV maps. inside out which means that are weak and falls under space so this is how it works guys Aikhal explanations and if it does it as quickly like a sorcerer and doesn’t work our entire sequencing scene and doesn’t work our entire sequencing scene and doesn’t work our entire sequencing scene you hold us all no problem now 108 guys ok- docks have heard the races and beating love dies ist ein and does not fall with oh. with wings on the index out with mts and DPRK desik sample and water with me without i think left the FSB personal income tax if i laid my site Botvinnik srach ectomorphs if allowed with this aura estimating the charger and all i have a drink tea is not them here and the whole month before without sex not also more FIG English sauce basic Lee Cindy for eight miles and more or more FIG and trading and [ __ ] her FIG and trading and [ __ ] her FIG and trading and [ __ ] her battle Justin Theroux andy and a fur die for you simply page guys matron sorcerer here works at me sad Russian Ministry of Foreign Affairs and submit to get completely find sound and simply is bad guys even jodi statue predict centuries subscribe evening christ african cord not and a and the northern video rice cup
|
Isomorphic Strings
|
isomorphic-strings
|
Given two strings `s` and `t`, _determine if they are isomorphic_.
Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
**Example 1:**
**Input:** s = "egg", t = "add"
**Output:** true
**Example 2:**
**Input:** s = "foo", t = "bar"
**Output:** false
**Example 3:**
**Input:** s = "paper", t = "title"
**Output:** true
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `t.length == s.length`
* `s` and `t` consist of any valid ascii character.
| null |
Hash Table,String
|
Easy
|
290
|
1,460 |
welcome guys so at least we today uh we are solving this legal video uh one four six zero so make two arrays equal by reversing sub arrays so given to a race with equal length target and array and you can select any non-empty sub and you can select any non-empty sub and you can select any non-empty sub array at the reverse it you are allowed to make any number of steps so return to if you can make arrow uh err equal to this array equal to target okay so you can see right simple target the one two three four two four one three and so it's true you can reverse the uh two four one this sub array becomes this and uh doing this okay yeah and the this is the same and this is also you can change this 112 okay so let me just uh give you an answer so basically once if you can change any two uh to an adjacent array by reversing it actually you can make a permutation of the original target oh sorry original array so that means if any array right any array with the same permutation can always be uh connected it can always be uh trend uh can always be transformed into the target so basically if target is the permutation of the your original array then the answer must be true so all you need to know is that you just need to check the target is the permutation of the array so if target is a permutation of rate and the answer is true otherwise it's false okay so yeah this is the same right and at least it's not impossible because there's a 911 okay uh so it's very so uh what we need to do is basically we sorted the target and then salty array so if you're talking array uh if the target is actually the permutation of array then you just return then this must return true right else it's else will be false so yeah this is the answer okay so uh one another reason is the symmetric group uh is generated by the adjacent uh permutation so basically if you can permute uh any two uh you can put if you can promote any two uh numbers in your array then you can generate all the symmetry group okay so this is mathematical way to say this yeah but basically you just uh list the simple fact so this problem looks difficult but uh actually the answer is very easy okay yeah this is just stands okay and uh i will see you guys in the other videos be sure to subscribe to my channel thanks
|
Make Two Arrays Equal by Reversing Subarrays
|
number-of-substrings-containing-all-three-characters
|
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000`
|
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
|
Hash Table,String,Sliding Window
|
Medium
|
2187
|
1,326 |
all right let's take a look at lead code 1326 minimum number of taps to open to water a garden so the question is going to give us an input an n value which tells us how many units large the garden is and then it gives us a range list so all of these numbers so the first index represents the sprinkler size that the 0th sprinkler can reach so the zeroth sprinkler can sprinkle three units in the left direction and three units in the right direction and then sprinkler at index one can sprinkle four units to the left and four units to the right and then you know same thing goes with this next sprinkler the next sprinkler can sprinkle one unit to the left and one unit to the right so the question is they want you to see what's the minimum number of sprinklers you need to turn on in order to cover the whole n units right from 0 to n what's the minimum number of faucets sprinklers you need to turn on in order to cover every unit in that range so the first thing we want so this is a three part problem so the first thing we want to do is create the intervals so what do i mean by intervals so i kind of already you know explained it right but you know the faucet the sprinkler at index 0 can sprinkle three units to the left and three units to the right so we want to express that as a as an interval so the interval can be written as zero to three so if it can sprinkle into the negative values we don't really care because um that's not helping us solve the issue at hand right because all they care about is covering um zero to n so that's our goal is to cover all the units from zero to n so if we can cover anything below zero we don't really care about that so even though this sprinkler the first sprinkler and maybe the last sprinkler would also cover into the values past five but like past n we don't care about those values all we care about is the values from zero to n so we can kind of just you know take that into account when we're creating the intervals so yeah just you know set the lower bound as zero and set the upper bound is five you know anything above and below that we don't really care okay so the first interval is zero to three right so you know we can go from the zeroth unit to the third unit using just the first sprinkler the second sprinkler or sprinkler at index one can go from the zeroth unit to the fifth unit and then yada so you know sprinkler at index two can go from the first unit to the third unit the next one can go from the second unit to the fourth unit and then yeah so these two sprinklers at index four and index five they can't cover anything right but they can only cover themselves they can only sprinkle on four and five to five okay so hopefully you understand how to create the intervals that's pretty straightforward so what can we do with the intervals now so the idea is that once we've created these intervals now we can convert this to a jump game 2 problem so i've already done a video on jump game 2 but i'm still going to you know recap how to solve how to do that algorithm in this video because i don't want you guys to have to um redirect to the other video i mean if you want to reinforce your learning then by all means go ahead and check out the other video as well but you'll be able to solve this problem just from watching this video so once we have the intervals then what we're going to do is we're going to create we're going to reprocess the intervals into a format which is you know the same as the format for jump game too that way we can just directly apply the jump game to algorithm onto it so we need to create a one-dimensional so we need to create a one-dimensional so we need to create a one-dimensional list right because this is like a 2d nested list pretty much and yeah so we want to convert it into the 1d list to do the jump game 2 algo on it so in order to do that basically we're going to have an array called best reaches and the idea is each index is just going to represent the furthest possible unit that sprinkler can reach so um yeah so sprinkler zero can reach uh can reach the fifth unit right we see here there's two sprinklers that can start at zero and the furthest one of those two is the one that ends at unit five and then um here for index one um so i guess it's not necessarily saying the sprinkler can reach number five but it's saying that um starting from this unit what's the furthest unit we can reach if we started at that unit so starting at unit one the furthest we can reach is unit three and you can see from that interval here and then the next one is starting at unit two what's the furthest unit we can reach and there's only one option and that's four and then starting at unit three what's the furthest we can reach well there's actually nothing that starts at unit three so we just skip that we leave it blank and then same with four what's the farthest we can reach starting at unit four it's just four and then same with five the furthest we can reach starting at unit five is unit five and so um actually we're going to have to initialize an array that's you know as big as their um as big as their boundaries 10 to the fourth and yeah i'll kind of cover why we need to do that later but yeah just know that when you create this best reaches array you're going to have to initialize it to be the size of 10 to the fourth um yeah okay so um so once we have this best reaches now we can do the jump game 2 algorithm so if you are not familiar with that then i'll go over that again in this video so basically we have three variables so we have a max reach uh which just is like a running you know running variable that keeps track of the best possible the furthest possible location we can reach we have a jumps to keep track of how many jumps we've taken and we have a layer end to pretty much um so okay i forgot to mention so jump game 2 is actually innately it's actually a breath first search type of problem so we might not see that because we're just given a you know a 1d list but actually this is a breath first search type of problem and we can treat it layer by layer so that's why i have the layer end here and i'll explain that in a second so if we kind of break this down layer by layer so everything we can reach from the with zero jumps is considered our zeroth layer so we're plopped down onto this um index zero right without having to take any jumps we're starting here so then from this location from layer zero we can reach all of these locations we can reach all these numbers two one and zero so this whole section right here that's your layer one because you can reach all of those from layer zero and then our layer two um well technically it doesn't exist in this problem because um we can never cross this um threshold but um yeah so basically you kind of get the idea with the layers right so you know layer zero is where we start and then layer one is everything that we can get to from the stuff at layer zero and then everything at layer two is all the locations we can get to from layer one okay so that's kind of how we're going to that's kind of how you find the minimum number of jumps it takes to get to the end right it's just uh whatever layer that um that final location is placed into right so right i already told you that max reach is going to just hold you know a running sum of the max possible the furthest possible location we can reach so let's kind of just walk through this example here so we just do a linear walkthrough of this array so i have the index indexes you know written out here and we have our i pointer so the first thing we do is let me reset this real quick okay the first thing we do is we just iterate through and one condition we have to check is if i is equal to the layer end that means we've finished looking at every node at that layer if you will and then if you've finished looking at every node at that layer then you can increase your layer count so jumps is essentially the number of layers so you can increment your jumps to one you can increment by one so actually before you do that you want to update your max reach right so if you forgot how to do that basically the max location you can reach from index zero is um three right because if you just add three to zero you get three right because from here you can go out to one two three right so our max reach right now is three and then our um layer and so our jumps also increments by one because we just finished looking at everything in layer 0 so now we have to go to layer 1 and then our layer end is also going to be updated to match whatever the max reach is so basically to recap what these three variables mean right now they're saying that with one jump the furthest possible location you can reach is three and that checks out doesn't it right you know with one jump from here with one jump the furthest we can get to is this location right so that makes sense and that's where our first layer ends as well right your first layer ends wherever that you know the furthest it can reach is for that layer so right so after we finish processing that zeroth index now we go to the first index and then we try to update our max reach so at every index we're going to just try to update max reach so what's the maximum we can reach from this location well we can go 2 in the positive direction right so that will land us at index 3 right so uh three is already equal to three so we don't update the max reach and then are we at the end of this layer no we're not the end of the layer is at index three right so we don't increment the layer count or we don't increment jumps so let's keep iterating until we reach the end of the layer so now we're at the next index and we try to update max reach so what's the maximum jump we can what's the maximum location we can get to i'm using a jump size of one here it's just you know the next index right so we don't actually update the max reach because three is equal to three and then um yeah are we at the end of this layer no we're not the end of the layer is the next index right so let's keep going so now we've gone to this location and before we so we know that this is the end of the layer but before we increment the layer count let's first try to update our max reach so the max jump size we can take at this location is zero so actually our max reach won't change so now let's update the layer count so layers goes up to two and the um layer end also um gets updated to match whatever the max the current max reach is holding right so that's three so it doesn't actually get updated so what so um i use this example because let's keep going forward um okay first to recap right so what these three variables are saying right now it's saying that with two jumps the furthest we can get to is location three right so with two jumps you know no matter you can pause the video you can try for yourself starting at this zeroth index with two jumps the furthest we can get to is index three isn't that right you know if we were to take three jumps here and then take a jump of zero we'd still be here right or if we take um you know a jump size of one at first and then we take a jump size of two you know we're still landing at index three right so with two jump sizes no matter how you do it the furthest you can reach is index three okay so now i use this example for a reason because um in jump game two they told you that there'd always be a valid path to reach the end but this question it's not guaranteed that you can always cover the whole interval right they say that you should return negative one if you can't water the whole interval okay so anyways yeah so pretty much the idea is um you know once we finished looking at this layer two now we're gonna move ahead and um yeah so now we're at index um four and our current max reaches three so that means we couldn't have actually gotten to index four if you know our max reach is lower than the current index we're at so if we ever come to a situation where we have surpassed our current index is greater than our max reach we can immediately just return you know negative one because that means that there is no way to water this interval this position right here and um or sorry there's there was no way to reach this location here at index four you know right no matter how we you know how no matter which combination of jumps we take starting here there's no way to reach this fourth index so um yeah like i said the if the index that we're on is greater than the max reach then we can return uh negative one and um yeah so that's pretty much the algorithm um so i mentioned earlier that you want to initialize this best reaches array to you want to just initialize it to be a list that is um size 10 000 um 10 000 1 and 10 000 1 actually and the reason you do this is because this end value they give you could actually be you know the n value could be like 10 000. the n value could actually be 10 000 or something and um you know maybe their intervals only cover up to 100 or something right so then you would need to you need to account for iterating all the way through to 10 000 yeah so that's why you need to create the initial best reaches array to be the size of ten thousand okay hopefully you guys understood that this uh it's hard to explain jump game two it's not very intuitive to be honest with you but if you have done jump game 2 before then this problem should not be too hard so like to recap the first thing you want to do is create the intervals and then after that you want to create the list of best reaches you know using these intervals and then with the best reaches you can just apply the jump game 2 algorithm all right if you have any questions please leave in the comments hopefully that was a good enough explanation um yeah so leave some constructive feedback um i'm sorry if i stumbled across my words a lot during this video but um yeah i feel like that's the best i can do so hopefully you guys understood that if you don't understand this video maybe check out my jump game 2 video maybe that's a little bit more well done on that jump game part but um yeah hope you guys enjoyed and thanks for watching
|
Minimum Number of Taps to Open to Water a Garden
|
sum-of-floored-pairs
|
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`).
There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden.
Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open.
Return _the minimum number of taps_ that should be open to water the whole garden, If the garden cannot be watered return **\-1**.
**Example 1:**
**Input:** n = 5, ranges = \[3,4,1,1,0,0\]
**Output:** 1
**Explanation:** The tap at point 0 can cover the interval \[-3,3\]
The tap at point 1 can cover the interval \[-3,5\]
The tap at point 2 can cover the interval \[1,3\]
The tap at point 3 can cover the interval \[2,4\]
The tap at point 4 can cover the interval \[4,4\]
The tap at point 5 can cover the interval \[5,5\]
Opening Only the second tap will water the whole garden \[0,5\]
**Example 2:**
**Input:** n = 3, ranges = \[0,0,0,0\]
**Output:** -1
**Explanation:** Even if you activate all the four taps you cannot water the whole garden.
**Constraints:**
* `1 <= n <= 104`
* `ranges.length == n + 1`
* `0 <= ranges[i] <= 100`
|
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
|
Array,Math,Binary Search,Prefix Sum
|
Hard
| null |
1,385 |
hello everyone here's your friend one punch coder today we're gonna talk about legal question 1385 finding the distance value between two arrays so this is easy questions if you haven't read the question yet please pause the video for one second and just to read the description and anus then what is asking right it is a question so it won't be hard to solve as long as we understand what is asking and to me my complain about this question is it's a little hard to understand when I really so it's asking the distance value and the distance value is defined as a number of elements array one I such that there is not any element array 2j where the distance is less than or equal to D so I was like why has to say there is not any can't you just say there's no habit and anyway so if we check out this example here well know what is asking so basically the example was iterate through everyone and it picks each element in every one and compare with all the element in array two and make sure the distance is less than or equal to sorry greater than two greater than the distance D so for the example for is for a use for to compare with all the elements in your way to and they are all greater than two which is the distance and five is also valid in that case so there will be one and two elements in a real one that is satisfy this condition so it's returning to and the eight is not because when 8 minus 10 and the absolute value will be 2 and that distance is less than integer D so it's a null value so now the most intuitive oi as you my thought will be just doing a nested loop where you to rate through everyone there were two and compare value and see if it works out and that's exactly what I'm gonna do now so we're gonna have a answer as a variable which we're gonna return in the very end and we're gonna start with a easy follow-up here start with a easy follow-up here start with a easy follow-up here I gotta call it you know what I couldn't call it thanks because I sounds more like a index so for X so here gonna have a count you know way what are you use for yeah so if the if it doesn't satisfy the condition then the count become to zero and would break the loop and the way add it or not added because count is zero so in that way we can increment answers as long as they satisfy the condition and very end return answer so we're gonna do a test here see if it works yes it works so this is very intuitive and that's not important that's not the important thing I want to talk about here today because there's better way this method actually is taking Oh times in so we can say m is the Lance of everyone and is the Lance of array too and it's taking this amount of time but there's a better way so how are you gonna do a better way and what's the temp compel time complicity of the better way is using binary search so using the binary search we can decrease time complexity to log and how and here's what I'm gonna do so I'm gonna give you a very simple demonstration here we're gonna take the first example right here so now I have two arrays and nothing are sorted even though I mean this the first one is already sorted but it's not guaranteed by the question so what we're gonna do is we're gonna sort the second array and well I mean you can't store the first way it doesn't matter so but here I got a sore the second array and we will have four five eight in the first one it's already sorted I didn't sort it and second one if I saw will be looked like one eight nine ten so and here now I'm gonna do a binary search for each element in array one so for example I can use for to do a binary search in array two like sorted and find where is the position to insert this value for example in this case the position the most left position the first position to insert for will be the index one which will be the index of eight and we have things like this if we insert four to the right the array to right and now we see the minimum distance for four will be either 1 minus 4 or 4 minus 8 the absolute of these two values because these are forced neighbors and we find the I'm just write it down here for - a right so if we find it down here for - a right so if we find it down here for - a right so if we find the minimum between these two X and this is y so if we find the minimum between these 2 and if the minimum distance is greater than D that means our the other distance will definitely be greater than D so there's no point for us to compare 4 to any other value in array 2 other than its two neighbors right and that's exactly what we're gonna do we do sort with sort we do binary search and we compare yeah and we'll get the answer if we're doing this way so there we go so now we're going to start Co same thing star wins a answer variable which is 0 and like I said we're gonna sort it first we're gonna do every to the sword we're gonna need the Lance of RA to for longer track and now we're gonna eat to rate through everyone we're not in array one here we're gonna do the binary search let me do some common here sort I gotta call this index and then we can use Python stare library by sex to do a binary search by second left will be giving you the most left index to insert a certain value to a sorted array so are you so you will be array two knobs then now we're gonna have an interest basically just a minimum distance for num2 for now and their oneness we're gonna initialize this to a very large number I can do it and now what I'm gonna do is we're gonna do a boundary check is when you do a binary search the index could be 0 then in that case there is no left neighbor you could also be the last element the last position then there is no right neighbor so we want to make sure we check that now we're gonna do index greater than 0 if index is greater than 0 that means it has a left neighbor than menges equals 2x minus 1 it's Neph left neighbor now we're gonna get a left neighbor for num and you're getting through the same thing for s right neighbor and the right neighbor will be index case we're using by bisect left the and then the right neighbor will be just index won't be in X plus one this is not correct and yeah now we get the minimum distance for number no now we do compare if it's greater than D then answer plus one otherwise we return answer and let's see if this works oh you know what before that let me all right try okay it works well let's submit this see if it's faster yeah slightly faster and yeah as you can see here the time complexity here as sort will be n log N and here will be a loop that'll be a simply om and since it's oh and here the binary search will be sorry here is o N and here is o an and it will be bonded by om so the whole thing will be actually my mistake and log in you got so yeah this is an easy question but I think there you can make it more interesting by thinking some better approach so I think this is it for today I'm your friend one punch coder I hope to see you guys next time Janet
|
Find the Distance Value Between Two Arrays
|
number-of-ways-to-build-house-of-cards
|
Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100`
|
If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles.
|
Math,Dynamic Programming
|
Medium
|
815
|
1,704 |
hey this is ike so we're back on leak code again today i'm just going to go ahead and do pick one we'll go for an easy problem uh i'll just keep clicking pick one until we get something all right so this problem says determine if string halves are alike so you are given a string s of even length split the string into two halves of equal lengths and let a be the first half and b be the second half so two strings are alike if they have the same number of vowels okay and notice that s contains uppercase and lowercase letters and so return true if a and b are alike otherwise return false uh so let's look at some examples so the input is s equals book uh output will be true because b oh so the two halves will be b o and then okay let me zoom in some more actually so the first half will be bo then the second half will be okay and so there's just one vowel in uh o and there's just one vowel in bo and then one vowel in okay so each half has the same number of uh same number of vowels i wonder what happens if the string isn't of even length though uh oh okay you're given a string s of even length perfect so first i think the first thing we want to do is just to successfully split the string in half so let's try to do let's say split string split the string in half and we can say let's do so we know the length of the string so we can just say uh first we're going to say part 1 is equal to s and then it's going to be everything up until the halfway point so that should be the length of s divided by two and we can kind of verify that let's just say our string is the one in a book so then we want to technically go up to because this is zero these are just putting numbers at the corresponding positions this is 0 1 2 3. so we technically want to end because when we use a splicing like this we want to put in the location 1 pass we want to put in the number of one past what we're looking for so if we just want bo that means that we need to go from 0 to 3 or sorry 0 to 2 so then this should be good because the length of s is 4 in this case four divided by two is two and we're going from zero to two so that means we should just get bo so then let's try for part two so then part two should be equal to s and we'll splice it since we had this as the ending point for part one uh the starting point is inclusive unlike the ending point so we should just be able to say length of s divided by two to the end and let's just go ahead and print part one and part two and run it oh whoops wait oh wow i was actually i didn't change the language to python uh so let's do python 3. i copied the code from before so i'll just paste it in and move this back all right so now in the proper language let's uh click let's click run code so slice indices must be integers or none so i'm guessing what happened is when i did len of s divided by 2 that converted it to a float so i should just be able to cast it back here okay so uh we didn't output anything but we can see that in the standard output we got bo and then okay so that means that we successfully split the string into two parts so let's now try to go into the next portion which should be let's try to count the number of vowels in each of the parts so we might as well make a another function and just call it count vowel since we're gonna have to do it for uh we're gonna have to do it for both parts of the string so just say def count vowels and we want to take in a string we'll call it we'll have to put self in here and we'll take in a string s and okay so we know that the vowels are a e i o u so let's do let's just say vowels this can actually be a constant too so we don't have to keep reevaluating it so we'll say vowels it's just going to be equal to i'll say vowels it's going to be equal to a e i o u i'm just going to keep it lower case and we'll see why in a second um so we can then i think we can just run through the string s and then see if its letters appear in vowels so i'll just say like count equals zero and we'll say uh we'll say for character let's say for c in s uh if c is in vowels then count plus equals one uh and hopefully this works i'm not sure if we need to put self dot in front of vowels when we use it but uh that's something we'll just have to try it out so let's delete the print statement and let's instead print count vowels let's do count vowels part one so that's a problem since it's a class method we should put self dot count vowels yeah so i think this actually i think this needs a self in front of it as well uh because we did vowels equals a iou and then we want to say if c in self.vowels so it printed out none and that's because i did not return count okay so our output was one and so we just did this for part one and bo does have a single vowel so that looks good uh we can also do the same thing for part two just to see what we get we should get one and then one after we run this okay cool so we see uh input was booked and then standard output is one and then one and so i guess the final part of this problem should be we need to return true or false whether they have the same number of values so i think we can just say return self.count self.count self.count vowels part 1 equal to self.count vowels part 1 equal to self.count vowels part 1 equal to self.count vowels part 2. let's run it cool yeah so we just evaluated the as a boolean expression here to get whether the counts are the same for part one and part two um but i think there's still something we need to do so if we change let's actually let's take out these print statements here for now actually no let's do them in and first do this test case uh what if we did something like b capital o okay wrong answer so it seems as though part one didn't successfully count the uppercase o and so let's see yeah so part one didn't count the didn't successfully count the uppercase o so this should be something that we can uh fix here and we might as well fix it right in the count vowels function so i guess what we can do is probably just convert this string to be lowercase since vowels are all uh lowercase so let's see or actually uh i guess actually a better way would probably just be to include the uppercase vowels in the constant string because uh if we try to if we it'll probably waste it's kind of a nitpick but uh it'll be faster to just have a constant with vowel with all the vowels lowercase and uppercase as opposed to converting the string to all lowercase each time we call this function because that'll actually copy the string every time since strings are immutable uh so actually yeah i think it'll probably be better to fix it this way so let's try this again so our input is b capital o okay and let's run it all right cool so it looks like the counts were correct and the output was correct uh let's see if there's anything that we could be missing uh what about so we know the string is of even length um and so these should work even if our string is of length uh can we get a string of length zero here though let's kind of want to see okay constraints two is less than or equal to s dot length it's less than or equal to a thousand okay so we won't get anything that's equal to zero all right so i think we're good i'm just gonna take out the i'll just comment out the print statements and we can go ahead and click submit all right looks like it worked so we just solved determine if string halves are alike if you found this video useful please leave a like and subscribe and if you want to see any other programming content just let me know in the comments down below thanks
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
1,363 |
Minimum that you will see the channel man notification will be visible whose name is Largest Multiple of Three To see To see To see something keep writing this Mukesh Open and give and interiors of its internal Jasmine Table of Three Left Hand Witch Formed By contesting Samudra given it's an order tap critical problem since the answer is not fit and zodiac in the answer is worst thing I am this no answer return is extended the then let's see what questions let's see we refuse you give me It is said that you will get an egg of interest. Okay, okay, what do you want to tell me, by using it vigorously, you can make the largest medical officer. Okay, so look at you, cut your lakhs. Is it meant in capitals that the southern form by Contesting from the giver digits in any order of merit can be cut in this way. Okay, that is disgusting, so this is the question and you have to arrange it in this way or on which date you have to install it, whatever becomes possible on this planet. And if it is not being made and now let us do it, how to do it, we will get that we delete most of you from it, we can add either the address that will be made in it or the answer that is not there, okay so That answer is not possible Answer is not possible Not possible If the answer is possible then we will read Ignore Stuart Broad too low only to delete to use internet Cheese and all the rest like this What is this answer Okay now this is not a little Now you can do a little bit with this, butter it and let's go a little further, so how to do that issue, I mean to say the truth, you want to ask, if you see, I will be a little patient if it will be in how, okay and In that we next Sunday that for any number to be encroachment free what union number when time 108 mantra is ok which with whole number gents time under 273 and that three cases comfortable and thing is ok on monday to chitthi Okay, now what is known in the part, the master is revealed, what will we do, we will kiss you on the cheek and understand, we will send the whole, we will question the whole, we will say that the relation of this whole, say that we will say that the relation of this whole, facing the whole, in time, we shared the ribbon. We will exploit this question not only and will share it. Okay, we are busy, you will do the next work, we will check whether Samvat is equal in Urdu, is this the song that is being made, is it ours, are we making it, if our already method. Multiple Sambhar is coming, who is comfortable emperor since December last year, so what will we return and of course, we will return this episode by exploding, folding and resorting, we will make it silent, okay and this is shoot me shoot. Cancer in se and here the largest one digit is that from death to your friend this is our palazzo number if you and solar therefore shift in decreasing order okay then this one is happy if all of us are already coming three. I will delete all these, I have given three to one in April, so send this time of sex of images, gram with multiple husbands and will give 1200, then in this case, we who are already subscribed, printer 's happiness, 's happiness, 's happiness, this , , , hence song. ASmall 351 Okay if after connecting with the evening there is Nidra Devi Rao then we will go so we can do one thing a common prescription that from the whole to the whole such any which is the smallest such number then there is a little number which is one reminder It is giving okay, it was present along with you will remove it, this is the problem, the form wants two three layers, so this year the Election Commission went to Raghavan, so if this mixture is the smallest number, it is a false record, except a little number which is three like this is present. If there are, then we will do the fingers. Okay, the quantity of landing and the test was to be done at this time. And this which is always the attention which is the number sir like per hour Google Plus vote in the deficit is one then the cover loot the smallest number, we click on mode and do it there. If it is giving then 13 - it will happen if the pressure is increased but if 13 - it will happen if the pressure is increased but if 13 - it will happen if the pressure is increased but if this comes online then it seems good, such blood will go absolutely accurate and because I put the rule and on, then at this time which we have, madness is set to maximum. You can do it, okay, then the taste present on it is definitely one, just from the beginning, if there is a plate with a twist here, it is illegal to remove it from the lab assistant, it is prohibited, but it is not so, it is available only by turning on the mode, so Amazon, we basically give When there were two people including one time, this also remembers, these three and believe and three two come, both want to be of Ankit, so this is one model, patience and two are Montu, after watering, you are Bal Gandharva, this is a cash account. Some of the important and former MLAs have expressed their own allegations that if we remove the forest, if our forest is in a mood, you will remove such a number whose money should be removed and the number whose money is being diverted to make extra, then that. Will you take the mind with you or the money, both the legs which will bring mode two, then because both the elders and others will be in pieces, the over four zero police station and what happens to us, four more is free for this, it is 1.5, don't free for this, it is 1.5, don't free for this, it is 1.5, don't become okay. So, if you want to say something like this, it is Delhi proof for him, but he will get some idea as to why he is doing this, okay, so if it is going to be som more than a code two, then I go, then remove one mode of exile, or two modes, twice. Remove it, okay, those two are not aware, then those who will be the youngest are okay, list, the youngest son was born today, who will be the one who turns on the mode, you are giving, send the two of the Mathri house, please tell me, it is okay to remove those two. Make it and the remaining numbers will be made from our sea which will be exactly 30 ok and if not we find any such number which is missing on my blog where it is said that if I say this on Facebook 1234 then he will explain it. Its time will come, its satisfaction question will come and what is Saffron Motu, okay, the same thing happens, we will remove the photo or we will just put the band, then two three four will save and its time will give you only external jobs 432 low returns. Okay, we will do something like this, but if in our case something as simple as 12345 is fine here, then we would like to tell you that if AIIMS does not do this and we have only 135, yes then that. What will we do in this way, and so we will keep deleting the number until all of them see what is happening by turning on the mode here, they are making pranam by auto doing it, they have the knowledge of 513 by getting votes, here give us either one. We will make a turn, what is it first, I swear to you for 1 minute, first let's see this, understand why shift is equal to four, golden is already dead table and dutiable, so we will not do anything in this, now we will consult 345, I have a problem, if someone says to do, then what? It happens that the one who is on mode is not coming, National Health will give stomach, we have to give mock drill, so we give five from here, first understand the whole question, after that, how to set this dry, okay, absolutely try and think about it. If you want to dip some one flashing then either remove one dam which is model K10 or two not been able toe 1282 ok if some mode is giving free look into two then either one mode of three lootwa this is some number which will be present A little bit like this, some number which is small in juice, who are you down on the side, like this number which you are giving by peacock udder, you are cute and if you are not a traveler, there is no one nearby again 29 2012 We had made two We will go and tap it, I should go to Mumbai, okay, if he is saying so, he will take tension from us, call the font and talk to him, we will have it, we will remove it, loot everything, you are unique in some of it and in a way If it is 231, then this is Wave's, we will give 3202, okay, then we will put it, okay, but message to and I definitely have something, it is 4505, then there was a course, so where will all these Edisons be with us, you are sitting on the table, please burn your Edison, okay. So here also it would be useful to say but one thing is that the habit of asking should become like this, Singh, either make a free 5th park near me, then like this, if we definitely give that, then 512 should come, now you see we have to ask for votes. There is a monkey but the two auto guys are Pacific, this is Montu and now one guy is standing green, famous service corruption, our mode is off, there will be no Manglik fault here, if something like this happens but in this case, if something like this happens then answer It is not possible MP Singh Redhu, there will be a last year in this also that the answer is not for school admission, if it is not on the right side by a quarter of an inch, then to solve a country like India, celebrate him and his and leave the city. Let's put the message in place in the draw and give it colors. Okay and this is our spongy ghat. Now let's sew on it and see how we're going to paint it. So now let's fold it into quarters. Grade Prohibition So first of all we became handsome loot hai in were nor them lap bless oo [ were nor them lap bless oo ki ne song ki we turn free leg you hai if till monday only ghrit hai i will always work in chickens so that they sindhi Cultures let's have a party on this in English A node 60 days Okay okay we have folded and Sharma ji Guru ji wow there is a woman who is not like a bull we will take her if you have actually taken it from the side then the course we all scripted check Will you say that there is only one digit and MS Word Loot-Loot-Loot-Loot Pandey, this Eid has come, Jai Hind, why not give candy crush Lutiya's mantra, which is martyr, the obstacle has been taken away, we will get frills, okay, we will start the exam, that's why and enter that's why Acid and Shubhendu Animation Iodine President SC Code S What kind of photo editing is this, now we have to enter, stir well done, then if my pada hua digit off is table and I am confident, then only the limit is fixed Jai Hind Dainik A A1 Indira friends, you are ok, now we will remain half, what will we do next, only then we will erase you from 443 issues, this is our honor, this is the answer to 320, what will we do, we will do their work as an engine, we will do this Our lion is if one asset even model makes pimple two, if we have knowledge, then what will we do, we will reverse this, either we will make one, if the reminder is closed, then we are the two with two reminders, okay, then let's do one puja. Live a difficult situation means reminder that the temples are okay find the sea but okay so for this is him zinc iodine is clear what we will do we want to finalize which is the website which remains tied after death is the temples of the body So okay let's see that in this we need only one number, you were smart in this exact date off side that there is a 121, so it means this is the smallest talk, this is looking at the short hair, so what will we do, ideal account, we will do this problem. And we will share basically after this we will simply break the digits of I this then minus point from here if you do not message this volume do not try this one that we have included and if it is not available at the time of this Dual this Note is ideal for prohibition, I ignore DJ sound, we will take a notable account, now two numbers are required which subscribe us, our question means respect to you, the number is required as we give that test series page subscribe if the person's name will be subscribe button Understood that by which number we can and we will click on it that it is Effigy and I want to equal to how to mystery looting house breaks, then if it is such a case, then we will open that. You get them implanted, our answer is ok, unmute it with us, then if ID xc90 is equal to minus one, then first it will have to be updated, this bell will come, XPS of Jio egg 125 healthcare will have to be done in end side effects cs6 turn off 12225 We will give and collect it from here, okay, people will sit from here and as soon as the second is over, the dead body will be found, whose body is being found in two of the wards. Okay, take it now, it will be completely looted, after the people are finished, we will check whether you agree. A scene of Vansh that if I have got Guddu - Bane Luta then we will do it so that if I have got Guddu - Bane Luta then we will do it so that if I have got Guddu - Bane Luta then we will do it so that off side effects cs5 world tour of wishes 125 - we will stop and like this from here wishes 125 - we will stop and like this from here wishes 125 - we will stop and like this from here we will work identified s90 baby, it is fixed how to his income of admission open If this is not found towards the for all type, then we will cover up the officer problem with someone agreeable to us, then do it with us, that the ideal person has become, if it had not happened, I have two such people, now we will find such people, if then Apps are not the second bond among such people, till now the update means that if you have not got such a thing, then if you got the first one, then you must have got the second one, neither if the second one is from your heart, then we will divide both of them to the maximum of 2012 and why are we fasting for this last. In the weekly income tax, which is allowed, and if we do not find even 2 ₹2 modes, then and if we do not find even 2 ₹2 modes, then and if we do not find even 2 ₹2 modes, then we will do the letter end extension, now we will do the same thing for this, we will do the same thing from the front, if Our honor will be 3.2, that will if Our honor will be 3.2, that will if Our honor will be 3.2, that will probably be the record, so let's see what we will do if you live in it. So let's see what we all will do in motorcycle two, then do the same work as we did earlier in this case. So, I have 20 minutes to work. I wanted you to come quickly, I will change this code here and this chord a little so that it will be almost the same for us and Mushairas, here I have to put it here, then the dialects will be air, food, night fall here and if Write number three, write * If it happens then ours will Write number three, write * If it happens then ours will Write number three, write * If it happens then ours will become soft then back it up, okay if you don't get honest then pocket, all this has to be done and found of points, he is benefited from IIM and 3.22 A graduate from poverty, benefited from IIM and 3.22 A graduate from poverty, benefited from IIM and 3.22 A graduate from poverty, he requested and wanted and Indore people We need to stop the charges, if both of them are found then forgive them, otherwise don't do anything President, okay, this is our case, this is the complete situation of this treatment, this statement will end here and I think this is the back end here, there is a respect tree and these people look at you, this thread is cut, the work is getting finished, according to the police, it is good here so I am fine, they should have seen the reminder. What else will we do for Android 4.0 What else will we do for Android 4.0 What else will we do for Android 4.0 We were the last straw in these were the British soldiers Zero I - - Attacks will keep happening, we will soldiers Zero I - - Attacks will keep happening, we will soldiers Zero I - - Attacks will keep happening, we will cut off the dictionary app that today, if the digits of I want to be minus one, if it is not so, then we will get it done today in the answer, what will we do for this is how they are made to work in the train. Plus and after that we digit of high quality ok, I will search for the answer again, check once if the result is one and a half, set a reminder, if one of the crackers in MS Word is blood, then anti dumping is frustrated, 100 not fixed. If the permission is there to make a sexy one then it is the right answer then we submit it if it is there then it is dreams ok then it fulfills ours then this is in the records and you see it Tiger Group Loop 1333 I hope you have understood the solution. Okay, so this question was twisted, so we asked that how do you want to click on continue, how will you ignore, in this way, we will arrange to delete the content, add a little SIM and click on I had to do it, I had to give us that which people will delete it, then this is our whole blood, okay, this is the stupidity of the function, you should understand that this is a flu side of watching the calling, do it.
|
Largest Multiple of Three
|
largest-multiple-of-three
|
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
**Example 1:**
**Input:** digits = \[8,1,9\]
**Output:** "981 "
**Example 2:**
**Input:** digits = \[8,6,7,1,0\]
**Output:** "8760 "
**Example 3:**
**Input:** digits = \[1\]
**Output:** " "
**Constraints:**
* `1 <= digits.length <= 104`
* `0 <= digits[i] <= 9`
| null | null |
Hard
| null |
208 |
hi everyone welcome back to the series so in this video lecture we'll be implementing this dry data structure so before you watch this video make sure to watch the previous video because I have implemented the same data structure using pointers in this video lecture we'll be implementing this data structure using 2D arrays so let's see how we can do that so let's say we have a disk dictionary which contains these six words the range of the characters in these words is from small a to small Z that means we have at most 26 type of characters for every node to store let's build the corresponding try for this given bunch of words we start from this root node we have the very first character for the very first word we are trying to store that is try so we store T here from T we have another character which is R from R we have y so in this fashion we store this word try in this try data structure and we mark this character y to be is end so it's is and Boolean variable is marked to be true that is here we Mark the end of this word which starts from t and ends at y let's try to insert car so do we have a child for the root node which contains C no so we create a child which contains C then we create a child which contains a finally we create a child which contains r and here at R we Mark the ending of this word okay so we have stored car word in this trial let's store this word cat so let's we start from C then from c v move to a then from a so let's store this correct let's store this word cat so let's check if we have C A in this try so we have C here which is the very first child of the root then we also have a as a child of C now do we have a child t for node a we do not have t as a child of node a so we create a child for node a and we store T there now if you're trying to inverse we try to insert this word t r i e into this try so let's start with the T so we have t as the child of root now from T we have r as the child do we have I as a child no so we create a I we create I as a child of node R now from I we create e as its child so now we have stored try here let's store cards do we have C as our child node for root yes we have C so we have a yes we have a as the child node for C do we have r as the child node for c for a yes we have r as the child node for node a so let's store d as the child node for character R let's store s as the child node for a character D and we Mark here as the ending character s is the ending character here T is the ending character here e is the ending character so the Boolean variables or the Boolean is and variable for these characters are marked to be true for other characters they are marked to be false let's store A and D do we have a as the child of root no so we create a child a and we make it as a child for root node now do we have n as a child of a no so we create another node and store n there do we have d as a child of n no so we create another node and we store D there and we mark this D to be the ending character for this word which starts at a and ends at D so in this fashion we have builded the try corresponding to these this dictionary of words let's see how we can implement this using 2D arrays so in the previous video we have implemented the tries using pointers in C plus so in this video we'll be implementing these tries using 2D arrays only let's see how we can do that so first of all how let's just count how many words how many nodes we require to store these words that depends on the number of characters we are storing or the longest path in this try which is this one okay because that will give me the maximum number of nodes which I require so in this path we have one two three four five nodes correspond to the length of this word cards so that means we require at most five nodes to store our try so n is equals to 5 while for every node we require an array of data an array of size 26 to store these 26 characters because the range of the characters in these words is from small a to small Z if the range would have been different then we would have taken a different array which may whose size may be different from this 26 since we just contain lowercase English letters we take an array of size 26. so let's implement it let's see the typical node structure so all we have to do we need to know these two things that is maximum number of nodes required and for every node how many characters we need to store or there are possibilities to store after that we just create an array a 2d array of dimensions and cross 26. okay so here n is 5 so let's create an array of Dimensions 5 cross 36 okay 5 cross 26 that would be like this 0 1 2 3 4 and forever so these numbers represents the nodes so this is node number zero this is node number one node number two node number three and node number four so if you have n nodes they will be numbered from 0 to n minus 1. now for every node we have 26 characters which we can store so that's why we take an array of size 26 for every node so in this fashion we have a kind of adjacency list or a 2d array we can say and we have 26 slots for every node starting from node number 0 till node number n minus 1. so here the very first slot is a corresponds to the character a this is this corresponds to the character b c t e and so on although the actual indices are 0 1 2 3 and so on like a corresponds to 0 B corresponds to 1 C corresponds to two fine so let's try to store the words in this type of try so we had the dictionary that we had the very first word was t r y okay so A B C D E F G H I J so we had somewhere T here now from that t so let's say we have like so for the slot so let's say we have t somewhere after couple of nodes we have t here and what do we do to store this node try we iterate we go to the very first node starts from node number zero so we start from node number 0 and for this node number 0 we want to store this t so we go to node number 0 and we come to this slot and here we simply put one so what I'm saying here okay so this is the very first character which I have encountered for this word I want to store this word t r y go to the node number one to look for this second character that's what I'm saying here okay so that's why I store one here and now I move to this node because this character T is directing us to this node that is node number one so I come to this node which is node number one and here I am searching for r so corresponding to R we have some slot like over here corresponding to node r so here we store 2. that is what I am saying is okay we have found T we have found r now we have inserted T we have inserted R now to insert y so that so remember I'm explaining insert operation here how we gonna build the try so to insert y go to the node number two so we move to this node that is node number two and here corresponding to slot y what I'm going to put is so this is y so corresponding to node y I'm gonna store three that is if you want to look for the next character then go to the node number three but here we do not have to go to this node because here we are simply marking this character y as the ending character for this word how do we do that to do so we use an extra array let's call it is and array so we also take another array this is and array and in this array we this array has a size of n it is a size of n so 0 1 2 3 4 and so on now since this node which is node number 2 here is the ending node what I'm going to do is I'm going to mark this node as the ending node okay so since this character here at this character which is corrective y corresponding to this character y we have like node number three that means for node number three we stored one or we store t P stands for true that is this node number three is the ending node for this word fine so in this fashion I basically store a word in a try using 2D arrays let's store the next word which is car c a r i want to store this word so let's start from the very first node to do so we'll start from the very first node let's say node number 0. so since I want to store car so I want to store car for this node for this character C I will start from node number 0. so which is this one so for this node move to the slot which contains this character C that is which like corresponds to this character C here and store one here so what I'm saying okay I have inserted character C at node number 0 now to insert the next character which is a move to this node which is node number one so I move to this node and at this node I store a so I put 2 here so what I am saying I have inserted a at node number one to insert the next character which is R move to node number two so I move to node number 2 here so at node number two we want to store this R so corresponding to this R we have slot here and here I put 3 that is I have inserted R in this slot corresponds to node number two to store the next character move to node number three but here but I notice that R is the last character of this word I am done with the character so I have inserted all of the characters of the word into the try that means for node number three I'm gonna Mark true which is already marked through here so in this fashion I'm gonna insert the words into the try so let's see how we can search for a word in the try so let's say I want to search for again that's why I want to search for t r y so to do so I will again start from node 0 so I initialize this node variable to zero so I start from this node which is node number 0 and at this node I move to the slot corresponding to the character number T here it contains one that is okay I have found T move to the Node 1 to look for the next character which is R so I move to the node number one and at node number one I want to look for R so move to the slot corresponding to character R which is this one so what I'm saying okay I have found R here to check for the next character move to the node number two so I am here at node number two and at node number two I come to the slot corresponding to this character Y which contains three that is I have found v y to search for the next character of the word move to the node number three but what I see I am done with my word which I want to insert I want to check whether Y is the last character or if it was inserted then that means why must we marked true the node corresponding to Y must be marked true so I check here in this array I can see that the node which is 3 corresponding to correct of Y is marked two that means try was inserted and hence it is present in the try so we return true in this case that's how I search for a word let's say I want to search for a prefix if there is a word which contains a prefix let's say c a okay to do so I will again start from node 0 so start from node 0 come to the very first character C and corresponding to this character C find the slot here in this node number 0 which is this one and it contains a non-zero value all other it contains a non-zero value all other it contains a non-zero value all other slots contains a zero value except C and T So this C contains one that means okay I have found C to check for the next character a move to node number one so I come to node number one and here I want to check for a now check for a which is this one okay I do not okay I didn't insert it okay I didn't inserted a here I think I this was a mistake so this okay so this is not d so this is D basically so this I inserted car c a r that means corresponding to character a we must have 2 here so this is wrong okay so I come to a and I see okay I have found a we have a non-zero value here that means I have non-zero value here that means I have non-zero value here that means I have found a move to the node number two to check for the next character but I am done with reversing my prefix which I wanted to search that means I have found both of the characters into the try and hence that simply means there is at least one word which has a which has CA as its prefix which starts with this CA and hence we return 2 in this case so that's how the starts with functionality Works in this implementation let's jump to the code implementation part so this is my try class in this try class I want to implement the code for the try using 2D arrays so let's first declare those arrays let's clear a 2d array the try array corresponding to The Matrix which are explained in the slide t r i e of Dimensions let's say two zero two and every node so this I am putting a upper bound here that means take any test case in this problem statement look at the constraints any test case will never cross like n the maximum number of nodes in any test case will never exceed this number now for every node I have 26 characters to store because notice that we have just lower case English letters and we have 26 lowercase English letters now we also need a Boolean array that is and array to Mark the ending of a word which we have inserted it has a size of size same as the number of nodes so again put an upper bound here and apart from it also declare a node current node to or let's say root node let's not call it current let's call it root so this is the node from where we have to start remember whenever we initialize a node with 0 that means we are starting from this root node okay so let's jump to this public part and here we can see that in this Constructor what we're going to do is we're gonna initialize we also have to keep track of another variable let's call it counter and the purpose of this counter is simply like here I just whenever I like I wanted to insert this D at this position and that's why I inserted one here that is okay T is present to check for the next character move to node number one so to store this one two I use this counter variable okay and here in this try but what I'm gonna do is I'm simply initializing these arrays so initialize root with 0 initialize a try like you can also do it like this do not initialize them here initialize these variables right here try initialize like counter initialize counter with zero and also initialize these try array with 0 and this is an array with false fine now here into this let's just jump to the let's just implement this insert function to do so let's declare a pointer let's call it node so this is the node from where we are starting so we since we start from the root node we initialize it with the root node now iterate over the word for every character check if it is a present or not so in the try if this character is present C minus a then this value try node C minus a is not zero so if it is 0 if it is null then that means or if it is 0 then that means we do not have this character at this node we do not have character C at this node and hence we store it try node C minus a to store it we just increment our counter with 1 and put it here why what I am saying okay at this node corresponding like at this node I am storing this character C and it is saying okay we have this character here to check for the next character of the word move to this position okay that's what I'm saying here now move our node to this position which we have stored here node C minus a fine and at the end when we are done with traversing the word Mark the ending character of the word to be true so is and for the last node mark it to be true so that's how we insert the word into the try let's see how we can search it again initialize the node with the root node iterate over the word check if the current word if the current character is there C minus a if it is 0 then that means this character is not there if it is the case then return Falls right from here otherwise move to the next node to which this current node is directing us to Tri a node C minus a fine at the end check if that means if I have traversed this Loop then that means I am standing at the last node and check if the last node is the ending node if it is marked as the ending node or not so return is end is and node so if it is marked true then we return true otherwise will return false let's see if we have a word in the drive which has the prefix same as this prefix which we have passed which has been passed in this function to do so again initialize this node with the root we start from the root node iterate over the prefix so C prefix check if we have this character in The try so if we do not have this character then just return right return false right from here otherwise move to the next node to which this node is directing us to and at the end return true because we have found a prefix which like there is at least one word which starts with this prefix fine so that's all we have to do that's how we Implement try using arrays only although it consumes a little bit more memory than the previous implementation but we do not use pointers here okay it's accepted let's submit it accepted so let's jump to the complexity part let's analyze the complexity here you can see that the time complexity stays the same as we are just iterating over the words in these functions so let's say if we have a word of size K which you want to search insert or check if it is a prefix then we require big of K time complexity while the space complexity is again n into 26 where n represents the number of nodes the maximum number of nodes which we have or n corresponds to what is n here n corresponds to Max characters so let's write it over here so here the complexity is that time the space complexity is n into 26. where n represents the maximum number of characters which a word may have which award has so we simply take the longest word and the length of that longest word represents this n and that's my space complexity although we also use arrays like is and array so and the overall space complexity would be n Plus 26 plus n that will give me big of n fine so that's all and I hope you got what we did in this video and this is just another implementation for the tries and I hope you enjoyed it and in the next in the upcoming videos we'll be solving problems over this data structure so stay tuned with me and I hope to see
|
Implement Trie (Prefix Tree)
|
implement-trie-prefix-tree
|
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
| null |
Hash Table,String,Design,Trie
|
Medium
|
211,642,648,676,1433,1949
|
146 |
what's up everyone sam here from byte by byte calm and in this video I'm going to show you exactly how to implement an LRU cache so that's the least recently used cache and this is a very common problem in a lot of coding interviews so we're gonna dig into it right after the intro and if you haven't already make sure you hit that subscribe button on the Bell icon so that you get notified every week when we release new videos alright in this video we're going to talk about how to implement an LRU cache and this is a pretty common problem so it's definitely a good one for you to understand how to solve this and also understand how to work through and it's a good demonstration of how to use the but optimization as well so with this problem basically the structure is a little bit different because we're implementing LRU cache like class and so really what we're doing is we're implementing these two functions so it changes our approach a little bit in the sense that we don't really have to be you know we don't have to be super conscientious about like defining the functions ahead of time and also actually on leap code at least it tells us what the run time that we're expecting for this problem is and so that makes us it a lot easier as well it's telling us that we want to ideally do both of these operations in oh of one time which means that we want to do them in constant time and so let's look at how we can approach this problem so with an LRU cache just to make sure that we're all on the same page here the basic idea is that we're gonna implement a cache it's gonna be you know a cache of some set size and then what we're gonna do is when the cache is full we're gonna evict the least recently accessed item in the cache and so you know we might have a cache that had values and you know I guess we do the one thing we do want to make sure that we're clear on here is what the types of the key and value are so you know this case get is gonna return an int and key and value are both going to be integers as well just to keep things simple and so maybe we put in our cache one two three four five six and then now we let's say that we wanted to add another item while our cache is full and if we put the one in first then that means that the one is going to get evicted so that we can put 7 in and then the two would get evicted to put 8 in etc and so how can we implement this well we sort of need to do two things right like first we need to keep track of what the order is of the elements and so we could do this in a couple different ways like we could say for example let's keep an actual you know set of when the like a timestamp of when they were most recently accessed or like there are a lot of things we can do like that but we'd want to make sure that we're not over complicating it and so you know this is a perfect example where I think it's easy with the brute force solution to start getting really complicated but let's back up and think you know simply how can we just keep track of what is the next item or what is the item that we need to evict and so a really easy way to do that is just to keep the items in order from most recently accessed to least recently accessed right or at least recently accessed to most recently accessed because it doesn't matter what the actual time that the element was accessed at it just matters the relative times that we access the different elements and so what that leads me to immediately thinking is what if we stored our elements in some sort of sorted data structure right like maybe we can store them in a heap maybe we could store them in a list maybe we could store them in even an array potentially but I think you know the easiest thing here because we're gonna potentially be what we want to realize is that we're potentially going to be updating this order over time and so it seems like the easiest option here is just going to be a linked list right because the linked list of the items will be in some fixed order and then if we want to when we access the item all we have to do is pick it out and move it to the front of the list and so let's look at like what this would look like so we would have you know a list like this and so we might have like one two three four and then let's say that we have you know get to then what would happen is we would remove this one and put it at the beginning so we'd have two and then one and then three and then four and every time we get an item all we have to do is we have to find it in the list and update it or if we you know if we try and put another item it's gonna go at the front so you know five would go here and then we would just evict the last element of the list right so we just remove the last the very last element and so functionally you know that's a really easy way for us to keep track of just like what is the order of like when they've been accessed but the problem with this obviously is that this is not going to take all of one time right it'll take all of end time for us so like let's look at these individually so first if we want to get something it's gonna take us potentially o of n time because we have to iterate over the whole thing to even find if it's in the catcher right and then to put it then that could take constant time depending on the size of the cache but if we need to evict this last element in the cache then that's also going to take all of em time because we need to iterate all the way through to the end to access that value and so the question is how can we do this more efficiently like can we do a with a linked list and also do it more efficiently and the answer is of course yes because we know that our we're going for this specific time complexity for both and so what is the issue here if we look at our bud optimization the issue is really that every time we're doing something we're iterating over the whole list and so we're doing this all of this work every time and the question is there a way that we can avoid having to iterate over this list so let's say that I had a linked list and I have the values in it and basically what I want to know is I want to be able to tell without having to iterate over the entire list if an element is in the list and if so where it is right and so let's say that I have you know get three and obviously I'm not including the values here I'm just putting the keys because you know the value would be stored in this list somewhere and we can just sort of ignore that and so if I did get three how could I do this well I could keep some sort of separate list or set or something that I could look up to three and it would tell me if it was in this array or right so I could keep just a set that would be like you know here the here are the values and then I would go to get I would see Oh threes in here okay that's fine but now I still need to iterate through here to actually find it in the list because there's no way for me to access things out of order in our list and so a better way that we could do this would be what if not only did we say if that it was in the list but we also kept a direct reference to it right so what if instead of doing a set we actually kept a mound and so we could keep a map which is basically like a set if can function like a set except that it also has values and so we have you know one two three four but now we're actually going to have these the key is still the number and then the value is a pointer to the note and so now when we want to get three we can go in here and we can find oh there's three and it points me right to where I need to go and so I don't need to traverse the whole list I'm right here and so the and so now all I need to do is extract the three and bring it to the beginning of the list which if you're looking at this carefully you might be like well Sam how am I going to do that because I don't actually I can't really extract this three if I only have a pointer to the three because I need a reference to this previous one so I can update the pointer to point to the floor and so the easy way to deal with this would be that rather than doing a singly linked list we could just do a doubly linked list and the advantage of the doubly linked list as well is that when we do a pullet we're gonna have key let's say that we put you know five and some value V then when we do the put we're gonna add our new onto the beginning so we'll have five and then this would be added to our set with a pointer and then it's really easy for us if we need to evict the last one with the doubly linked list we'll generally have a reference to the beginning in the end and so that just makes it really simple by keeping this map as long as we keep the map lined up with our list itself and we keep that doubly linked list now we can when we put it takes us constant time to insert this note at the beginning and insert it into our map and it takes this constant time to remove the last element if we need to right so all of a sudden now by just keeping this secondary data structure this map we are now able to do this problem in constant time and make the get and the put both being constant time and so that's how we approach this is a good one to sort of know off hand just because it does come up fairly frequently and hopefully you're seeing as well how you know this is a slightly different than some of the other problems we've done but it's the same basic idea of I'm saying like you know here's where the inefficiency is how can I do something to address that inefficiency and make it more efficient and that's how I want you to think about these problems and that's all I got for this one so I look forward to seeing you in the next video thanks so much for sticking with me through this video if you enjoyed this and are looking for more you can check out our free 50 interview questions guide where we go through 50 of the most common coding interview questions and if you like this video make sure you hit that subscribe button and the like button let us know what you thought and check out some of our other videos we have a ton of other content like this and I look forward to seeing you in the next
|
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
|
203 |
hi guys welcome to algorithms made easy today we will go through the day 20 problem from the july lead coding challenge remove linked list elements please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update we need to remove all the elements from a linked list of integers that have a given value for example given we need to remove all the elements with value 6. this question is about learning the basic delete operation in a linked list if an element to be removed is in the middle it is generally easy we would need to remove the link between the node and its previous node and point the next of previous to the next of node that is to be deleted but what if the node to be deleted is the head node in this case we do not have a previous pointer in such cases we can create a dummy head node that will act as a previous pointer this dummy node or a pseudo head is also called as a sentinel now we can eliminate the link between the dummy node and node 3 and update the next of sentinel to point to a correct node here node 4 we then return the next of sentinel node as the head node while returning the result let's take this linked list as an example and try to delete the node with value 3. first and foremost we will need a sentinel node we can give it any value here let's give it a value as 0 we will also point its next to the head of the input linked list our updated link list will look like this now we will take 2 pointers one to track the previous node and the other to track the current node initially the previous will be at the sentinel node and the current will be at the actual head of the list we will now iterate over the list till the node at the current pointer is not null and while iterating we will see if the node is the one to be deleted as here it is we will delete the current node by updating the pointers we will update the next of its predecessor to point to the next of the current node we will also move the current to the next node we will again do the same as the current node value is equal to the value that needs to be deleted so we update the pointer of previous node and move our current pointer as this is also the node that needs to be deleted once more we do the same here we see a node that we want to keep so we move our previous and current pointers one step ahead and again check if the node needs to be deleted or not as it does not we again move both the pointers one step ahead now that the current node becomes null the loop breaks and we have this linked list remaining with us as we need to get rid of the dummy node or the sentinel node we return the next of sentinel as the head of our output link list so this becomes our final output let's revisit what we did we initialized sentinel node as list node 0 and set it to be the new head then we initialize two pointers current and previous to track the current node and its predecessor we then looped while current is not equal to null and compared the value of current node with the value to be deleted if the values were equal we deleted the current node otherwise we set the previous to be equal to the current node then we move to the next node at the end we return the next stop sentinel this becomes our algorithm the time complexity here is o of n as it is one pass algorithm the space complexity is o of one here's the actual code snippet from the method you can also find the link to this code in the description below thanks for watching the video if you like the video please like share and subscribe to the channel let me know in the comments what you think about the video
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
1,044 |
hello everyone welcome to codas camp we are at 30th day of october challenge and the problem we are going to cover in this video is longest duplicate substring so the input given here is a string variable yes and we have to return the longest duplicate substring in the given input so let's understand this with an example so first what are the substrings given in the input string there are only three characters so the substring can be in our ba so in this case these three are the longest compared to the other two sets so let's start with searching a and a so do we have two a and a s in the given string so there is one a and another a and b so this is going to be the longest duplicate substring in the given input and that we are going to return that as our output so how we are going to approach this programmatically if you remember we have solved longest common substring longest common subsequence and many similar problems with this pattern so the first idea that stuck my mind or your mind would be a dynamic programming solution that we have used for longest common substring so the difference between longest common substring and longest duplicate substring is nothing but in longest common substring there will be string one and string two for example consider string one as banana and string two as hana then we have to find a common substring between these two strings so a and a will be the common string but here in this case instead of using two strings we have only one string and we have to find both the substrings in the same string so the only difference programmatically we face would be both substring should not start from the same position which is nothing but in if suppose a b c d is one sub string and a b c d is under the substring which is nothing but the same word again or the same sub string again so a substring cannot start in the same position it can overwrite but it cannot start in the same position for example in banana itself if you start recognizing the substrings a and a is one substring and a is another substring so here they both overlap but they both do not start in the same position so let's go to solve this problem by using two dimensional dp so very similar to longest common subsequence or longest common substring we do have a two dimensional dp array to compare and fill the common duplicate substring between these two strings and fill the length here so finally we would come to the point wherever there is a maximum number so the three is the longest duplicate substring in the given input string which is nothing but a and a so it is simpler to solve this way and i as i said uh the substring should not start in the same position like it should not start from here and here in the two strings so to avoid that we are going to fill zeros in the middle diagonal cells because that will rectify that problem so by using this technique you can come up with a solution but the space this problem here if suppose the length of the string is 10 power 15 then you need 10 power 15 into 10 power 15 space into the uh bytes number of bytes for uh storing the integer variables so this is definitely not going to be the optimal solution so how are we going to make it better so another idea that stuck our mind to always solve a string problem is try so we are going to construct a try and with the help of binary search we are going to solve this problem so let's start constructing our try based on our binary search so here the length of our string is 6 starting from the index 0 to index 5. so in this case any sub string that cannot be start from the same position so it must be at least start from the second position if at all the substring length considering the length is maximum one so in that case our uh length of our substring would be somewhere from 0 to 4 which is nothing but 1 to 5 so in this case we are going to find a middle value thinking that our substring is somewhere in the average length and try searching for those lengths of strings in the word again using the try for example now the left index is 0 and right index is 5 now the mid value is going to be 3 so we are going to construct the given word into sub strings of length three so let's start by constructing from the root node first b is there and then uh from b it is a and then from a it is n ban is our first word so starting from the zeroth index what if the word starts from the next index we do a sliding window from our index one we are again going to start constructing our second word of length three which is a and then n and then a so again from third index we again gonna do a sliding window which is nothing but n a n so now from the fourth word we are going to start next three letters which is a and a so if you search for a whether a exists or not yes a is exist then we are going to check the next character which is n then we are going to check the next character which is a so this is already present which means we found one duplicate of length three so we keep hold of that so which means we found some substring of length three so there are possibility that this can be the long longest or we can even find any substring of more length so what are we going to do we are going to shift our left to three and fix our lower bound to three and upper bound to 5 and again find a mid value which is 4 so now we are going to again construct a try starting from the very first character with sub strings of size 4 and check whether length 4 substrings are having duplicates or not and it goes until we our left and right bound meets and finally what is the count we found of the duplicate string will be our output so this is again a problematic solution because binary search works an efficient way which takes login time but to construct try every time to each and every length it is gonna take k into login time and again searching it would take another end time so that is again gonna take more time to construct try for every possible length because the maximum length of a given string can be 10 power 50 so in this case we have to go for even more better solution so the best solution for this problem would be rolling hash or rabin car algorithm so before getting into how this algorithm can help to solve this problem let's go for a quick overview of what is rolling hash problem so rolling hash problem is generally devised to find any pattern matching in a given input string for example you want to find this pattern a b in a given input string then you have to pick each character and compare there is a and then the last character differs so again it is going to start from the second character a c the third character defense and again starting from the third character and it is going to take infinite time so this is going to be a tedious process so how are we going to optimize this by using hash values so we are going to construct hash value of sub strings that match this length for example let us consider a is equal to 1 b is equal to 2 and z is equal to 26. so we are going to assign each character a value so in this case aaac is going to represent it as 1 plus 3 and a b is going to represented as 1 plus 2 so it is gonna first check the length of this pattern and the length is going to be four so it is going to take substrings of length four from the string one so the length four is a ac it is gonna map and check whether hash of aac is equal to hash of aab no they are not equal so in this case this can't be the same pattern or string so it is moving ahead to the next one starting from the second day and it checks a c is hash and then a c a is hash and then so on it keeps checking its length and then finally it checks a b yes it matches the hash once it matches the hash it is going to check character by character whether a and b matches or not so why because in some cases if suppose the string is 80 and another string or the pattern here is bc they both share the same hash so they both gonna share five as their hash value so in this case they if they are not equal again some anagrams also share the same uh hash for example if uh aca is one word and ca is another word they both gonna share the same hash value so in this case we cannot simply go for uh this method instead we need some powerful uh hash method to identify the characters so here we are going to introduce uh the exponential format to represent position of each character so how are we going to do that so to indicate the position of each character we are going to identify its position based on uh tens hundreds and thousand values for example how do we represent a binary to decimal value so if there is a 1 0 1 then we'd be multiplying 10 power 0 because it is in the zeroth position and then 10 power 1 and then 10 power 2 and then 10 power 3 and it goes on same way you can represent these characters by for example if a is equal to 1 b is equal to 2 c is equal to 3 then a ac is going to be represented as 1 into 10 power 3 plus 1 into 10 power 2 1 into 10 power 1 and 1 into 10 sorry 3 into 10 power 0 why 3 because c's corresponding value in alphabet is 3 if this is complicated in the given example a and a is our substring in banana so this is going to be like 10 1 into 10 power 3 n is 14th character so 14 into 10 power 2 and a is again 1 into 10 power sorry this is 2 1 and 0 so this is how we are going to represent the characters so this also not necessarily have to be 10 it can be 26 or 31 or any value as you like because since we have 26 characters we can represent them in the format of 26 power 2 26 power 3 sorry 1 and 26 power 0 or since you don't want any even numbers you can go for odd number which is the nearest prime number to 26 again you can represent it as 31 power 2 and so on so again there comes a problem if we try to represent them in this format then it is going to cross the integer limit or long limit in our coding so in order to shorten the values we are going to do modulo of some prime number to reduce the value so let that be 31 or 113 or however you want to be for example if we do a modulo with 113 then all our values will be shorten up within 100 or within 113 so in that case it is easy for us to compare the hash value of two strings so this is the overall concept of rolling hash so they will compute hash value of each string of certain length and compare the hash value whether that matches any other hash value in the given input string and if it not matches it is going to check for the next string not matches still it is going to find whenever it matches when it matches it is going to check character by character so we are going to get the help of this technique plus a binary search to get an optimal solution so let's see how exactly we are going to implement it so as i said we are first going to use a binary search technique now left is equal to 0 and right is equal to 5 so the mid value is equal to 3 so we are going to take hash value of sub strings of length 3 from banana now the first string is going to be ban so this is going to call the hash function to calculate its hash so this is going to be 14 into let me use 31 the prime number to calculate the hash value 31 power 0 and 1 into 31 power 1 and 2 into 31.2 31.2 31.2 so this would come around 1967. so now we store this in a set so now our set is going to have 1967 and then calculate the next set of hash which is for a and a so instead of again doing the same process repeatedly we have a shortcut to find the hash value of the subsets easily because as we know the length is going to be constant that is 3 so 31 power 0 31 for 1 and 31 for 2 is going to be the same for all the characters just that the front values change so here what are we going to do is we are going to remove b and add an a to the substring so this a n is going to be same as well so what are we going to do we are going to subtract the value of the leftmost character and then add a value of the next character which is nothing but 1 why we add only one because anyway it is going to be the uh right most character and the right most character would always have 31 power 0 so 31 for 0 is anything power 0 is always 1 so it is not going to be a matter so whatever character we gonna add at the last will be its value will be added to the previous value and the value of the very first leftmost character will be deleted from the previously calculated hash value so the hash value of a and a would be some 1395 and any n would be more than some 2000 so there comes again a and a so when we calculate the hash for a and a that will be again 1395. so when we try to store that in a set which is already exist which means we found a duplicate substring of length three so what are we going to do we are going to save in a result so far the duplicate substring we found its length is three so now we get back to our binary search so we know there we found a duplicate value of length three so it can be three or more than three so in that case our left bound will be switched to three and right bound would be switched to five again and new mid value will be calculated and again all the hash for new mid will be again calculated by using the space to order in a set and if it found a match then it is going to alter the result if not what is there and the result will be returned so yes this is the overall concept of how we are going to implement longest duplicate substring using rolling hash and binary search and this is going to work in big o of login yen login time complexity so this login is for binary search and another login is for the sliding window for each and every uh sliding window for each uh m the mid value we found and n is for uh n is nothing but n times we do uh the number of times we calculate the mid value so yes uh hope i made sense so let's go to the code now so here's the code for this problem and uh before getting into the main method let's see the hash and next hash method so this is nothing but a method used for us to calculate the hash value of any substring we pass on to it so as i said we are going to uh have a 31 as a number so for each character we take the characters value and multiply it with uh the previous value and multiply it with 31 so the number of times the position is we multiply 31 that many times just to compensate the power so the next hash method is to once we find the first sub strings for example if 3 is the length of mid then if we find the first substrings hash then rest of the substrings hash will be easy we are going to negotiate the left side value and add the right characters value same way once we find our new mid is equal to 4 the first hash will find the first substrings value and then the rest of the strings will be formed by next hash so this is it from for this method and here comes our rabbin card so what are we going to do here is as i said we are going to declare a set and in that set we are first going to calculate the hash value for the first substring of length we found here length is nothing but the mid value we pass so once we find that we are going to add that to our hash so after that we are going to iterate for the list rest of the string and for each substring of length we pass we are going to calculate the next hash value by using the next hash method so every time we find uh the hash value using next hash we are going to update that in our set we are first going to check whether our set is containing that or not if it is there then we are going to uh save that substring from that length to uh the other length because the current substring will be saved uh or return to the main method if not we are going to add that value to our set and continue our search coming back to our main method as i said we are going to set the values of left and right to one and length of the string uh here and a result variable is to hold our result which is the longest duplicate substring in the given input string and we calculate the mid value and call our ravencard method with the string and the mid value so as i said the mid value is going to be the length of the substring for which we are going to find our hash values so if the returned length is not is equal to 0 which means we found some duplicate substring of the calculated length which means we have found a duplicate substring of calculated length so obviously the result is going to be either that length or can be more than that so we are going to set our left is equal to mid plus 1 if not if it is written 0 we did not find any duplicate string of that length so it could be less than what we sent so we've fixed the right value to mid minus one so once all the loop is done the result variable will have the result of our problem so yes this is it let's run and try yes solution is accepted let's submit yes our solution is submitted and this is 1989 person faster than the others our solution so thanks for watching the video do try out on your own and also observe what is the other solutions after submitting your solution so hope you like this video if you like this video hit like subscribe let me know in comments thank you
|
Longest Duplicate Substring
|
find-common-characters
|
Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`.
**Example 1:**
**Input:** s = "banana"
**Output:** "ana"
**Example 2:**
**Input:** s = "abcd"
**Output:** ""
**Constraints:**
* `2 <= s.length <= 3 * 104`
* `s` consists of lowercase English letters.
| null |
Array,Hash Table,String
|
Easy
|
350
|
56 |
welcome back to algojs today's question is leak code 56 merge intervals so given an array of intervals where interval i equals start end merge all overlapping intervals and return an array of the non-overlapping intervals that cover all non-overlapping intervals that cover all non-overlapping intervals that cover all the intervals in the input so with example one we have one three two six eight ten fifteen and eighteen and our output is one six eight ten fifteen and eighteen so we've merged one three and two six and the reason for this is because there is an overlap between the two arrays so 3 here is greater than 2 which is in the next array so we have to merge and take the smallest from the first and the largest from the second and then in example two we have one four and four five and the output is one five so if the value in the first array if its second value is equal to the first value in the second array essentially there is an overlap so the best way to understand this problem and to formulate a solution is to definitely draw this out so you can get a visual representation of the intervals and what's going on so let's draw this out so we have one through three as one interval we have two to six as another interval we have eight to ten and finally ten to twelve so these are our intervals right we have as you can see an overlap between this point and also this point and this point because remember if the two values are equal then that is classed as an overlap so those are the two areas that we'll be needing to do some conditional logic in order to create a merge between the two different intervals so we're going to need a result array which we're going to populate and pass in the answers and we are initially going to set the result rate with the initial array and as you can see the initial array that we're going to be looping through is already sorted but in the case of this question there may be an issue where they're not sorted in which case our first step would be to sort this array to make sure that it's in order so that we can see where the intervals are exactly so we've created this result array we've passed in 1 3 so the first array within it and this is going to be called previous okay so we're going to call this previous now because we've already checked it we have a start and an end within that interval and we have a start and an end within the next interval so we're going to call this second interval current so as we said we have an overlap here and the reason for this overlap is that this value right here is less than this value here so we can say if current actually what i'll do is i'll call this prev i'll call this current so if current at start so if this value right here is less than previous at end and remember in this case right here we have an overlap and those values are equal so we have to say is less than or equal to previous at end then what we need to do is we need to update this interval in order to accommodate this interval and the way we'll do that is we'll reassign previous n to equal the max between previous end and current end so the previous end will now be six so this will be our new previous value previous down here which is in the results will update if i go to 1 6 and i say it's the maximum between previous and current value just in case so say for example the previous initially was this it was one through seven in this case we have an overlap but the previous end value so this is previous at a minute the previous end value is already greater than current end so we take the maximum between the two so now we move on we update current to be here and we check this interval right here is there an overlap between current and previous no there's not there is no overlap so in this case all we need to do is add current into results current is 8 10 but here's the catch we need to update previous to the current value so that the next time we check current and previous it's going to be regarding the next two so previous moves here and current moves here now we check for an overlap this is considered an overlap so we take the maximum we update the previous end so this is going to be 10 we update that to the maximum between the previous end and the current end which is going to be this value right here so it's going to be 12. so this is what the previous now looks like and this will update to 12 and then we move along current goes out of bound and we return res so with regards to the complexity analysis time is going to be of n where n is the length of the input and space is going to be one constant space because even though we are populating this result array at the bottom here this is added to our output so it's not classed as occupying space within this solution so we're going to start this off by creating constants called start which is going to be equal to zero and end which is going to be equal to one so this is just starting off by creating the indexes for zero and one within the interval arrays then we need to order the intervals so we need to sort them in ascending order so intervals dot sort taking a and b and remember we are sorting an array of an arrays so we need to say a at start minus b at start then we need to create previous variable which is going to be equal to intervals at zero so it's going to be equal to the first array within the intervals array then we need to create the result array which is going to be equal to an array containing previous then we need to loop through the intervals so that current of intervals and we need to compare current at start with previous end like we did in our solution walkthrough so if current at start is less than or equal to previous at end we need to update previous end so previous to end is going to be equal to the maximum so math.max between previous end so math.max between previous end so math.max between previous end and current end else if there is no overlap we can just push current into result and then we need to update previous to be current because in the next iteration current is going to move one forward so we need to update previous to match that and then we can just return res okay let's give that run let's submit it and there you go
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
80 |
hey guys today we're going to solve lead code number 80. remove duplicates from sorted array 2. so we're given a sorted array numbers and we need to remove the duplicates in place so that duplicates appear at most twice so there can't be in the return array there can't be any number that appears more than two times and the hard part about this is that we can't allocate an extra space so what people usually think about when they see this problem is like swapping the array values around so that they go to the end or things like that but there's actually a really short solution that doesn't involve swapping and it's kind of like a true pointer solution so what we're going to do is we're going to start from the beginning of the array and essentially until we find a duplicate that appears three times we're going to move forward our pointer we're going to keep it kind of like a pointer so okay we can move forward with our pointer we can still move forward and with this one we don't want to include this into the result so we're going to keep a pointer pointing to this number but we're still going to move forward with the rest of the numbers so this one is different from the one before so we can essentially copy this value into the stored pointer reference that we were maintaining before so this one is going to be overwritten with a two then we're going to move forward with both our pointer and our traversal of the array and now these two will go here and then this three will go here and the final length is going to be one two three four and five so the pointer that we use to keep track of the position at which we're going to have to insert the next non-duplicate element can actually be non-duplicate element can actually be non-duplicate element can actually be used as the returning length as well because we need to return the length of the array after doing these modifications so the first thing that we are going to do is store the pointer in a variable we're going to call that final length because i will as i was telling you it can be used both as the position of the next number and the final length returned then we're going to later on return this value then as i was telling you we're going to have to traverse the whole nums array and at each step if the current final length is less than two meaning that we couldn't have any elements appearing three times because length is less than two so that's literally impossible or if the current number is different from the number at two positions before then we can add this number to our result and we do that by just overwriting whatever was at the previous final length index and incrementing finite index uh final length by one and so that's it already it's very elegant solution and people usually write a much longer code but this works just as well and it's a o of n time complexity and o of one space complexity so that's it for now and bye
|
Remove Duplicates from Sorted Array II
|
remove-duplicates-from-sorted-array-ii
|
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`.
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\]
**Output:** 5, nums = \[1,1,2,2,3,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,1,2,3,3\]
**Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\]
**Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
| null |
Array,Two Pointers
|
Medium
|
26
|
1,346 |
foreign and its double exist so like how an actor has its double you have to check whether the number has a double of it okay so we are given an array of integers and we have to check if there exists two distinct integers ing that means I is not equal to J and the indices are between 0 and array dot length so it doesn't matter okay and the given array has its double so array of I is equal to 2 times R of J okay so essentially the gist of a test we are given an array for each number we have to check whether double of that number exists so why does this condition of I not equal to J this because when is a number and twice of its number same only when the number is zero so if the number is 0 when we multiply 2 times 0 we'll get 0 but we need two zeros to conclude that the number and its double exist with just one zero we can't say the number and its double also exist because we just have one zero not two zeros right so that is one this I not equal to the condition comes into play so that is a very important or intricate detail that we have to notice when solving this question okay let's as usual move on to an example and try to understand the logic behind it and develop an algorithm later we'll move the lead code and solve this question so with this array given to us we'll create a hash map and store all these values and their respect to indices as key value pair so the number itself will be the key and the index of that number will be the value so 10 0 2 1 5 2 and 3. so these are the hash map and their respective foreign using this hash map we are gonna Traverse this array again and check whether the double of that number exists so let's start with the first number 10 so whether 2 times I that is in this case 2 times 10 20 exists in the hash map does 20 exist no that is not 20 so we'll move on to the next number 2 into 2 is 4 so that's 4 like this in the asthma no we do not have a 4. now let's model the next number 5 so 5 into 2 is 10 that's 10 exists in the asthma yeah we do have a 10 and its index is 0. so what do we say that a double like this and hence it exists thumbs up okay so with this R function comes to an a because we have found a double and we have written true so that is what we need to check whether the double of any number exists here with exists hence we return true if after traversing all these numbers we say that is no double in that case will return false so we'll move on to the algorithm shape so first what do we do the procedure was to First create a hash map so the first procedure was to create a hash map containing all these elements that are present in the array along with their indices right so that was the first step the Second Step was to through Loop through or Traverse through this list again okay so after traversing to this list for each and every number what do we check whether 2 times that number exist in the hash map if it exists also check whether the indices are not the same because as we saw in 0 the number and 2 times the number is same so we have to check whether the index of both of these numbers are different so I and 2i should have different indices okay and return to in outside the loop after checking all these conditions for all these paths if we did not find a pair and it's double then it means there is no pair which contains a number and it's double hence will return false so this becomes the core logic of this question now let's move to leaker and solve this question so here we have the function check if we exist so this condition takes the array as input as we saw and returns a Boolean whether the number and its double exists so similarly we are going to check with it you have subscribed to God I would if you're not please subscribe so moving on here we have the function now let's get started by creating a hash mark that becomes our first step so hash it's gonna store integer in both its key and its value so hence integer command period the name of it let's have it just now is equal to new hash map of okay now what do we do next we Traverse this array and store all these elements along with their index inside the hash mark So for end I is equal to 0 I less than a r dot length I press now what do we store all these values into the hash mark So map dot put off key comma value so key here is the array of I the element itself the value here is the index is represented by I and hence array of I comma I now after this we again Traverse this Loop so I copy this follow-up again here Loop so I copy this follow-up again here Loop so I copy this follow-up again here we are again traversing this array again and this time we are going to check whether 2 times the given number exists so if the number two times array of I does this exist how do we check whether does this exist for that we have a function called contains key off okay so this function map Dot contains K of this function is gonna check whether the given number here is present in the hash map or not so it's going to written as true or false so if it is true we also have to take one another condition which is whether the index of this number array of I and the index of 2 times array of I are different because as we saw in the case of 0 we have to check that in order to eliminate the possibility of taking the same number for I and also for 2i okay so I must not be equal to map dot get of 2 times array of I okay so map.getoff gets us the value of okay so map.getoff gets us the value of okay so map.getoff gets us the value of the respective key value pair and that stores the indexes as we saw here so I should not be equal to map dot get of 2 times array of I so 2 times array of I is the other number or it's double so the index of double that is map.get of I the index of double that is map.get of I the index of double that is map.get of I should not be equal to I so that is our second condition this is being checked only for the case or the h k is of 0 okay for the other cases this condition would give us the right answer for the h k is of 0 this condition is there okay now if it is true what do we just return true because we have found a pair which has the number and its double but what if we run this follow-up again and what if we run this follow-up again and what if we run this follow-up again and again but we didn't find a pair will come out of this follow in that case we return false saying that the number and its double does not exist in the same array that is given to us as input so this is gonna be our code now let's run this code and verify for all any syntax errors so this runs for the sample test case which is two test case and we have passed that right submit the code and verify it for all the other risk cases yeah congratulations you have successfully solved the question of check fvn and its double exist so if you love this video please drop a like and comment below if you have any queries and don't forget to click the Subscribe button we'll see you in the next episode of lead code till then bye foreign
|
Check If N and Its Double Exist
|
maximize-the-topmost-element-after-k-moves
|
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that :
* `i != j`
* `0 <= i, j < arr.length`
* `arr[i] == 2 * arr[j]`
**Example 1:**
**Input:** arr = \[10,2,5,3\]
**Output:** true
**Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\]
**Example 2:**
**Input:** arr = \[3,1,7,11\]
**Output:** false
**Explanation:** There is no i and j that satisfy the conditions.
**Constraints:**
* `2 <= arr.length <= 500`
* `-103 <= arr[i] <= 103`
|
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
|
Array,Greedy
|
Medium
|
134
|
403 |
hello and welcome to another video in this video we're going to be doing frog jump and so in this problem it's pretty straightforward a frog is crossing a river and it's divided into some number of units and essentially you have the stones array where at all of these indices a stone exists and the Frog starts at zero it needs to get to the very end and its first jump has to be one and then subsequent jumped have to be either K or k minus one or K plus 1 units and also these stones are in ascending order for example in this first one if you start at zero you can even make it bigger if we want okay so if we start at zero we can jump one stone here and then we can jump two stones and then we can jump Three Stones we'd want to jump one two three four five and then we get to the end so our jumps have to be increasing or decreasing or the same but they can only be increasing or decreasing by one unit so if we try that here we can't really get past this little Gap here because if you see like we can jump one we have to jump one unit here and then no matter what we do we can never do anything right so we can jump two units and then one and then this is four so in order for this to succeed the jumped to this Stone has to be three units and you can't really do that right from one you can't get to four or three because you can only jump two or one in either way it doesn't make so we need to basically rearrange this to make this a little bit more useful because like let's say we're at this Stone and we just jump like 10 units or something and we're like all right we're at Stone 11. well where is Stone 11 in the array even like do we want to just like manually go through the array that doesn't seem like a great idea we want to just be able to say is the stone in our stuff or is it not right so the easiest way to do that is just convert these stones into a set so we're going to convert this into a set and we are going to store the first and last value just to know like where do we start and when do we end so our first here is going to be zero and our last is going to be 17. it's a pretty straightforward it's actually like I'm surprised it's a hard problem um you only have a few things that you could do at every step right you can only jump one or you can only jump K or k minus one or K plus one units so what does that sound like to you well it sounds like a dynamic programming solution with not too many choices you can only jump like I said you only have three choices and so for a dynamic programming solution what would we like what would we have to do so for dynamic program we have three things right so we have state then we have a base case and then we have a recursive case and what would we use for these right like ours like what would you use for the state let's just think about that first of all what do we need well we probably want to know what stone we're on right like that one's pretty straightforward we have to know like number of stone but what else do we need anything else like how do we make our decisions well if we jump K or k minus one or K plus one what is K right like we have to know how far we can jump and so we have to store this like K or jump variable so we'll just call that k okay and then from there we just know we can jump either K minus one or k or K plus one and so what's our base case also pretty straightforward there's a couple so a let's say we try to jump on a stone that doesn't exist so Stone not in Stones set what should we do there well that basically means we landed in the water so we'd want to return false okay well what else do we have so we can also make it to our final Stone right so stone equals final Stone like our Stone we need to get to what should we return there we should return true and then what else do we have so we have a cache but remember I think I've done a lot of these problems where you're just trying to return one solution that succeeds and so anytime you're trying to return one solution that succeeds instead of doing a cache you can also have a visited set instead of a cache because everything in visited is always going to be false because if you ever get anything that is Success then you could just you can just immediately recruit a curse out and return true to the whole thing like we're not asked how many different ways can the Frog get to the end or something or what are all the arrays of the ways it's literally can it get there or can it not so our last thing is going to be is Stone in visited set and then if yes return false if not we just keep going because it's everything in the visited set will be false okay what about for a recursive case like what can we do well this one's pretty straightforward we jump K or k minus 1 or K plus 1 units right and we just update our state of DP accordingly like our Stone will be Stone plus K or stone plus K minus one or stone whatever and then our jump will also be like let's say our previous jump was five units and now we jump six units well we want to pass six into the next state because then we know we can jump six or six minus one or six plus one units so that's all the recursive case is we just try all the three jumps but there is a one more thing we're missing in this recursive case so hopefully you've been able to spot that so we don't want to jump zero units right like if we jump zero units we can just get in an infinite Loop where we're jumping zero units over and so what we need to do is we need to check for that where our jump we yeah we do want to jump K or k minus one K plus one we never want to jump zero units so we will check for that to make sure we don't have that happen and that's pretty much it um there is one other optimization you can make and I will show you that and I'll it'll be pretty obvious once I show you this example so let's say our stones are zero one two three four one hundred and I say is it possible to get to the end well it's pretty straightforward that you can't because at each jump you can only jump one more time right so here so how many jumps you have you jump here jump eardrum here get five jumps and what's the max and we could possibly jump so here you jump one two three four five well obviously this is not going to get you from zero to a hundred so because our numbers like because we know how far we can jump right like the most we can we the most we can get to is one plus two plus three plus four plus five so what would that be that would be 9 12 14 15. and so the biggest number we can possibly get to would be 15 right like because we do that one then we'd be at three then we'd be at six no did I do that right let me see so we have one two how many jumps do we have uh six numbers yes we have five jumps and let me just double check that one more time well yeah I think we should be able to let me just double check that so one then we'd be at three then we'd be at six then we'd be at ten then it would be at fifteen yeah so if this was 15 we could do it but these also have to be like obviously these have to be like bigger that would be doable but this is the biggest number we can get to given this length so is there a way to calculate quickly a sum of an arithmetic series that increases by one digit at a time so let's say this is like n digits and so there is a way to do that and it's literally the sum of a n minus one length sequence is n times n minus 1 over 2. and let's try that in this case so n here would actually be six so this is n minus 1 length so it would be six times five over two which would be 15. and so we can just check for that in the beginning we can just say like okay what's the maximum we can jump let's calculate that and if the maximum we can jump is less than this number then obviously we can't we don't need to like do the our whole DP we can just say false so that is a slight optimization because you can do that in Big O of one time right you can get the length and you can get the last number so that's pretty nice so we are going to include that in and that's kind of like maybe if it would still pass if you didn't have it but that's just like something you could add so we are going to include that but other than that it's pretty straightforward so let's start coding it up here so remember first we're going to check for that optimization where we're going to say if we can to get to the end because it's like if we just take the biggest jump at every single step and it's still too small we can just return false that's going to be if Stones negative one the last stone is greater than so remember it's you have to take the length of the stones it's the length of the stones uh times and so if they're if the stone is length Stones then our n jumps and that example would be actually n minus one so remember this is the formula to get the sum of N minus one stones and N minus 1 is the number of jumps so that would work in our case so if it's n minus 1 is the number of jumps then this would be n and then n minus 1 would be stones minus one and then we need to actually put that in parenze okay and we need to also divided by two and this should always be a positive number because it's essentially an odd times an even number which is always sorry it should always be an even number so this mod this floor divided by two is fine because it'll always be a full picture okay so we can just return false if that's the case and now what we're going to do is we're going to have our visited set so we're just going to visited set and then we're also we also need to want we want to record the first and last Stone so let's do that as well so we can say like first stone because just so we know where we're starting at equals Stones zero and Stones negative one and now we're literally going to transform stones into a set and if you think you don't want to be manipulating Stones you can make a new set so you can do that as well but I'm just going to do it in place so we're going to say Stones equals set stones but you could make another variable if you wanted to totally fine if you want if you don't want to manipulate your inputs okay so now we have our DP function and remember it's going to take a stone and a k right we said so I think I used jump before but we can use K so what's our base case well if stone equals last Stone then we want to return true and what's our false cases so if Stone not in Stones meaning it's water or stone k in visited meaning we already went there it's everything in visited is false we can return false and now we have the cases for the jumps right and so first we can handle the jump that's uh K minus one so we could say like if K is greater than one and remember we don't want to jump zero time so we're just going to say if K is greater than one do this otherwise let's skip this step because we don't want to jump one minus one times so where's our jump going to be well it's pretty straightforward it's going to be Stone plus K minus one that's where it's going to end up and then our new jump length is going to be K minus 1. okay so we can return through here and then we have two more cases so if DP Stone plus k you can probably clean it up a bit but it's not the case true and they all do have like slight little differences so okay and so for our last case we need to make sure that we basically need to make sure that our Stone isn't the like if you think about it this first stone has to be one length jump and this works for like this will be fine for this because K would be one so this would never go here so this would be this but now we have to make sure in our last case that the fir like the stone we're on isn't the first stone because the from the first Zone you can only jump one so you don't want to jump one plus anything you want to jump one minus anything this is already excluded because of this and so now we need to check for the plus case so we just need to say if Stone does not equal the first stone because from the first Thunder you're only allowed to jump K length and DP Stone Plus Jump Plus One then whatever you want to do we want to return true as well and then finally if we went through all these cases then we know we can't succeed from this state so we just add this state into our visited set so we want to add this should be K by the way not drum okay so we want to add it to visit it and then we just want to return false and then finally we want to call our DP function and what's our initial state so our initial state is first stone and then what's our jump length from the very beginning it's one right so it says the first jump has to be one unit so that's what we're going to put in and we are just going to return that and let's see if we have any errors or anything yeah so you can see it's uh pretty fishing so let's do the uh time and space complexity now for this so essentially if you go back for the time we are pretty much um well like let's see what's happening so this is of one and we are going through stones and you might think that like well every stone can be 2 to the 31 so shouldn't this be like 2 to the 31 well no because the biggest the stone can like if the stone is too big this will just fail right away so the biggest Stone can be is the biggest jump you can make so actually it's still like o of N and so that's why for the actual number for Stone it's actually the length of the Stone's array not the like biggest value of stone because let's say we had some array like I said that one tooth you know what it was like two to the 31 this would just break immediately because this would be false and if there was ever a 2 to the 31 in here because it's increasing the biggest number would have to be like really big and because the array is only 2 000 elements it would just break you know of one time because this would always be false so this check ensures that our time is of length of stones and our biggest Stone doesn't matter so this is going to be like stones length of stones and then the jump also if you think about it can go like one two three four five six seven so the possible the biggest jump is like roughly the length of stone so all the states for jump would be length of stones as well so it's Stones 10 stones for time and then for space if you think about it our visited set is gonna have the stone on this K and like I said for stone there it's still going to be the length of stones and K is also going to be the length of stones so they're both the length of stones times the length of stones which is like Stone squared time and space uh but yeah I think that's going to be it for this problem so hopefully you liked it like I said not too hard of a problem definitely one of the easier hard problems and they're I think in the last week or something there were like some very hard problems that I said but I think this one's pretty doable so if you didn't get it um just try like after watching this try to redo it shouldn't be too bad and uh if you liked the video please like the video and subscribe to the channel it really helps to grow it so I'll see in the next one thanks for watching
|
Frog Jump
|
frog-jump
|
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.
If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.
**Example 1:**
**Input:** stones = \[0,1,3,5,6,8,12,17\]
**Output:** true
**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
**Example 2:**
**Input:** stones = \[0,1,2,3,4,8,9,11\]
**Output:** false
**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
**Constraints:**
* `2 <= stones.length <= 2000`
* `0 <= stones[i] <= 231 - 1`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order.
| null |
Array,Dynamic Programming
|
Hard
|
1952,2262
|
476 |
hello welcome back to my channel and today we will be solving it good problem number 476 that is number complement so the problem statement given here is given a positive integer num we need to output its complement number and the complement is flipping it splits to the opposite and let's check with it let's check with an example so n here is okay i did not select that so n here is 5 let's take n as 5 and i'll show with 10 even or any number let's take it as 10. so n is equals to 5 what is the binary representation of 5 it is 1 zero one flipping its bits means just change the ones to zeros and zeros to ones so this should be zero this should be one and this should be zero so this binary number is equivalent to the number 2 let's take an example of 10 or we so the binary representation is 1 0 and by flipping its bit we will get 1 0 and this representation is 5 so this is simple problem we just need to convert this to a string and store the binary bits in opposite direction so if we have five as a number okay i'll just erase this part so it gets better okay this should be raised and that should do so if my binary number is five so what is my binary representation it was 1 0 and 1 so we'll just extract the last digit of it and we'll store that in opposite direction in a string called sum so this will store one so i extract the last widget and store it and i extract the second one and i store it and i extract the third one and i store it so my sum will be having one zero one and then we'll just convert this to an integer and print it that's it that was the whole intuition behind this problem let's see how we are doing it so we are just taking a sum empty variable which will be storing our reversed string or the reversed binary bits and then we'll be iterating over the nums or the num which is given to us and we'll extract the last bit and how do we extract the last bit it is num mod 2 will give me the last bit so if it is one zero one number two should give me one and we'll add this one to the sum to our answer that is this so one will be added here and remember that we added we need to reverse this string so instead of reversing we're just adding it in a reverse manner that is we are not simply doing sum plus one if it were to be sum plus one if we doing sum plus one sum is equals to sum plus one then this would have given us one zero one exactly so we cannot figure out the difference but if we take an example with another number let's take it as n is equals to i don't know why the laser keep stops working okay let me just erase this again so if we take n value as let me take something different so that should be and is equals to 6 n is equals to 6 and what is our value 1 one zero this is a binary representation of six if we now flip the bits what is it giving us one zero okay sorry zero and one this is our flipped bit representation and what is this number is one so we should be getting one now if we were to do it in a standard way that is sum plus one so we would have been just extracting this part and we would have been adding this so now we would be getting 0 this is our last bit so i'm getting 0 here and we are adding sum plus 0 so you would have been getting this now we are extracting this and now we extracting this so we would have got some different number so that is why we are just doing some equals to 1 plus sum so this would give me a reverse string as well as the complemented integer that we want so if the number is divisible by 0 we are adding 1 to it why because we want the complement that is why so this should do it and this part is this or part so we could simply write num is equals to this and this will do the same operation it's just that uh bit operations are faster so that is why i have done this and this part is important because sty is a c template that will return us these string to integer so my reverse string is 0 1 and this reverse strings integer value is 1 so this should give me one so how we are getting this we are getting doing it by stoi sum and 0 is the starting index of the sum so we from where we are wanting to convert it from the 0th index and what is the base is two so if you want uh the sty to perform from binary to integer so we need to write two if you want from 10 to some base then we can write 10 as well and if you want from hex then we can write 16 as well so now let's run this code and this code is getting accepted let's just use some damn test cases as well and this is getting submitted and this should get accepted as well okay this is getting accepted as well and that was it for this video thank you for watching
|
Number Complement
|
number-complement
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
| null |
Bit Manipulation
|
Easy
| null |
1,838 |
hi everyone today we are going to solve the little question frequency of the most frequent element the frequency of an element is a number of times it occurs in Array so you are given integer array norms and the integer K in one operation you can choose the index of nums and increase an element at the index by 1. return the maximum possible frequency of element after performing at most K operations so let's see the example so you are given 1 2 4 and k equals 5 output is 3 because increment the first element three times so that should be four and the rest of K should be 2. and the second element two times to make nums like four for four so out of two at second at index one so that should be four and the K is now zero and we successfully uh get the three four so that's why output is three okay so let me explain with this example one three five and the k equal four I already sorted the input array like this um they I think there is a case where input array is unsorted but there is a we don't see any constraints such as subsequence or RJ Center rules so I believe we can sort input array like this and there are a few variables one is a left pointer and the right pointer initialized to be zero and the result variable also initialized with zero this is a return value and the current total is uh like a num is a total number of between left pointer and the right pointer and uh I already write down the some formula so how to explain this so to solve this question light pointer is kind of a target number so let's say light pointer is now index 2. and so I use this formula so now right pointer is three multiply and this is a length of window with the index pointer and the right pointer so 2 minus 0 plus 1 is 3. and total nine so what is 9 about as I told you a right pointer is kind of a target number so if all number in the range are three in this case um this number is three total of all numbers in the range are nine so and then greater than this total is actual total number in the range so that means like 1 plus 3 and the Seven Plus k for so we can increase the number four times so that's why we need plus four so total 11 so 9 is greater than 11 it's not that means we can expand the range to next and then we do the same things for this range okay so what if this number is four so this number is 4. so total of all numbers in the range should be so like this is a kind of Target number so we need to this number four and this number also four so total four multiply 4 multiply 3 and a total 12. but the actual number is 7 plus 4 and 11. so 12 is greater than 11 yes in that case uh we can get like a 3 4 because we need a 12 but uh after uh increment operation we get like a total of 11. so we have like a one shot so in that case we have to shorten the current window so in that case we need to move left pointer to next so current lens should be like this so that's how we can use this formula so let me uh explain from the beginning okay so let's begin um first of all uh one multiply uh zero minus zero plus one is one and one uh is greater than total is one plus K and 5. we don't meet this condition so in that case just uh update right pointer to next and now um right pointer is now three and three multiply 1 minus zero plus one is two so total six is greater than current actual total is 4 Plus k for eight so six is great thousand eight uh it's not so in the case just update the to a right point of the next oh uh by the way uh ranks of range should be uh answer so now uh so we confirmed that we can uh change all numbers to three or when we have a range like from zero to one so now size two and then move next and now the right pointer is three so three multiply length three is oops um equal nine greater than actual total is seven it's hard um three plus four eleven so 9 is greater than eleven it's not in the case um result should be three because uh we can change all numbers uh to three uh between current range so in the case just move next right point up to next and then again now right pointer is five multiple I write is now of 0 1 2 3 minus 0 plus 4 is 4. so total of all numbers uh 20. so great doesn't actual total is one plus C plus C7 and 12. Plus 4. so 12 is greater than 16. yes in that case um we have to shorten the current window so in the case we move to uh left pointer to next so now our ranks of range should be C so 3 and if all numbers are 5 in the case uh total of all numbers should be 15 is greater than current total should be uh should be three plus five and eleven plus four 15 so 15 is greater than 15. this is not greater than or equal so it's not in that case we can expand the range to next and again uh so now uh Target number is five so five multiply so lengths between left pointer and the right pointer is now full equal oops 20 is greater than so current actual numbers should be uh 10 plus 16. Plus plus four twenty in the case we can expand the range so before that current ranks of the range is now one two three four so up to date a result variable to four and then move next but there is no number here so that's why uh visually down four okay so let's check so now we have two five and if I update this three to five and the rest of the K should be two and uh we find another three if I update this three to five okay should be zero and then we successfully get uh four or five yeah I think that is the answer okay so let's write the code first of all um we need to sort input array so salt and uh we have a few variables like a left pointer equal right pointer equal result variable and uh total variable uh initialized to be zero and start looping if right pointer is less than length of nums in that case um first of all calculate current actual total so total plus equal numbers and right and a while current Target number multiply light minus left plus one this is a window ranks um between left pointer and the right pointer is greater than total plus k in that case we need to shorten the window length so total minus equal numbers and the left because uh this left number is uh will be out of bounds and then up to date the left pointer to next after that compare current max length versus current length so result variable equal Max and the lasers variable and the right minus left plus one after that um move light pointer to next so right plus equal one and then the term result variable so let me submit it yeah looks good and the time complexity of this solution should be order of n log n because uh we sold input array here and the space complexity is um so in this program uh o1 but uh depends on uh sorting algorithm it should be like a order of n or other complexity so it really depends on sorting your algorithm here so let me summarize step-by-step so let me summarize step-by-step so let me summarize step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of frequency of the most frequent element step one inside the left and the right pointer result in the current total variables and the step two start looping at the current number to the current total and a certain window size between this and the right pointer if number so current right multiply current window size is greater than total current total plus K operation step 3 compare the current length with the current max length yeah okay that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
144 |
um hello so continuing on January lead code daily challenge one of the problems today's problem is binary tree pre-order today's problem is binary tree pre-order today's problem is binary tree pre-order traversal um so what this problem says is we get the root of a binary tree and we want to return the pre-order and we want to return the pre-order and we want to return the pre-order traversal of its node values so pre-order traversals means root first pre-order traversals means root first pre-order traversals means root first then the left node then the right node right so for example here first we do one the root node then it's left child there is nothing so we don't add anything um the right child which is two so we add two then the left child of that which is three um and then right child there is nothing so we add nothing right so that's the idea of pre-order so that's the idea of pre-order so that's the idea of pre-order traversal so we can do this really simply using DFS we can choose to do either um DFS uh recursive or iterative using a stack so we'll also do both but first of all starts with DFS so um recursive DFS so what do we need we pass in a node um and what do we need to calculate here so we need to return the node first but because we want it as a list right we want to concatenate it as a list we put the value in a list and then we add it to the whatever result we get from the left side so remember the pre-order the left side so remember the pre-order the left side so remember the pre-order means traversal means root left right okay and so the root here is this one and then the left side and then the right side and the reason I said we are doing in a list here is so that we can concatenate list if we just do this it won't work because this returns a list for the left subtree this returns a list for the right subtree and so you can't add to a list to a value um and so we need to convert it to our list now what if we are at the last node let's say maybe we are at three and we go check the left side which is nothing well in that case we should just return an empty list because there is nothing that way nothing will be added to the list and so we can just return nil again for the same reason because we want to end up adding it as a list and so we can't add the null to our list you can say like 1 2 plus nil right and so instead we'll return an empty list that way it's just one two right so this here will say if it's so you can do it or no it is none or you could do just if not node in Python and then we would return an empty list in that case and now we have our recursive function we need to start it by calling it on the root and so we'll return that value and this should work let's submit and that passes okay so that's the recursive solution now how do we change it to be um to be a an iterative one so we need to use a stack instead so we use a stack and we initialize it with roach in the same way we are starting here with root and then we initialize the results that we want to return at the end and now we keep going through the stack and each time we extract the node so we pop it okay and we since it's root Left Right which means we need to process the node first which means basically we want to add it to the we want to add its value to the result but then we want to go through its left and right okay but because in a stack if you add two first and you add one later one would be puppet first right so if we add we do the same order and add left first and add right on top then right would we process it first but that's not what we want to left process it first and so we add left the last one and then right first that way when we extract the first one we extract is left and so here when we are going through the child we want to start with right and then do a left so let's just actually just do it so append no dollar right first then add node.left so that one would pop then add node.left so that one would pop then add node.left so that one would pop we pop the left side first so that we'll expect this order right and now there is only one thing is what if the node we added was null in that case what we want to do is we want to check here if node then we do all of this okay um and that should be it so let's run it and looks good let's submit and that passes test cases as well yeah um yeah so that's pretty much it for this problem uh please like And subscribe and see you on the next one bye
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
1,647 |
how's it going guys today we'll be working on legal question 1647 it is a medium difficulty it's called minimum deletions to make character frequencies unique okay so in this question we're given a string s and we're trying to figure out if it's good and if it's not good how many uh characters do we remove it so that is good so what is good a good string is when um the frequencies of all the characters that exist in the string are not the same okay so say we had this string we had a b and c we see that there are three a's three b's and two c's okay those numbers are called frequencies is how many of the same of one character exists in there so the frequency of a is three because there are three a's in there we also see that frequency of a and b are the same which means this is not a good string and the question is how many letters do we remove so that it is a good string there's a couple ways to do this for the string okay uh we can see here you can see the explanation here that if we remove two b's that means we're gonna have uh three a's one b and two c's and none of those frequencies are the same or we can remove one b or one c making there to be three a's two b's and one c and no clashing frequencies and each of those takes the number sorry each of those take two uh two deletions of course we could do removing three a's which leads us to three b's and two c's and zero a's but in that case we're removing three letters so that doesn't really work okay so for sure the first thing we'll need to do about this question so uh let's i'm gonna try this i'm gonna write this example here okay so we have triple a triple b double c so i have this the goal here is to um essentially make all the frequencies unique right uh but we for sure need to keep track of how many frequencies they are for each character so we could use a dictionary today we're going to be using a thing called um collections.counter okay collections.counter okay collections.counter okay all it works the same way as a dictionary but it just takes in the string s and it'll make the dictionary for us so just so we understand what's going on here um we have a right b has three c has two so all this is saying okay there's just some data type that tells us there's three a's three b's and two c's and the goal here is to make each of these numbers unique sorry all of these numbers uh to be unique right in this case we have two threes and one two so that's not good okay um so let's just write this to be clear let's just say we had you know we're storing these numbers to be like this okay we need these to be unique now our question seems a little bit we can look at the question uh differently so how do we make these unique well we can go through each of these numbers and then because the goal here is to decrement um any of these numbers so that they're all unique and making sure that it's minimum so the key here is to uh is to think of it as each number has a place to fill okay so um let's say we had a set okay so we had a set okay uh we know that there are there can never be let's make this darker there can never be two numbers that are the same okay and in this case we can use a set okay so say we filled in uh you know they cannot be do the same so say we just filled in so our first loop we filled in so let's just call this s okay our set s so first we filled in our set has whoops our set has the number three okay um so three doesn't exist in the set yet okay the goal sorry remember the goal of this set is to keep track of what frequencies we used so if we go on the first number okay we see that uh three doesn't exist in the set yet so we're going to add three okay and then the second loop we're going to go to the next number three we see that three does exist in here what that really means is hey we already have a letter that has the frequency three so you're going to need to decrement that until it's not in the set anymore right uh since a took the a already took the count of three b has to take a different count that is not three and less than three so we're going to decrement it by one right b becomes two and then we see that two is not the in the set s so now we can add it okay so now b has taken the place of frequency two a has taken k place of frequency three and then we're gonna go to c right c has a frequency of two is already in the set so let's decrement it by one is not in the set therefore we have three two one and every single time that we decrement um a number this frequency count all we're saying is that's how many characters we'll be removing from the string right in this case when we decremented this three to two all we're saying is we're gonna move one b when we're decrementing this two to one all we're saying is we're moving one c okay and we're gonna add those two together right so those two numbers together in this case is two right this is our count really but this is how many we're going to be removing right um i hope that makes a bit of sense and um one thing we'll think about also is what if it goes down to zero so say if we had three two one and then we had let's say letter z that had a count of three right we had a letter z that count of three well in this case using the same algorithm that we just said let's say so it's three existing here decremented by one count becomes three now uh now two is already in here decrement that count becomes four decrement that count becomes uh five and decrement that again now we have z is equal to zero and that's perfectly fine if z is zero that means uh what happened was we're saying z couldn't be three because a took that spot so it couldn't be uh two because b took that spot and the same thing goes for c z couldn't take one because c has that spot therefore it had to be zero and in this case we'll be moving five letters instead okay um in this case we're always going to be taking the minimum amount of deletions because uh we're filling in every single uh you can think of it as a frequency spot or frequency uh slot that we can put in so let's just start coding it out now how do we do this so instead of making uh an actual dictionary doing this you can do this too there's a very useful built-in data too there's a very useful built-in data too there's a very useful built-in data type called uh collections.counter it does exactly uh collections.counter it does exactly uh collections.counter it does exactly the same thing um and it takes in the counter s okay so each value each key is going to be a character and each value is going to be how many like how many times that character occurs in this in string s okay and then we're going to have a result equal zero so this is what we're going to increment every single time we take out a letter during our loop um and then we're just gonna call uh our set as reset okay sorry i said to be oh we don't want to be calling so just say used okay so this is gonna have all of the uh this is going to have all the integers which represent really letters um that has taken up that spot in the set so remember a goes in here so if there's a three here that means a letter has taken up the spot three a letter b has taken the spot two and it's like i explained before so we're gonna loop through i'm gonna loop through our dictionary so-called and we just use our dictionary so-called and we just use our dictionary so-called and we just use dot items for that okay so this is going to be a character it's going to be a frequency okay and while we're looping through if the frequency is ever zero that means there's at least one letter in there that we haven't decremented all the way to zero so we haven't removed all the letters yet and it's still in used right so if it's if so remember if it's in here and it's at least greater than zero that means that letter is still in the string that letter if that letter is still in the string and it's in here that means we need to keep the keep decrementing it because we cannot have this means uh we have the same frequency as another letter and this means it still exists in the um in the string okay and what we're gonna do here is again we're gonna decrement um the number until we find a spot okay and we're also going to add our result by one okay and every single time that we're done this okay so frequency is at some number where all we're going to do is add three okay that's where we're going to add it we already have our account and we're going to be decrementing all the way until either zero or until the letter finds a spot or the number from the spot and then we're going to return res okay so we'll run the code um submit and we have a really good answer uh this answer is that i found it in discussions is obviously not mines my solution is very ugly but it was very useful to be able to understand this and explain it to you guys so thanks for watching hope to see you
|
Minimum Deletions to Make Character Frequencies Unique
|
can-convert-string-in-k-moves
|
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.
**Example 1:**
**Input:** s = "aab "
**Output:** 0
**Explanation:** `s` is already good.
**Example 2:**
**Input:** s = "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ".
**Example 3:**
**Input:** s = "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters.
|
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
|
Hash Table,String
|
Medium
| null |
462 |
hello everyone welcome to day 19th of may liquid challenge and today's question is minimum moves to equal array elements too in this question we are given an array of size n and we need to return the minimum number of moves required to make all the elements of the array equal how can you define one single move in a single move you can increment or decrement a value of an integer by one so let's try and understand the solution by the presentation that i have created for this it's not a very hard problem just one simple trick and you will get the answer so let's get started and let me just start the slide show let me just take a pen minimum moves to array elements 2 solution lead good 4 6 2. so the question says make all the elements of an array equal to a single element and in one operation in an increment or decrement and r element by one we need to identify minimum number of such operations required to make the all the other elements equal so the only caveat here is identifying what should be that element to which all the array elements should be made equal to for example in this array we have 1 10 2 and 9 which element shall we pick up 10 2 9 or 1 to which all the other elements should be made equal to and that element would be nothing but the median of the array why i am saying the median element because median element has a property that it stands at the middle point and all the elements to the left of it will be lower than the current this median value starting from the least uh to the closest one and all the elements to its right would be greater than the median value so we'll try to balance each of these elements to the median value and that will give us the minimum number of operations needed to make all the elements of the array equal now we know which element do we need to choose so let's try an iterator one of the examples of the first thing we have we are going to do is to sort the other so that we can identify the middle element so we have one two nine and ten what will be the middle element the length is 4 the second element the element at the second index which is nothing but 9 so we'll try to bring all the elements to element 9 so how much more should we need to add to one eight how much more should we need to add to two seven so we don't need to do anything so it's zero and ten we need to delete one from it so the answer is one here the totality of these operations is 8 plus 7 is 15 plus 1 is 16 so we get 16 as our answer so let's try and understand it by another test case what we will do will sort the array because in order to identify the middle element we need to do the sorting operation so we have one two five nine and ten so which one is the middle element fifth five is the middle element so we'll try to bring all the elements to five we need to add 4 here we need to add 3 here we don't need to do anything here we need to subtract 4 here we need to subtract 5 here so what is the total sum of these elements 4 plus 3 is 7 plus 4 is 11 plus 5 is 16 so the answer again is 16. now the problem reduces to identifying the middle element out of the input array there are two approaches of doing it the first one being the naive approach you sort the array uh and you find in the middle element would be at the index length by two the time complexity for this approach is order of n log n because you are performing the sorting operation the first thing that we are going to do is to sort the array and once we have that array sorted we'll try and identify the middle element of the array which will be the median one it would be at the index length by two and we'll start the iteration in the input array we have also maintained account variable that will store the number of counts that we need to make and count would be equal to count plus equal to the absolute value of element minus the middle element and in the end we'll simply return the count so let's just try this up accept it but the time complexity of this approach time complexity is order of n log n because of the sorting process and space complexity is order of one
|
Minimum Moves to Equal Array Elements II
|
minimum-moves-to-equal-array-elements-ii
|
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_.
In one move, you can increment or decrement an element of the array by `1`.
Test cases are designed so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** 2
**Explanation:**
Only two moves are needed (remember each move increments or decrements one element):
\[1,2,3\] => \[2,2,3\] => \[2,2,2\]
**Example 2:**
**Input:** nums = \[1,10,2,9\]
**Output:** 16
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Math,Sorting
|
Medium
|
296,453,2160,2290
|
969 |
hey everybody this is larry this is day 29 two more days of the lego daily challenge on in august uh hit the like button in the subscribe button also my apparently my math is wrong there three more days but uh anyway let's get to uh pancake sorting given an array of integers a we saw them with pancake flips okay that sounds straightforward uh we don't have to do it optimally okay so we just need to make ten flips um okey so these are just an example you look forward to the okay uh okay and a is n is equals to a hundred so we can do really lazy things to be honest um and they're all permutations so that's okay uh yeah and then one index so i think the strategy i would use and these are actually just these kind of problems come up a lot more on code forces uh or competitive programming where you have these constructive algorithms uh where you don't have to be the minimal or the best you just have to do something within some bang right so the way that i would think about it just try to think about a property that you can observe that could just get you um something that gets you closer to the answer and then able to get it in an iterative kind of way right um and here um because with pancakes you can only flip the top of the pancake or the beginning of the array right so that means that what you want is that once you set something in place you don't want to flip it again so by that logic um i would try to do something like okay given here uh from one to four i would try to get four to the back and then never touch it again uh so when you're naively that's gonna be um you i would imagine you flip the fourth you know you flip from the four to get to the beginning and then you flip it from the beginning to the end so that means that for each element you're going to flip at most twice um and that means that'll be good for this bound and then you have to think about implementation details but because n is less than 100 or less um you know this you can do it with a very naive n square or even end cube algorithm so uh so that'll be fast enough that for me to get started um yeah and that's what i think i'm gonna do so basically the idea is uh get max from zero to some k and then almost like um what is that like so basically it is essential selection sort but using pancakes right because for every iteration of the array you take the largest element in the prefix and then put it into the back and then just keep on going um so yeah so it's a variation of the selection sort and that's where i'm gonna get started uh yeah cool so n is equal to length of a um let's start with k is equal to n because we want to get the entire n and we just get yeah while k is greater than zero uh because if it's zero then the first element should be good uh and also we just have an output array so answer is equal to this um return answer um okay so then now we get the max element uh or is it the maximum i mean it would be the max element but you can also probably do the math to look for a certain number right for example your first iteration for the array you're just going to look for the four because odd gives us a as a permutation from one to n so you can actually skip just like doing a little bit of it's the same logic and the same complexity but it's just different way of thinking about it uh but this different way of thinking about it allows me to use a library function instead of a for loop so basically i want the prefix um i want to find so if k is 4 because k is n in the first step we look for 4 right so um i think this is the syntax so yeah so swap is naming is terrible but um let's just call it index is to go this um and i make sure you do and then now you um so what we want to do now then is to swap on the index so now that moves it to the front and then now your second move will be to use the entire array so it'll be k right because or not the entire way but the entire subway so these will be two moves and then now we have to update k to accommodate these two moves so and i'm a little bit lazy right now and i don't think we need to worry about complexity so we could just do it manually um or we could just do it with a linear thing maybe we could be a little bit smarter uh if we need to but i wouldn't worry about that necessarily just yet so okay so now we reverse the first indexed element so plus and then a as you go to the uh now we want to reverse the first k elements right i think this is roughly right though i might have off by one so let's play around with it and oh yeah the other one's just a sorted one hmm oh i'm just being silly with the syntax maybe that's right i don't usually when you mix them or when i mix them together i get a little bit confused uh which one takes precedence uh but that's just me um three is not an indexing so yeah uh let's see all right i think what i meant to do then is this so let's i mean that at least i mean you do take a performance hit but uh at least for me i know that i'm gonna be right on this so then at least we can kind of uh take a look uh at the debugging right and then you know uh you can always save the optimization for later uh the first thing is about getting the concepts right uh and okay so this is the input array we swap oh because four uh so this is off by one in that case like i said so this is the index but this is a zero index so we actually want this plus one okay yeah so there we go um again we you know we don't expect our answers to be the shortest answer so it's okay but we can clearly tell that um you know and we can add some if statements to terminate early i don't think it's a big deal so i'm not going to do it but you can see that you know at the very end it's sorted and that's good enough for me so yeah so let's fund the call again uh you do maybe get a little bit of a time penalty but i don't worry about it um i think for these constructive algorithms uh you go accept it but these constructive algorithms um you know challenge yourself and up solve it later but in you know your first instinct should just resolve it in any way that's accepted uh as and as long as it's fast enough there's additional new ones in the code in that uh the time complexity or the not the complexity but the running time is the sum of all the test cases so in theory uh there is a little bit of carryover uh in terms of performance but otherwise it should be okay um and as long as you're mindful of that if it you know comes up in a weird way but yeah overall i just did the most naive thing that i can do uh which is like i said selection sort uh going all the way to the back because we can only control the prefix right so yeah so this tests you a little bit on your sorting algorithms uh you know and yeah um so definitely you know play around with study it um but yeah it seems pretty okay uh yeah let me know what you think about this problem uh seems okay difficulty uh hit the like button to subscribe button leave a comment join me on discord and i will see y'all tomorrow bye
|
Pancake Sorting
|
number-of-recent-calls
|
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
| null |
Design,Queue,Data Stream
|
Easy
| null |
62 |
in this video we're going to look at a legal problem called unique paths so we're basically given a robot that located at the top left corner of the m times n grid so we want to figure out how many unique paths that the robot can travel down to the bottom right corner of the grid so you can see here we have an example where we have a three times seven grid right so robot starts at the top left and we want to know how many unique ways that the robot can travel to the bottom right in this case we have 28 ways right we can either uh for each and every single cell right we can either go to the right or we can go down right so we can either move down or we can move right at any point in time so let's say we have an example right where we have maybe two by two so how many possible ways that we can travel to the bottom right in this case we're starting here and in this case we can go here right we can also go here and we know that for each and every single cell we can either go to the right or we can go down we cannot go top or left so in this case we have to know the total unique ways if we go to the right if we traverse the if we traverse on the right side and we want to know the total unique ways that we have to traverse the to the left going down to reach to the bottom right so what we're gonna do is you can see here let's say we have a two by two what's going to happen is the parent stack will ask its uh children stack right in this case the parent stack will go to the right and try to find the total unique ways for it's to go for this robot to go to the right to reach the bottom right and then what we're going to do is that the robot will also go down or try to find the total unique way to go down to find the total unique ways to go to the bottom right so in this case this when we get to here when the robot gets here then the robot will go to the right and also go down to find the total unique ways for this position to reach the bottom right so if i go down in this case there's one way because if i go down i reach the bottom right so what's going to happen is we're going to return back to the parent stack say there is one way to reach the bottom right and then if we're here like at out of bound then pretty much there's no way for us to reach the bottom right so we're just going to tell the parents that there's zero way to reach the bottom right so what's gonna happen is that for this parents for this stack right here right for this position we take the total uh unique ways to reach the bottom right which is only one so in this case for the current position to reach the bottom uh bottom right it's just going to be one and then what's going to happen is it's going to return back to its parent stack where the parent cell to tell the parent cell or tell the parent stack that the total unique ways for if we go down to this path or for this current position is gonna be one right so there's only one way to go to the bottom right so we're gonna tell parent stack that and then parent stack will also go to down right in this case if we go down then in this case we will also get one because here you can see if i'm at this position total unique ways to go to the bottom right in this case it's just one right if i go down that's out of bounds so there's zero so what's going to happen is if we go to the right there's one path so we're going to return back to its parent stack so if for this position the total unit path to reach the bottom right is just going to be one so now the parent stack knows the total unique ways for going to the right and total unique path to go down then we're just to get a sum out of those two decision to those path and we'll we will get the uh total unique ways or total unique path to go to the bottom right for the current coordinate right for the current position so to do this in code uh what i'm going to do is i'm going to have a global variable m and a global variable n and uh basically what we're going to do is we're going to set m is equal to m this dot n is equal to n we're gonna use a recursion uh function to solve this problem we're gonna say return helper we're gonna start we want to know the total unique ways for the first cell in our grid right and at the end we want to return the total unique ways for this coordinate and all this function is trying to do is trying to return how many unique ways for the current row and the current column okay so what we're going to do is first we're going to just check to see if uh the base case right if we satisfy the base case and the base case is that if rho is out of bound right if row is bigger than um or equal to m or if column is bigger than or equal to n the reason why we check those two because we the robot can only go right or down so we don't have to check to see if we're if the row is less than zero or l or the column is less than zero because we're not going to go to the left or the top so if that's the case if we're out of bound we can just return zero right because there's no way that we can reach the bottom or the bottom right if we're out of bound right so then what we're going to do is we're going to calculate the total unique path so if we go down the total unique path in this case is going to be row plus one so it's going to be the next row and the same column so what's going to happen is we if we're also going to calculate total unique ways if we go to the right so it's going to be row at column plus one so this will calculate uh the total unique ways for this coordinate right here right and at the end we're just going to return the total unique ways for both if uh both uh going down right the path that we go down to reach the bottom right plus the path that we go to the right to reach the bottom right okay and if we were to run this in code we'll get fail because one thing that i forgot to do is in this case if we're reached to the bottom end right if row is equal to m minus one and the column is equal to n minus one right the last cell we're going to return one because we found a path right so now if we were to run our code you can see we have our succeed right we basically works but the thing is this will give us a time complexity of exponential so what we can do is we can use a cache right we can use a 2d integer array okay which cache the result if we visit this place before right if we visit the cell before we can be able to um like return the pre-computer result um like return the pre-computer result um like return the pre-computer result right because you can see here for this position right you can see we're going to the right we're going down and in this case for this cell right here i also have to go to the right and go down so you can see but here for this cell i also had to go down and go to the right to calculate a total unique path so you can see that this is being called two times or twice so what we can do is we can use cache right to basically cache this and this will improve the time complexity down to a m times n so let's try to do that so if this position uh is not null right if it does not equal null then we can return the pre-computed value right and then what we're going to do is that for this position once we calculate it we can just save that in our cache okay and then we can just return the results to the parent stack so now if we were to run our code you can see we have our succeed nope it didn't work okay the reason why didn't work so the reason why it didn't work because i didn't define it so in this case cache is going to equal to integer at m at n okay so now if we were to run our code and now let's try to submit and you can see we have our success okay so now let's take a look at how we can do this using a bottom up so to do this using a bottom-up approach so to do this using a bottom-up approach so to do this using a bottom-up approach basically we know that if we're at the bottom right in this case the bottom right finish line then in this case there is only one way right in this case there's only one path to reach the bottom and if we're here right what's the total unique path to grid to the bottom right in this case only one because we can only go to go going down to reach the bottom right and if we're here total unique way to go to the bottom right is just going to be one to the right so there's only one path so for those two elements we know that there's only one path to reach the bottom right but what about here well in this case we know that the total unique path for here is one and total unique path to reach the bottom here is one so in this case to figure out total unique path for this position is going to be the bottom right plus the bottom sorry the bottom uh position the total unique path for the bottom uh cell to reach to the right to reach to the bottom right plus the total unique ways for the right cell to reach the bottom right in this case one plus one will give us two so here is gonna be two okay so what about here in this case we had to figure out this one so in this case there's just gonna be one because for the bottom row you can only go right and here you can only go down so these ones you can set it as one so here you can see here um if i go to the right there are two unique ways to reach the bottom right if i go down the total unique way to reach the to the bottom right is just going to be one so it's going to be the total for those two paths right for those two uh unique way cells so it's going to be 1 plus 2 will give us three so there will be total of three right three unique path to reach the bottom right here so you can do this way right you can do this way and so on and so forth right so what we can do is we can set those borders elements to all be one right these borders all to be one we're gonna start at the at here and then working our way up right so but let's take a look at some edge cases here so if we only have just like maybe let's say we only have here like one by two right so in this case same thing the bottom row will be just one so here's one if i have something like this same thing it's going to be one and one here but if i have something like this right this is just only one cell then it's just going to be one right so those are the base cases is that basically we want to fill each and every single the bottom row as well as the last row and last column to be one and then we're gonna and then what we're gonna do is we're gonna start at this position right if there is a position that we can start so in this case what we're gonna do now is we're gonna do the using a bottom-up approach so to start first i'm bottom-up approach so to start first i'm bottom-up approach so to start first i'm going to create the cache array and then basically we're going to say integer 2d i'm going to call it cache with the size of m and there's going to be n number of columns so for each and every single row that we have right so for each and every single row in cash we're going to set each and every single row so arrays dot fill so we're gonna fill them with ones okay initially we're gonna fill them with once and then once we fill them with ones right now we have the bottom row and then every pretty much every single cell to be one and what we're going to do is we're going to start at the um the bottom right the very the second uh the last second row and the last second column so we're going to say for integer the current row is equal to m minus 2 right m minus 2 will be the last second last row let's make it index so i is equal to rho minus two and then while i is bigger than or equal to zero i minus right and then let's have a j pointer so in this case integer j is equal to column or sorry not column this is m sorry so this should be m and then j is gonna be n minus two and then while j is bigger than or equal to zero right j minus okay and then we're going to start at the second row and second column and then basically we're going to do is we're going to calculate each and every single position right and then at the end we're just gonna return cash at zero right and this will give us the result because we're starting it here and then we're going to calculate this the total unique way for this cell basically the answer is going to be the total unique ways for the bottom cell and totally unique ways for the right cell to reach bottom right so we're going to have a bottom is equal to cash right at i plus one at j okay and then the right is equal to cash at i at j plus one right and then what we're going to do is that for the current position so cash at i at j is actually equal to the sum or the total of all unique path for if i go right or if i go n if i go to the bottom right so bottom plus the right so this will give us the total unique weight for this current position and we're just going to do it one by one and for each and every single position until we reach the first cell in the array right for this first cell in the grid so if we were to run this you can see we have our accepted and now if i submit the code you can see we have our success so the time complexity here is going to be m times n and its base complexity is also going to be m times n because of the 2d cache array
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is 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.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
299 |
Hello friends, in this video we are going to do all the balls and count in this game. There is a question which is quite tricky and when I wanted to understand it, I was not able to understand it but I will explain it to you so well that after watching this video. After this you will definitely not have to watch any other video. Question What are you playing Bills and Count game with your friend? If you want to play Balls and Count game with your friend, then he has given you some secret number. You have given some secret number. And your friend is doing gas, then you have to tell how many words will there be in it, how many coaches will there be, okay, so first I think the question is a good way for you and then we will move towards it, okay, so first ask the question very carefully. If you have to understand then only you can understand the question. It is also one thing if you have written a secret number 1807, your friend is zero. So now you have to tell me how many numbers of coaches are there and what are some of the characteristics of the question, what are some of the conditions. That if the number in the secret number is the same number as in the Se Tu Se Gas number and both are from the position then what will happen to us then our strength will be. If that number is there in the secret number but the same number is also there in the gas number but the positions of both are different, both are at different positions then what will happen like here the secret number is given 1807 and here the gate number is given 10 then see What is its position? One is its zero. What is its zero? Both the elements are equal to each other. No, they are not equal to each other, but is the 7 which is 7 present in it? Yes, it is present. What does it mean if both the elements are not equal to each other, but? If the guest number which is 7 is present in the secret then what is this then what will be the value of the first zero? Yes it is equal when it is equal and the position of both is also from then count the mistake what is the zero Is is equal to one No is not equal So now I have to check whether the one which is in the one gas number is present in this secret Yes it is present here It means are both not equal but both the numbers are at different positions If present in both, then add K's account to this page. Then here whatever is seven is equal to zero, no is not equal, is the zero in it present in the gas number, is it present in the secret number, yes present means what is the account of less. Increase it and what to do in the last thing is you have to delete it for the bill and for whatever is less than it you have to donate B, then how much is it tomorrow, one is bol and 3 is how much is B, you have to return like this. The secret number is 011, it is not equal, what is the zero, which is of G number, is the story present in the secret, is not present, then neither is one nor one, what is this, is it a mistake and what will they write by writing, zero is nothing. Now I will go here, I will get totally confused because as soon as it is equal, what does it mean? Okay, then I will go, what is here, are both the elements equal to each other, no, not equal, what is the one here in gas, that is the story in the secret, yes, here is here. What does it mean? Both the elements are equal to each other. Now what is the one? The story is present in it. The answer is in the cigarette. So I thought, by now you must have understood the question. The question is about nothing. You have been given a secret number. A guest. Number has been given, you have to tell how many number of coaches will be there, how many number of balls will there be, if both the elements are secret and the position of both the elements in the gas and the element will be from then the mistake will be made if the position of both the elements will be different but If both the elements are present in secret and gas then they will represent co. Okay, so how will it be solved? How will it be solved? See sir, I tell you very easy ways like here the secret is given as 187 and here as 7810 so if you want then you can use the map or you can You can count, if you do it then you will have to make an area of 10 size you do it then you will have to make an area of 10 size you do it then you will have to make an area of 10 size because from zero to 9 you will have to install the elements like the count is 10 and if you map it then you can do something in the order or map it. I will tell you both, I will count and tell you and first of all I will tell you what to do which is a secret number, it will be to reduce its frequency and like here it means zero is one to three which is one is seven. Is it equal to one which is equal to seven what will I do before that if it is not equal then what should I do should I go ahead if I want to reduce the frequency then how much will be the next frequency will be zero okay then I will go ahead again now I will do it again, you will check that its frequency is one, meaning seven in this, one was big, now I will check this also, seven one is big in this because what was the condition of co, that the element should be present in both of them. If its position is different then why am I checking whether the 7 here is the 7 here? 7 has come once, has the 7 come once in this, then Kabul has increased, okay, then the value of i will now go to a here, then I will check that it is equal, I will leave it like that, then I will go here, plus I once, now whatever is zero here, whatever is zero, what is its frequency, 1 and what is how much less than zero, its frequency is one, meaning, A will go out. So now whatever is our mistake, we have to simply return it, you do not have to do anything, you have to start and compare these two and check whether the one and the seven are not equal, then is the frequency of the one consumed equal to that one? What will we know from this that there is one bar in it, what does it mean, we will increase it and in the last we will return like this. Have you understood how much, I will tell you the count, so if I talk about time city, then it will now become N and space. Density of course mapped. Now let me move ahead in the first video and if you want to learn to build and also learn the concept very well then you can take the score of GST. If you click on the screen and go, you will get 10%. You will get click on the screen and go, you will get 10%. You will get click on the screen and go, you will get 10%. You will get discount if you do Triloki Teen Coupon Guide because I have read from it so you can read from it if you want then if you know then I am in the video okay I will tell you okay so what we have done I have made and Zero and one answer, what have we done? One photo has been taken and every element has been done. Okay Meaning, what are the two Ghats, okay then we will do it What should I say, I have to increase it, like I have told you here, I am quite in depth. I have told you the thing here, where did it come from, I told you here, okay, this is the incident and at the end, you have to put a character here in this question, the solution of Java, if you call it C plus then I think you must have understood the question, how then? If you don't understand then you have to rewind the video and watch it again and you will understand. And friends, I would like to make a request to you that your social media handles can help you in going better and me too. What you have to do is simply link the video that I am making or whatever it is, take a screenshot and go and tag me there and share it with your friends so that they will also know that Mattist is doing a very good post and which It is helping many people, so this is our C Plus code, what will I do, will I run it is working fine and as I click on it is getting direct now, so much load is put on the system that you can do it and you You can Instagram by taking a screenshot of this course so that more people can get help now and I will simplify, I will serve your doubts very well and if you have any problem then my WhatsApp number is given in the about area, you have to message me, don't do it tomorrow. Because I am busy in the office maximum time, I do n't know how to pick you up tomorrow, but if you message me.
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
1,630 |
hello everyone welcome to my channel here I solve L Cod problems and prepare to the court interview today's problem number is 1630 arithmetic subarray a sequence of numbers is called arithmetic if it consists of at least two elements and the difference between every two cons consecutive elements is the same for example this are metic sequences 1 3 5 7 9 7 777 and 3 - 1 - 5 sequences 1 3 5 7 9 7 777 and 3 - 1 - 5 sequences 1 3 5 7 9 7 777 and 3 - 1 - 5 - - - 9 and the following sequence is not arithmetic 1 2 57 and you are given an array of an integers nums and two arrays of M integers each L and R representing the M range queries where the I query is the range from L ofi to R ofi all the arrays are zero indexed return a list of Boolean elements answer where answer of I is true if a subarray can be rearranged to form an arithmetic sequence and false over otherwise let's check restrictions uh you can see they have input array from two to 500 elements and uh from 1 to 500 quaries it's not so long so many items so uh we can try to solve it straightforward let's do it what we need to do first of all let's get number of queries to do it we can get length of r or L for in let be it be L El we need to Define a variable for answer let's call it answer and but by default it be empty list and return it after we check all queries get subarray sorted because every arithmetic subarray is sorted ascending or descending and check if every two consecutive elements have the same distance between them so let's do it to go through all queries we need to use Loop in range from zero to M because we have M qual after it we have uh we can do one small Improvement in case of distance between right and left side for this qu no longer than two in case in this case this uh Sub sub subarray will be arithmetic because two elements uh are already arithmetic sequence so let's check it so ERI minus L of I + I + I + 1 is a length of subarray if it's less or equal than two in this case i' add case i' add case i' add true to answer otherwise let's get Saar let's call it sub and get it will be a slice from nums uh started from lofi to R of I plus one because in Python flies doesn't include right side right after it let's sort it use method sort now we have sorted array and the we need to check if every two subsequent elements have the same distance between them so first of all we need to get this distance let's call it step and it will be equal sub of oneus sub of zero so it is the distance between two first elements and let's check all P to do it check in the loop from J in range of length of sub and we will check it from index two because first two items we checked before when we get step and let's check if sub of J minus one so it's current distance not equals to step in this case we need to Define some sub result so it result for V Square by default it's true and if conditions false so if current distance not equals to step in this case sub result will be false and break the loop after all checks we will be get true if all sub all pairs has the same distance step otherwise it will be false and don't forget to add sub result to answer append sub result that's it let's check tests so test pass let's submit it and I hope it will be enough to past all tests and uh will be quite effective and not and let's check it yes it works and it's pretty effective so in some cases we can use and the make straightforward Solution that's it for today thanks for watching see you tomorrow bye
|
Arithmetic Subarrays
|
count-odd-numbers-in-an-interval-range
|
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.
For example, these are **arithmetic** sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not **arithmetic**:
1, 1, 2, 5, 7
You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
**Example 1:**
**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.
**Example 2:**
**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]
**Constraints:**
* `n == nums.length`
* `m == l.length`
* `m == r.length`
* `2 <= n <= 500`
* `1 <= m <= 500`
* `0 <= l[i] < r[i] < n`
* `-105 <= nums[i] <= 105`
|
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
|
Math
|
Easy
| null |
84 |
hey everybody this is larry this is day 29 of the general eco daily challenge almost to the end of the month hope you're doing all right stay good stay healthy wait what now hit the like button hit the subscribe button join me on discord let me know what you think about today's problem i just i don't know largest rectangle in the histogram okay it's a hard problem and you're trying to figure it out okay i mean i've uh so i would say that for this problem uh oh yeah i guess sometimes people are asking me for daily updates i don't always have an update and i don't really have much of an update other than new york is getting hammered with like 12 inches of snow today so maybe i'll be indoors for a little bit um that's what i have but yeah for this problem um i'm not gonna lie i have some familiarity with it but i don't memorize it right because i don't remember when i even solved this but uh but i have solved this before because it is recognizable but i don't remember all the details because that's not the point of um you know i my approach is to get to a point where i don't have to remember particular solutions right i just have to remember how to do it or the techniques and you know like first principle like for ex like if you have a thing like a lot but if you have like if you have a physics problem um you're not going like i like to to start from like doing calculus and stuff like that where you know you uh get the formulas like for kinematics or something like that from first principles and instead of like just memorizing um all these formulas from physics and i don't know if y'all you know i don't know people have this experience where way back in the day maybe you know in high school they taught physics in a way such that it's like all these formulas and you just struggle to kind of remember the format how to apply it and so forth and then you take it in college with the one you know with calculus if you get that far and when calculus is just oh yeah it's just this formula then you integrate it and then you take the derivative and stuff like this is how you get all the formulas and stuff like that right like for me like the distance formulas are just like in the growth of the velocity is the integral of uh the acceleration right no the other way around sorry i know yeah velocity is equal to integral uh acceleration and you integrate that again and then you get the displacement right i know plus some plus or minus c or something like that right or plus c i guess where c could be negative but you get the idea right the idea is that building yourself strong enough so that you don't have to memorize the answer so that's a long-winded way of saying i don't long-winded way of saying i don't long-winded way of saying i don't remember how to solve this but that's okay because i know i can resolve it so yeah so i do remember there is an invariant and i don't know that there's an invariant but uh actually one thing that is cool is that i actually recently picked up a tablet i don't know if you could see this a tablet uh i'm gonna try to use this to kind of draw for an explanation hang on let me set this up i don't know if this is gonna be good so definitely leave me some feedback in the comments below and then yeah okay we'll see if this is actually this actually worked okay but okay so now let's say we have something like this right okay let's see if this works um still playing around the setup so this may be a little bit uh weird anyway but yeah okay so then the idea is that okay let's say you go from you know the way that i like to think about this problem is that let's say we are at you know we're going from left to right we have say we look at this and then how do we look at the past in a good way right in other words we're trying to figure out how to do an invariant and then the first thing i would think about is that let's see right so what does this mean for sex right so the largest rectangle is going to be the previous height times uh like the previous max height times some distance width right so then you can also go this but of course if you're limited by here then everything to the left of this is going to be at most this height so then now you end up with this kind of shape right where it is going to have uh where you try to figure out what is the max um max thing hmm how do you do that actually that's interesting because then the idea here is that wait let me double check that this is on the screen okay because that'll be a little bit embarrassing which has happened before um where these have variable rifts so these riffs don't really have to be directly next to each other like for example this could be one this could be say this could be another one but this could be two right and of course going forward that way maybe like you know because the next one is a two let's say we have this one which maps to this um then in this case going to the right of this will limit all this stuff so already we have an idea about how to build this thing but then the question is how do you do this in um how do you get the max of this in a good way right let me also double check really quickly on the constraints are 10 to the fifth for the h so that means that we have to do things in a sub quadratic way right meaning that n squared is going to be too slow also i should check that first because if that's possible that i'm drawing all this stuff for no reason and that uh that's a whoops but okay so i know how to maintain this thing but how do i get the current max height right because if we're at the six for example we don't want if we're at the sixth we're at this one this sixth height we don't wanna have to check you know let's check the what we would do is we checked the area of disk and an area of this and so forth um so we definitely want to avoid that how do i check that oh and also this thing i guess one way to think about it is i guess another observation is needed here and i think the observation that i need here is that there is an invariant about adding this last column right and what i mean by that is that hmm what i mean by that is that um is that true wow i mean i don't really have i have a what i was going to say is that you add a new column and let me actually change the colors a little bit so that's a little bit less confusing but um oops okay fine so let's say we have these okay let's say this is three because i didn't close the box this is slightly harder to use oops okay fine um well in this case this is always going to be bigger than something off of a shorter height but you know if we want to match these three right but then i guess at a certain point but this could be bigger than you know even in this weird thing uh maybe i don't remember the helicopter so you know bear with me and maybe this is a good time for the disclaimer that i usually solve this live so if it's a little bit slow for you and you're not happy with it uh fast forward watch it on 2x skip ahead maybe watch another video it's fine um but you could kind of see my thought process if you like so that's what i that's why i like to do it this way even though if maybe it's not quite direct to the solution say um but yeah let's say all these boxes have height and rift of one you can see that the nine boxes is bigger uh the nine green boxes and kind of eight yellow boxes um i mean the yellow because it's overlap with the green but hopefully you could kind of extend that downwards and see i mean i could use another color i suppose um so then the question is how do you decide when to use the bigger one right and then also in the future you know let's say in the future you add a shorter box then this thing doesn't apply anymore right like you would go hmm i feel like i'm missing one observation i was gonna say something about greedy about you know just always add four to the thing um and then three is whatever but okay i think i have an idea i think the reason why i'm struggling a little bit is that i try to resolve everything um okay yeah because i think the problem with what i was trying to do here is that i um at this particular instance let me use another color real quick uh at this particular instance i'm trying to resolve everything with this column to the left but that's not really necessary right we could actually delay that a little bit and what i mean by this is that we can resolve everything to the left um here but we don't have to resolve everything to the left of this and what i mean by that is that when we get to the very end let's say uh let's say um right here right at this box i'm playing around the drawing a little bit sorry friends it is kind of fun but yeah let's see if we have this box then we know that we no longer need the top of this chunk and then now we can process this green box because we know that this green box extends all the way up here right and we can draw different heights and stuff like that let me redraw it in a maybe better way i think i drew too much here on top of each other because i'm still trying to figure out the best way to use this thing um because this is my first go right um okay let me actually take the one from the examples real quick again but put it here okay so here what so we got the invariant enough to build something of a stack to kind of look backwards that way but then my idea is that okay let's say let's start by having a two right the two is obviously we just put it on the stack and then here at one we know that the height this height of two no longer matters right so oops so then now we have something like this right um and then now we go to the five we want to use four or five and then we also part we don't have to process the one yet because we know that the one uh the one rectangle goes to the right but we know that it can continue to go to the right here six we drew this and here again we don't have to actually because i think i was trying to process on push if you will but we can actually process on pop right and what i mean by this is that the six we'll draw another rectangle we and in a in variant kind of way we know that the one extends to the right and the five extends to the right and then now we look at the two what happened to the two right well here at the two and i'm gonna let me actually change to color real quick uh here at the two here let me draw the straight lines a little bit straighter yeah so let's say we have the two right then what does it mean well now we want to extend it to the left this way um and we know that the six and the five is no good um i mean we can process now we know how far six could go because we have the rift of the left side and we know that the right you know the left side is just the boundary between the six and the five um and then the right side of the six is obviously our current boundary because it cannot go right any longer so then now after two we now process the six and the five and we have this and then we see the one so then we know that the one keeps on extending to the right and then the two goes extend all the way here and then now here we have the three and again you know we just put you just wait and then at the very end we could process the three because we know that the three ends at well the very end and yeah and then the two we also process the two because we know that it ends here and then lastly we could process the one um and there and then of course when you process these numbers at the end you just choose the max of all these things because that means that for this height almost in a way you're trying to go as left as you can and as right as you can and as left as you can you just it's just the min right and of course um this is the visualization you can definitely figure out how to work that into uh you know what i know there's some fancy names around like model stack and stuff like that but these are what i would like to think about these uh what's it called monotonic uh data structures if you will i like to think about them not necessarily as a thing that you have to know or memorize but it's just if you know stack well enough you know cues well enough then these are just emerging properties right like you're not explicitly knowing that they're monotonic it's just that you build on it and it turns out that they're monotonic so i think that's the thing that would say okay i think now it's time to turn this thing off uh my drawing thing and now let's get to programming hopefully that was a good uh explanation though it took me a little while to get there because well look like i said i don't remember to do this by itself or like i don't remember to do this just to whatever i'm doing this from scratch uh or maybe not from scratch because i you know i've been doing this for a long time but i don't memorize the solutions for these things so anyway okay so now let's say you know let's have a stack and then now we have four i h in enumerate heights right so that just gives us the i index and h index and then now let's see how far can we go left before we see a smaller uh or a shorter like um i guess it's a bar i was gonna say rectangle right and this is basically what we said which is you know while length of stack is uh greater than zero and stack of negative one which means the last element uh we do want to store also the index so oh actually this is a good opportunity to use the um what's it called the walrus thing because i don't use walrus enough but yeah uh let's just say left index and left height i actually don't know if what's this because now it's a little bit i don't know if this is correct actually but n left height is shorter than h if it's equal then we don't pop it because we hm what do we do with zika i guess it really doesn't matter we just don't pop it right because if we don't pop it we'll just process it again but then it'll be overlap where we do pop it then we might miss a condition i don't want to add an extra condition so let's pretend this is good syntax because i'm actually not quite sure about how well is up because it's not it's a relatively new for me anyway operation so yeah so while this is the case we just pop yeah but before we pop we want to process that as a thing right so let's say we have the best with or best area so best is equal to the max of the best because we're trying to get the largest and then here the rift is just equal to i minus left index is it plus one right because it includes the current thing um and then this times the oh actually i'm wrong here sorry this should be greater than because we keep on popping stuff that's greater than right because um like we drew before if it's greater than then you kind of cut into it right so yeah so this is that times the left height okay so i think that's the general idea um yeah i'm going to click on one code real quick just for a syntax check because i know that this should not be an infinite loop so yeah so di invited syntax oh yeah i did forget parents thanks okay i mean we expect this wrong answer but i just want to know that the syntax is correct i know this looks a little bit yucky because generally you do this and it returns uh the left assignment so then you could directly compare but i guess that's a true assignment which is i don't know if that's quite the right syntax or like the optimal syntax i mean it's good enough but anyway so we're all learning here um okay so then now at wait and we can push uh or append in this case we push the to the stack the current eye and height and that's pretty much it um and then of course at ray n we do this thing um and let's just say oops right is equal to um length of heights i might be off by one here i think this should be okay though maybe we'll be a little bit careful so we'll do the same thing here i think this is correct except for that's not so we don't add a plus one here because it's just a boundary um i could be wrong so let's play around that oh this is also this is wrong though this should be negative one um so before i do this let me run it again just to make sure this doesn't mix basically just let's just get the max uh left um gets to um so okay so as you can see i messed up on the syntax and it's coming back a little bit um maybe i don't know the walrus syntax then left index not defined did i mistype it um did i miss up to wallace operator maybe i did i am very new to the walrus operator to be honest so give me a second yeah i guess so but maybe the rawest um for tuppers doesn't really work maybe i don't know let's see let me google uh hang on uh python forwards operator tuple uh rose operator does not allow unpacking assignments okay i mean i wasn't sure that i can do this to be honest so this uh this is fine we'll just have to rewrite it a little bit um so while the stack is going to do i mean this is fine right else we break that's pretty much it not a big deal uh yeah let me run it real quick just to make sure i have the syntax correct this time okay good we can even return best it's just that we won't um in this case i think we get the right answer because the 203 doesn't matter uh maybe not okay maybe i'm also still off by one though so we should check that because okay i was like i don't need this is that true okay i mean yeah but we still have to do uh we have to process the rest of the stack as we talked so yeah i guess we don't need enough height i don't know that we're not off by one i might have to think about this a little bit okay so this is good and this is basically all uh all the things that we talked about um not super confident about this only in the sense that i worry a little bit off by one the idea is mostly right that's fine i'm just worried a little bit about off by ones and why this is not why do i not have a plus one here if the left index is for example for five let's say we have let's say five is zero six is one minus zero right so why should that not be oh okay no i'm wrong on this that's why um because we process this knot at the six again i made the same mistake that i did when i was doing the drawing i processed this knot at the sex well no so i think i had the wrong mental visualization so yeah this is there's only a price not between the five and the six this is a price um between the six and the two um i keep on messing myself up and when you process the six and the two will mean that um two will mean that you're processing the six and the five together um and yeah and of course in that case the five has a rift of two and of course the index will be two a point okay i think now i'm convinced and happy about that might have some silly hours anyway but um but still okay let's try let's see what happens if we have like i'm just plugging in random numbers i think the one that i did want to try was um what if you have a zero especially at the end or something say i think it should be okay but i don't think that i handled it a little bit differently okay but i am wrong though so um so 120 shrinks it to so 120 we get 125 is the answer and that's good but then when we have a zero why does the zero not process to 120 left height is greater than zero right hmm that's weird i mean i'm glad i caught this but yeah let me and just for visualization i could try the same number but without a zero in the end and this is just a little bit lucky and that um i didn't really intend this to be the case okay so i am consistent about it so that means there's something wrong here as well that's weird actually when i get to the 125 answer so then what three 125 for 120 okay right before we pop five minus four okay i see i'm this calculation is wrong because it is calculating um this is calculating where it begins but sorry where we so this i is wrong because we want basically we want to we're not tracking the left item we're tracking the almost the right side of the left item right so this is always going to be mostly um one or something or maybe not but it's very wrong uh is what i'm saying because there is a where we're just not tracking the right thing what we want is actually um what do we want so that when we pop we keep track of the leftmost thing so let's do that leftmost is equal to zero i don't know if this should be zero or negative one but um but every time we pop we do the leftmost is equal to oh wait left motion not be it should be i whoops and then now we want to move it to the left which means i guess technically it's a min but actually uh we do it here and i think that should be better yeah maybe i mean i know that i didn't fix it for here do i need to fix it here no because once i put it in correctly i don't need to fix it there okay so as you can see i will still make mistakes so that's a good thing i mean in that you know um it's a good visualization on how i debug and try to visualize it and kind of um suss out what you think is the most suspicious and for me just working through an input you can see that i go okay where do i get 1 125 from where do i and how come i didn't get 1 20 times 2 and then i realized that i was getting 120 times 1 that allowed me to kind of look at why this is wrong and then i realized that the left index didn't actually contain what the left index is it just contain the index when you insert that bar and not extending it to the left like we're visualizing the drawings right so that is basically um yeah okay let's say now i'm confident or i wouldn't say confident but more confident let's give it a submit and hopefully i didn't miss any silly case okay cool much slower than a year ago but i feel like they've been just adding a lot of test cases so i don't know maybe i'm wrong though 669 streak and yeah oh i think over the complexity but as you can see this is just a for loop and you know you could see that there's a for loop and a while loop the way that you know this is not n square and the reason why that is because for every item in the stack it corresponds to one item in the input and of course each item can only be pushed and popped once because so that each item can only be pushed to pop one so only two operations at most or whatever you want to say not operation but um so therefore this is going to be linear time in total in terms of space same thing we push only with the items on the stack once at most so that's going to be linear space so linear time linear space and that's pretty much all i have for this one let me know what you think i mean i think this is just a area formula about i didn't have to explain it though i didn't so yeah um all right well weekend is here stay good stay healthy to good mental health i'll see you later bye
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
1,063 |
hey everybody this is Larry this is me doing week four of the legal premium weekly challenge uh hit the like button hit the Subscribe and join me on Discord let me know what you think about today's form 1063 number of valid Subways we haven't solved this one yet yay I don't know maybe not that excited but uh okay so give it an industry away nums returned a number of non-em empty returned a number of non-em empty returned a number of non-em empty subways with the leftmost element of the subway not larger than other elements in the subway way okay so what does that mean that means that the left element is going to be the smallest but after that it's fine so guys I mean this is a should be pretty okay it's just really um more really specific foreign versions of this problem have been asked already uh on contests maybe not recently but yeah but the idea is I mean this is a good starter problem to those kind of problems because it kind of um pushes you to kind of at least think about it one specific way which is that you have to think about the leftmost element or maybe another way to think about it is just one element at a time um here we can I mean you know this is a valid separate way so they're really only two directions and you can go uh if you don't want to do N squared and I did I forgot to look at the constraints but I assume that because it's hard you cannot do n square right and what is so after that the only two directions go which is from left to right or right to left um and in this case it makes more sense to go right to left um because then now we can build up um bill of something uh yeah I mean it allows me to at least build off things that we're looking at right meaning because the leftmost and then you when you look at an element and it is the level most element obviously looking at the right so assuming that we built some kind of thing on the right then we can now um yeah now take advantage of that by doing something incremental which allow us to do it in better than end square right okay so let's talk about it real quick I mean let's so I mean the idea here is that if every element um it wants to be the smallest element right and so what does that mean that means that another way to say it is that you want to find the element to the right which is uh smaller than this right is it distinct nope yeah so uh in this case then has to be an element that is strictly smaller than this current element and of course we have a data structure to do that if you kind of practice I'm always really bad at memorizing though it's one of those like uh what's it called uh um I don't know Max Cube uh what was it called monotonically oh yeah monocle right mono Cube or mono stack one of those I never remember those things so I always have to do it from scratch which is but at least like yeah I know I'm able to get it maybe eventually right and here um the other thing that I haven't really brought up yet is that when you see the next number that's smaller then you know the length or the number of sub arrays because sub array is contiguous that means that you know you just choose you just count the number of Freedom uh the number of what's it called choice of Freedom or degree of Freedom that we can right uh for example in this four you can you cannot go past two so you have zero degree of Freedom so you only have one choice uh in this two well you have all the freedom so you can go one just two you could go to the five you could do the three dot right so you basically see how far you can go um okay so basically now let's build something out right so um the way that I think about this is that and it's probably monostack just from to be honest me solving enough of these but maybe I'm wrong but the invariant here we're trying to do is that as we kind of put this in some sort of data structure and let's say we have the status structure um we want to get two things right one is uh we move possibly we moved choices that are not possible Right what does that mean that means that let's say um you know let's say I'm at some number X right doesn't really matter what it is but let's say we have some uh previously seen sequence uh what would be a good one um uh let's say five and then four right oh no the other way around four and five right uh when we process the four what does that mean uh or we want to process or we want to set up the processing for four so that future things can know that four is the um the smallest number right well not the smallest number but a number that is smaller than x yeah so that in Philly going so you basically processing it in a way such that in the future you can look back and see you know uh like for example here my question for X is going to be like hey what is the closest number smaller than x right and the thing that I want to uh stress on these kind of things is that you want to eliminate answers so that you don't kind of do work that is impossible and what I mean by that so what I mean by that is that if a number that say I mean we can do it excessively maybe I'll start that first uh exercise and just make a little bit more space uh let's do this excessively to kind of begin with right let's say the number is three what is the next number that's smaller than three well it doesn't exist right uh okay fine easy to do you know um so then now we just kind of do you know whatever but let's take down to six right what's the next smallest number obviously it's four right also obviously to see but let's say the number is 10 right what does that mean what's the next smallest number well then just four well why do I count and there are obviously only three distinct possibilities not including uh you know numbers that are the same or whatever but you know we'll just hand wave that for now you can kind of go through it but the thing I want to point out is that we what happens to the four and the Seven right well seven is never the answer and why is it never the answer because any number that's bigger than four that we see in the future I know we're going from right to left so future is a little bit awkward but any numbers that's bigger than four we see in the future will have four as this answer and it will never have seven at the answer right for obvious reasons or you know for you know reasons that you can kind of think through a little bit because any number that's bigger than four uh it doesn't matter that's all you need to know that it stops there right it doesn't it's a separate way it doesn't extend any further back so you never need to look for at seven so that's basically the idea um and the reason uh this is so powerful is that um because this seven you only push it and once you remove it you can remove it only once as well so we're only going to do linear time and that's basically where the amortization comes from so that's basically the core idea and what I said to you right now is basically how I kind of proof things right I don't really actually like memorize mono queue like uh this is mono stack so I don't memorize mono stack-ins or I don't memorize mono stack-ins or I don't memorize mono stack-ins or anything like this not specifically it's all about the invariant about the loops and stuff like this and the other question may be why is it called Mono stack well it turns out because uh for every number you want to remove all the numbers afterwards that are bigger than it so then as a result of that a property of the stack is that it's gonna be modeled tonically decreasing hence mono stack right um but that's with it or as I always say for these kind of problems this is uh an emerging property and not um not something to kind of be like memorize even I like before kind of going through it I actually have no idea whether it was going to be monotonically increasing or decreasing because I just I don't know like maybe someone could memorize it or they do it enough times or whatever but for me like uh I just think about what is the question and then how to solve it right and then kind of everything kind of falls apart or Force together um and it doesn't really matter that it's monotonic or that it is decreasing in this particular case uh yeah and then now that we have the idea we can kind of go straight to it right so yeah for um and I'm a little bit lazy so I'm just gonna uh reverse this uh you don't have to do it this way of course uh it just allows me to go from left to right uh and it has a nice property that you'll see in a second as well um but you know but keeping in mind that this is of course obviously linear time I also count down as linear's face because technically you would probably make a copy before reversing it because that's just bad practice too uh make it that ident uh or like you know using memory that they take care of but uh but this is just for as a trick for the indexing so you actually don't even need this I'm just lazy um and you know of course let's just use a wearable to keep track of the total right okay you have to fight something more than that Larry and then we have a stack and then now uh yeah while length of Stack is greater than zero and there's other stuff but we'll just skip it for now for because the first item it doesn't matter um and then we append in X right and then what happened what do we pop here we pop if the current number is smaller than the previous number we want to pop because this will always be the answer and not the next one right okay right uh I always get this one I don't know why it always typed like this but I always get it well maybe I think about man okay uh so well this number is bigger than um I had to think about the even uh the equal case that's why I'm hesitating a little bit but if I think for now this is fine but let's see what happens when you have a year code case um no you just replace it I guess it is way awkward though so yeah so if it's equal uh then we also want to pop because that means that we're able to go past this I think that's the correct interpretation uh and then we just returned Toto but of course we have to do the math first um basically now it is stopping at the last element right and actually I kind of messed up here or the couple of ways to handle this case um I think the thing is that stack could be zero or the length of Stack could be zero but you can actually handle this slightly better and what I mean by that is just have a um a sentinel and a thing which is like negative one and then uh negative Infinity say right negative Infinity because then this will never be true for the last element so uh so yeah and then now we before putting it on we can basically look at the difference in the indexes so if this is zero and this is one that means that this has technically uh zero degree of freedom but one supper way right so we can do something like um I minus uh the last elements uh zero because the top of the stack is going to be uh the top of the stack is the next element that is smaller than this one right so yeah uh all right so this looks Gucci for these three cases are there really more cases I don't know I guess like one three four five I mean there's just like more variations of this so I don't even know if I don't know something like that I'd say right uh I don't know if there's like an answer limitation but I guess separate ways can only be N squared so uh or n choose two you want to be more precise it looks good let's give a submit today not quick let's give it a submit and yeah uh what we have here what do we have here this is linear time linear space um uh did I say I couldn't cast to say I totally live I forgot about the stack somehow but yeah because if the stack this is going to be linear space No Way Around It I think one of the inputs would be linear anyway uh yeah a linear time obvious also obvious uh this part is linear the while loop is a little bit awkward to look but you can think about it as each item gets only pushed and popped once off the of the stack uh so that's gonna be linear type and this only looks at like n right so yeah um that's pretty much it this is a hopefully uh a good intro to monostack or whatever uh like I said I don't like thinking about these things with respect to Mono stacks for that reason or monoq or whatever because you can having the product is just about um you know figure out uh which one you need and you can figure out which one you need by figuring out what question you need to ask a data structure right and that's basically it uh cool that's all I have for this one let me know what you think have a great week and well week and weekend stay good stay healthy to get Mental Health I'll see y'all later and take care bye
|
Number of Valid Subarrays
|
best-sightseeing-pair
|
Given an integer array `nums`, return _the number of non-empty **subarrays** with the leftmost element of the subarray not larger than other elements in the subarray_.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,4,2,5,3\]
**Output:** 11
**Explanation:** There are 11 valid subarrays: \[1\],\[4\],\[2\],\[5\],\[3\],\[1,4\],\[2,5\],\[1,4,2\],\[2,5,3\],\[1,4,2,5\],\[1,4,2,5,3\].
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** 3
**Explanation:** The 3 valid subarrays are: \[3\],\[2\],\[1\].
**Example 3:**
**Input:** nums = \[2,2,2\]
**Output:** 6
**Explanation:** There are 6 valid subarrays: \[2\],\[2\],\[2\],\[2,2\],\[2,2\],\[2,2,2\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 105`
|
Can you tell the best sightseeing spot in one pass (ie. as you iterate over the input?) What should we store or keep track of as we iterate to do this?
|
Array,Dynamic Programming
|
Medium
| null |
1,956 |
hey everybody this is Larry this is me doing an extra prom for today I feel like I haven't done this in a while but I do have premium for I don't know how much longer so we'll see uh you know I'm gonna try to do a random premium that I haven't done yet yeah and then we'll see how far I get yeah that's let's do it wow and after that we're doing a hard one so let's see uh today's Premium plan is 1956 minimum time for K virus variants to spread hopefully this isn't too impossible because there seems to be a few of those okay there are any unique virus variants and an infinite 2D grid you have an X Y okay X survive I survive on Day Zero but notice that it's possible multiple virus variants to originate at the same point each day a good looked at all four um okay and then return the minimum integer number of days for any point to contain at least K of the unique variants oh okay that sounds hard uh on day three okay so I mean I think the short answer is gonna be oh hmm I'm not gonna lie I really thought it was going to be binary search and they look at the constraints I'm having second dots um well this is really a heart I'm not gonna yeah I thought there's gonna be some tricky binary search and then we have to figure out how to yeah I mean I don't think it's even that hard of a binary search that's why I'm a little bit confused to be honest uh but maybe I'm missing some new ones because you can get the okay yeah maybe it's still binary search maybe I'm a little bit confused uh but at most this is gonna be almost 200 days and then we do a binary search is just a hundred thousand or a hundred times 100 which is ten thousand and ten thousand um you know you can do that easily ten thousand possible points because it's not gonna be outside the Min or the max of those things even though they say it's Infinity uh infinity to the grid as long as it's within 10 I mean but that's all your bounding box so you know we do a Min and your max then that should be okay and you have at most 50 points I don't know if I confused the 50 the N for 50 and 100. but uh I could see that you could you know if you're sloppy then you know yeah I don't get it maybe I'm just a little bit like wondering if I'm missing some um wondering if I'm missing something to be honest but here you can actually uh because it feels a little bit too easy for me or not even hopefully I'm not yeah coming off as uh sounding like I'm bragging but sometimes I just I guess I just expect it like reading the poem I there is a harder problem in here and then they just kind of chose like a easier one if you will so I don't know but anyway all right let's get to it then and yeah let's get to it and then we'll just do a bounding box because we're lazy um how do I write this I mean X Max X um so for p x y and points uh X right so then we can do this a lot of copy and pasting for now hopefully I don't make a mistake because that's what happened last time or the other day okay right all right so then now that's a little bit confused to be frank uh let's just do it I mean because in theory you should be like if you do a first search it's fine as well thank you Maybe not maybe that's just a real way of phrasing it but yeah um am I trying to get again okay K is the thing okay so how do I write this um so for this point so basically for x and uh range of Min X to Max x one right and then now if this point is a possible answer how long does it take well um yeah you just kind of do all of them and then it's like a heap thing right just top K right I'm going to change this to Big K because I feel like I sometimes we use variable names silly uh yeah I mean I think that's it right and there's only 50 elements I don't I feel like using a heap may even be too much of an Overkill but I'm just gonna use sorting just because I'm a little bit lazy but I mean we can optimize this is easy to optimize so yeah um the best is equal to I just say um end time it doesn't really matter n times three should be Infinity because that's just you can do a proof to show that should be sufficient for any number but uh yeah um for then I can write this uh and then uh distance is your pen dude this is just Manhattan distance and then now we sort I've been using too many languages there uh okay so that means that uh for k is it K minus one is the distance of the yeah I think K minus one should be good so yeah so best is equal to men best uh D of K minus one and then we just did invest and that's pretty much it I mean maybe it's two-star maybe I get I mean maybe it's two-star maybe I get I mean maybe it's two-star maybe I get confused okay fine um I should make it happen anyway it's probably a healthier habit every times hour times out but um though it shouldn't be and we can even I'm too lazy to do to write it out I guess the points are not distinct necessarily but we can actually just do something like um points is equal to I mean we're just doing we don't really care about running time so we can actually do something like um I don't know XX for X in range of like a hundred or something that should be fine I guess it has to be between one and a hundred and not zero and 99 that's fine so what we're looking for is just a running time it takes 7 28 seconds or milliseconds to want four cases so we should be okay what do we return anyway expected three so I returned one yeah I guess that sounds about right where am I off by one I have to make sure I guess see if I'm off by one I guess I can just run the actual frame so we look good here let's give it a submit maybe too slow but we'll see oh did I misunderstand us huh maybe I misunderstood this problem hmm um do I have a typo both are possible uh why this isn't the thing is that doesn't even feel like it's off by one it was off by so much but um hmm yeah it's gonna print out a lot of stuff but it's the extra ID K is 2 minus one so here okay and I put down six why did I have six um if D of K minus one is you go to six Maybe wait I get six from oh I put and okay it's from Dad okay that's just me being dumb I actually uh I didn't mean n as an n i uh this is so dumb uh okay I mean and as in like the size of the grid for some reason I think in my head I think of this as an N by n grid so whenever n times three that's what it that means okay fine let's just do Infinity I'm too lazy to think that was me trying to be clever and instead got uh got fooled by myself right I mean it's a little bit slower than whatever um you probably could optimize this by changing this to a heap in Python it's not always a given to be honest that's why you have to do um you know because sorting is very optimized because there's a very common operation um if you use Heap you have to do you know for Loops in pi code and stuff like this and that actually may be slower I wouldn't be surprised if that's the case um I did have a silly mistake here yeah well I think in my head when I write n for because I think of this as a good problem in my right and I think of like the N by n and a greater something like this um but then I got confused because that makes no sense otherwise n times three uh because I what I was going to say is like you know the grid times three so you could actually just write like 300 and it'll probably be fine Infinity minus one has to be 300 because or whatever but uh that's what you get for trying to be a little bit too clever I suppose um and then didn't think about it afterwards so I think I just confused the wearable names for this particular one uh anyway that's all I have for this one let me know what you think uh yeah this is a little bit odd because the thing that we um we abuse if you will is the fact that the bounding box is not that big um so it's hard to kind of go over the complexity because there's just so many well I mean it's not that hard but it's just like a very specific thing like if you want to say uh uppercase X is the range of X and Y is the range of y's um then you have like x times y times uh n again for the Sorting um you know this is of N and this is n again so you have like x times y times n log n which for this problem is fast enough but you know it's not that optimal um I think you can probably do some sort of binary search I wonder I mean there probably is a lot more harder math with respect to like you know uh in a way this is like median finding type thing but only if you get the entire number and if K given K is not always a given so I don't know that I can do a hard over I mean I'm not saying that the harder version is not possible it's just I don't know if I can do it um I mean you can definitely think I mean because the way to think about that particular thing is just um I wanna I want to say that it reminds me of the renoy diagram in uh d0 or Manhattan distance but I don't know that's good because in this particular case you want I don't think that necessary like or like you know there are a lot of uh quote unquote off-the-shelf standard-ish quote unquote off-the-shelf standard-ish quote unquote off-the-shelf standard-ish as in textbookish computational Geometry that would kind of help you figure these out but to be honest I don't know that you know uh that I mean you can definitely do stuff in N Square uh or maybe not N squared but N squared as a base um because so if you and given that n is equal to 50 you can do something like N squared log N squared so I think maybe that's fine maybe they're raised around that um to kind of like sort the biplane something like this I mean I don't know maybe we're getting too hypothetical here and I don't know like if I were to need to code this I don't know if I know how to code this but you can imagine like um you could I mean this is an nd0 as well versus like uh is it yeah Manhattan distance versus like conquo regular pointer distance um but I imagine there's an analog and I could be very wrong in that particular problem you could take the graph and then you could take the Dual of all the pair of points which means almost like the uh well the lines that bisect the two points and then it's just in the section along those points and then you have n square number of lines and then to kind of find um I don't know yeah there's some like sorting and then maybe you can do some craziness I don't know I don't really have anything about here let's see if the solution does any better uh yeah I guess you can find out you could sweep line that's the thing that maybe no binary search well I mean if you saw it this is basically my code but uh I mean technically true not binary search um I did originally did think it was going to binary search and then just kind of um yeah I mean I don't know if I would call it sweep line but I think of it as like a frontier thing of just you know um how many intersections because another way to think about it right is that um you know and the way that I think about it is you know with visualization and the way that is initially visualize this would be with um you know with regular Quantic regular distance uh which means you know x squared plus y squared is equal to uh d square um and in that case you can imagine just having circles right then now you try to figure out um any regions with K you know given these circles um you could like for a given if you're binary searching then you'll just find like your binary searching on the radius which is the same as the time in a different distance metric um and then now you're trying to find out uh for a particular graph whether there's a region with um with k or more uh thing and then you binary search on that pretty all right to be honest not impossible but pretty tricky so I don't know uh but yeah anyway some things to think about if in case you're curious in case you're thinking about this stuff uh that's all I have for today that's what I have for this Farm uh let me know what you think stay good stay healthy take good mental health I'll see y'all later take care bye
|
Minimum Time For K Virus Variants to Spread
|
maximum-element-after-decreasing-and-rearranging
|
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n`
|
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
|
Array,Greedy,Sorting
|
Medium
| null |
939 |
hey guys how's it going John here today we're going to be solving another legal problem and this problem is called binary search tree range I decided to choose this problem because in my last legal problem I made a mistake where I wrote BST for a function name when it's supposed to be just like a binary tree I believe but I you know it got me thinking about binary search trees and I thought it was a good time to start introducing this topic binary search tree is actually one of the most interesting data structures it's mainly because it's a really good one to study on because it introduces the concept of hey what kind of data structure can I create in order for me to solve a specific purpose and a binary search tree them you know it's right in the name itself the binary search portion of this tree it's really clear what is trying to do basically if just by reading the name of the binary search tree you could immediately think that hey there's probably two choices like binary write 0 or 1 like 2 choices and it's geared in this data structure is geared for search because you know it's right there in the name and also finally it's a tree structure anyways I decided to cut this particular video in two sections the first section will be me just explaining what a binary search tree is and kind of like the properties that are involved it's not going to be an inclusive like the like a tutorial on the binary search tree but it will be just the minimum information that you need in order to solve this particular legal problem and then the second half will obviously be me solving the problems so I'll annotate like the different sections of the video below so check out the descriptions but yeah let's dive into this video so part 1 of this video let's quickly talk about what a binary search tree is to be very specific a binary search tree is a node-based tree structure that is node-based tree structure that is node-based tree structure that is optimized for search and it accomplishes this feature by optimizing the child nodes in a very specific way in an organized way so here are the properties of a binary search tree 1 the left subtree no only contains values that is less than the parent note to the right sub-tree the parent note to the right sub-tree the parent note to the right sub-tree node only contains values that are greater than the parent note 3 both of the left and right note sub trees has to be binary search trees these are essentially it for a binary search tree so using these three properties you could actually do a lot of incredible things for example finding a specific node is very easy in a binary search tree because you have these specific rules for example you can start at the parent node and then say hey is my node greater or less mahler than the node that I'm currently at my target note if it's greater they go to the right and then you ask the same question and then you could say oh if it's greater then go to the right you know and then or go to the left if it's smaller and eventually you'll find the target and you're guaranteed this behavior because your nodes are organized in a very specific way so you're always guaranteed to find the value well as long as you properly traverse the tree now in terms of traversal traversing a tree is one of the most fundamental things you need to know in working with the tree you can't really do anything without knowing how to traverse the tree now there's many ways to traverse a tree one is using recursion and there's also a iterative approach to traversing trees but the most important thing to know the difference between is def first search versus breadth-first search just to very versus breadth-first search just to very versus breadth-first search just to very briefly talk about it breadth-first search means that you will breadth-first search means that you will breadth-first search means that you will be looking at all them so you'll look at the notes all the notes that are closest to your parent node first and then you'll go down to the next level depth-first search means that you're depth-first search means that you're depth-first search means that you're going to go take one note and go all the way down to its child nodes and then go back up and then vice versa and you'll do this depth-first easy way now you'll do this depth-first easy way now you'll do this depth-first easy way now there's different ways to implement that first search versus breadth-first search versus breadth-first search versus breadth-first search I'll go to that in another video but one tip I could give you guys is that I use this mnemonic tool I kind of memorize like what I need to do but for if you want to do a breadth-first search if you want to do a breadth-first search if you want to do a breadth-first search then you have to use a queue and that's another data structure but i think of it like BB q like barbecue so breadth first search is it starts with the letter B so BB q you need to use the Q and then obviously the other one you need to use a stack or something else anyways finally the last thing that you'll know you'll need to know here is like actually traversing it there's many different ways to traverse a tree like in terms of the order of the nose that you see first so there's like in order posts order and pre-order so there's posts order and pre-order so there's posts order and pre-order so there's different ways like base it just means like which nose do you see first when you're traversing the entire tree but yeah so these are just like large subject matters that you need to kind of know and yeah I hope this was good enough explanation and when I start talking about it and when I'm actually solving it you'll be able to relate and I'll link videos below because I haven't done these videos yet so I'll link videos below on these different topics but yeah so let's get to the solving of the problem right now let's take a look at this problem let's read it real quick given the root of the node of the binary search tree return the sum of the values of all nodes with valley between l and r it stands for left and right anyways here's another important part the binary search tree is guaranteed to have unique values this is kind of important for this particular problem okay so how will we solve this problem let's like take a step back and let's not think about this as a binary search tree like what is this exactly so let's take a look at like these numbers um for example let's not worry about this like null because this is really specific no less specific the binary search tree is to describe a leaf node that is null um but let's take a look at this and then let's say okay so if we have a value that is left value that is 7 so this is a left range and then the write that is 15 so all we're really doing here is looking at these set of numbers and asking yourself hey what values are you know larger than what values that are in between here and what's some of that so in this case the value would be 1015 skipping the five skipping the three skipped adding a seven because it's inclusive mind you and skipping the 18 right because 18 is out of the range of the right so that turns what that's like 32 yeah 32 so and if you look at this output example it's 32 no stop cars that's essentially all we're doing we're just looking at a bunch of numbers and we're asking yourself hey okay I think it worked let's go ahead and start working on this problem so the first thing I like to do for any legal problem is to think of the base case think of like think of a case where this we don't even have to like execute this problem and that's obviously when the root is null then we could just return no I guess the next thing that we need to do here is so to solve this problem the hardest part of this problem is how do you traverse a binary search tree how do you look at every single node and then determine whether or not to you know include this in our summation so in this particular problem what we're going to do is add F first search essentially just is essentially just iterating every single item in a def first search pattern and we'll probably use it in order in this particular matter the in order post order or pre order like person doesn't really matter because in the end you're just gonna be looking at the point of the problem is to look at every single item and then only add the items that is within the range let's first solve the portion where we're just iterating over the tree just going through it every single node in the tree so to do that we're gonna create a function called F first depth-first function called F first depth-first function called F first depth-first search and we do DFT for short and then here sorry I'm typing on top of the cardboard box because I don't have the space or anything right now so it might be a little shaky I'm sorry about that so if so here we're gonna write a base case if node and return null and then here we're gonna do a recursive search on the left and then the right node left and the first snot T search the first search and this one we know that right okay so just by doing this we're implemented a function that given when you're executed with the root node it will go through every single node just by this and this is a recursive call obviously I'm just calling itself and then right here is saying hey if I don't see any more if I hit a leaf node return so we don't really actually have to do anything with the return value here and I'll explain that soon but let's go ahead and invoke this the first search which is and we're gonna pass the root node now here's support so just by doing this we have created a function that executes an inner function called F first search that iterates through every single item in the node now this is all if you think about that like array example that I show it's almost like saying hey just go through the entire array and then what's the next part we need to do the next part is just to create like a variable called results for example the results rizal equals zero to start off and then every time we see a value that is within the range added to the results so let's go ahead and do that so if we do it right inside here this is considered in order I think if we do this above the left and right I think that's pre and then if you do it below the right that's post but let's just do it doesn't really matter like I said in this particular the order of how you see it doesn't really matter in this particular problem but let's just do it in order so here if we say if the well of my computer is like okay so if the node thought my computer is really hot no the value is less than L well it's inclusive right so less than or equal to L all right sorry greater than equal to L and note that value is less than or equal to right okay my computer is lagging because it's super hot and I'm running like multiple things but anyways all we're doing is using this function signature of a tree node right here value we're saying hey is L and it is the node that we're currently looking at less than the mean greater than the L value and then less than or equal to the right value if so then we're just going to append you know continue adding to the results plus equal G's no value okay and then now our this is essentially we're getting this results and we're adding it every time we see a value that is inside our range at the very end we just have to return the results man it's like typing in is just like comes in I probably just have to read move it move my MacBook from the Sun all right let's go ahead and run this code hopefully I wrote everything correctly I'm gonna do a scan after this but okay so looks like that worked submitted and there you go yes it's been successfully accepted so man this is like the hardest conditions to record this video but that's essentially it this is essentially the problem there's other ways to solve this problem and the other ways essentially is like because there's many ways to traverse a tree so breadth-first search you could do all of breadth-first search you could do all of breadth-first search you could do all of this problem like it's early and yeah but there's a lot of ways to do this you could convert this whole thing into an array I mean there's a lot of things you can do but that's essentially the problem but yeah I hope you guys learned something new and I you know with all these problems I hope you guys take like what's really important it's not you know solving LICO problems of in itself it's not really that important you know like yeah it's good for practicing and all that stuff but you know the real reason why you solve these like LICO problem is because there's a lot of like hidden learnings from the problems for example in this problem we learned about traversing a tree now traversing a tree is like an extremely useful skill in engineering like you need to know how to traverse the trees all the time you know like if you're working with objects for example an object in itself is just a tree structure with the root being the object right and every single key value pair are just notes for example so you know all of these like concepts are very useful and like desperate search versus like breadth-first search like versus like breadth-first search like versus like breadth-first search like breasts first search is used in almost every map kind of map related problem where you're trying to find like the fastest route from point 1 to point B like you usually want to use a breadth-first search because there's no breadth-first search because there's no breadth-first search because there's no you know you essentially you want to like find you wanna like take on layers out of time rather than going 1 Bret OneNote all the way to its child instead you just want to look at all the knows and then you keep like increasing your radius until you the other point that you want so that's kind of like the point of like this problem in a nutshell that the reason why you study data structures in the algorithm is because it allows you to solve really interesting problems efficiently and at scale so but yeah I hope you guys enjoyed this particular lesson it was a quick one I hope and I keep saying that I want to do all these like other videos and give like certain like data structures to time it really deserves and you know I have I'm working on that so as soon as I get those videos out you know in my busy schedule and all I'll let you guys know but yeah thanks for supporting the channel for all the new subscribers and yeah I'll see you guys next time
|
Minimum Area Rectangle
|
valid-permutations-for-di-sequence
|
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
**Example 1:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**.
| null |
Dynamic Programming
|
Hard
| null |
1,266 |
in this problem you are given a few points in a 2d space and the points have some order so they will be given in some order like this point is first this is second this is third and your task is to find the minimum or distance minimum time you will take to visit all these points in order that is first this point you will start from this and there are some constraints on how you can or travel in this 2d plane so let's see so you can either travel so if you are at point x y this is x y i am writing it here this point so you can take one step to the right and every step will count as one time unit so these are the steps that are allowed so either you can come here so let me draw a square around this square of side 2 so either you can come to this which is x plus 1 and y this axis denotes y or the second coordinate this is the first coordinate or x so these points first one will be along the horizontal axis and the second one along vertical axis so what is this point this is x plus 1 y is unchanged here x is unchanged x y plus 1 and this is mirror of this x minus 1 y here it's x y minus 1 so these are four directions then you have these diagonals also so this is also just one unit 1 time 1 distance and what is this is x plus 1 y plus 1 this is x minus 1 y plus 1. this is x minus 1 y minus 1 and what is this is x plus 1 and y minus 1 so what's common among all of these distances so if you see this point here x component has changed by 1 y has not changed by anything so the difference was 1 0 here the difference is 1 then here the difference is 0 1 similarly here it's minus 1 0 and one more it's zero minus one so these are the point uh positions where one of the coordinates changes by one and let's write the other points which is diagonal points one this one is minus 1 and this one is plus 1 minus 1 so what is common among all the 8 points uh if you just see at the magnitude forget the sign or direction negative sign forget so either x changes by one or y changes by one i am writing the absolute value it can be plus minus 1 or both x y change by so maximum difference between these components is one but there will be at least one difference so you have to find how you will cover all of these so uh you have to start from one so this is time unit 0 you cannot take straight go to here since it's 3 and this is 4 so if you are at 1 if you go diagonally you will go to 2 then 3 so you will reach here then you will take up so this is the minimum possible so you have wasted first second first you start second you reached now you have to go to 3. and this is 3 4 and this is minus 1 0 so you see that what is the difference between 1 and 2 so it was 1 so 2 minus 1 what will be the value this will denote dx dy that is difference required to reach from 1 to 2. so here x has to be changed by 2. in x direction we will take 2 steps and in y direction we will take 4 minus 1 3 steps so you have to take 3 steps to reach here you can take more also first go along x then go along y so you can take two plus three five also but you see that you can reach in three steps only why take what's make one of these 0 so that will be 2 plus 0 1 so this is 2 so you can go one in any direction in one unit so this will take two units of time and here you will just take this remaining thing whatever is remaining so 2 plus 1 3 and that you can also see from the maximum value of x or y component one of these components absolute maximum value even if it's two minus three that is you need to go two steps to the right and three steps to the bottom that means here one two three so instead of taking this what you will do you will take one two and three so whatever is the maximum absolute value of the component that will be the minimum time required to reach to that point so here it was 2 3 so we take three steps so let's draw the points here how we will reach here it's 3 4 if we go diagonally we will reach 2 3 that is here then one step further both will reduce by 1 so this is 2 3 we will come to 1 2 that is here and then zero one which is here and then finally we will reach this minus one zero so how many units we have traveled one two three 4 5 6 7 so the answer for this will be 7 so this is the minimum time required to visit all these points in order so the approach here is again you will see what is the difference between these two so subtract one of these from other so 3 minus 1 is 4 and 4 minus 0 is 4 so we have to travel 4 units in x direction and 4 units in y direction we will consider only the absolute values since each one in each direction it's similar it does not matter which direction you are travelling so from here reaching here it's same as will take same time as reaching here or here if it's along the same angle in any direction so uh here it will take 4 units so even without drawing this you can calculate you will see what is the difference between these two its 3 minus 1 is 2 4 minus 1 is 3 maximum is 3 so 3 plus next you have to go from here to here so you see the difference minus 1 minus 3 is minus 4 0 minus 4 is minus 4 so take the absolute values only so it's 4 maximum so 4. now you have reached the end so you stop so this is 7 so you return so let's write the code for this so first we will write in c plus list then we will move to java and python so this is the problem the same example and they have given that at least one point is there so you don't need to worry about the base case that is this point is empty so n is at least one so p1 from where we will start initially it will be the first points so we are starting from of index one that is second point since we are already at first point so this will be our destination p2 dx will be p 2 0 minus p 1 0 so you have to keep the order constant if you are subtracting p1 from p2 then it should be done for both x and y you can do the reverse way also since we will be taking absolute value anyway so that does not matter and once we have reached p2 for the next step this will be the starting point so now p2 becomes p1 is the p2 that is we have we are at p2 and next point will be p3 so this will get assigned to p2 so this is accepted let's submit and the solution in c plus is accepted now let's write it in java and python or here we could have taken my reference as well let's see if it changes anything okay let me make it a vector of hint i think this was not there so we could have kept it auto also i think i had added this sign in the end so not much improvement so let's move on to java here it will be math.max math.max math.max and math dot abs and in java it's taking 0 millisecond so we are better than 100 percent in terms of time as well as very close to 100 in memory so same algorithm but performs differently in different languages now let's write it in python 3. in python also it's not bad so what is the time complexity here uh we are starting from first point and this all is constant subtracting one point from other we are subtracting two values so this is order one and we are doing it for one point at a time so it's proportional to the number of points so if there are n points the time complexity would be order n and we are not using any extra space we have just a few variables so this is the space complexity this is the time complexity so i hope you understood the problem it was a very simple problem you can try out yourself
|
Minimum Time Visiting All Points
|
minimum-time-visiting-all-points
|
On a 2D plane, there are `n` points with integer coordinates `points[i] = [xi, yi]`. Return _the **minimum time** in seconds to visit all the points in the order given by_ `points`.
You can move according to these rules:
* In `1` second, you can either:
* move vertically by one unit,
* move horizontally by one unit, or
* move diagonally `sqrt(2)` units (in other words, move one unit vertically then one unit horizontally in `1` second).
* You have to visit the points in the same order as they appear in the array.
* You are allowed to pass through points that appear later in the order, but these do not count as visits.
**Example 1:**
**Input:** points = \[\[1,1\],\[3,4\],\[-1,0\]\]
**Output:** 7
**Explanation:** One optimal path is **\[1,1\]** -> \[2,2\] -> \[3,3\] -> **\[3,4\]** \-> \[2,3\] -> \[1,2\] -> \[0,1\] -> **\[-1,0\]**
Time from \[1,1\] to \[3,4\] = 3 seconds
Time from \[3,4\] to \[-1,0\] = 4 seconds
Total time = 7 seconds
**Example 2:**
**Input:** points = \[\[3,2\],\[-2,2\]\]
**Output:** 5
**Constraints:**
* `points.length == n`
* `1 <= n <= 100`
* `points[i].length == 2`
* `-1000 <= points[i][0], points[i][1] <= 1000`
| null | null |
Easy
| null |
203 |
hello everybody I'm gonna be going over remove linked list elements on Lee code problem number 203 and it says given the head of a linked list and it enters your Veil and remove all the nodes in the link list that has node.bell equal to link list that has node.bell equal to link list that has node.bell equal to Veil and return the new head so we're going to enter it through this length list we're going to find the node that they want us to remove and then we're going to remove it and the way we can get to these different nodes in the linked list is by using the dot next um and that next uh I guess you could say method which is going to allow us to move to one node to the other in the link less right it's like a chain uh you can connect links to each other or remove links so I'm going to draw this out how we're going to solve this which is going to make it a lot easier to understand so we have this linked list one three five seven eight then we have the value that we want to remove which is five so first things first right we need a pointer that's going to iterate through the array to find the value that we want to remove and that's going to be called current and we're just going to set current at the head of the like list which is at the top so this one right here is going to be current now we also need a value that's going to um be before current right because say we get to our current's at five right we want to remove five so if we have a previous value before our current value we could do previous.next we could do previous.next we could do previous.next equals the value ahead of our current value which we'll just skip over this node completely and it won't be connected to our linked list anymore so we need to initialize a previous value and we're going to say p equals 9 at first right because it does it doesn't equal anything but we need to attach this to our linked list now so we're going to say p.m x equals the head of this p.m x equals the head of this p.m x equals the head of this right so after previous currently will be this one and that's how we want it because we want previous always before the current pointer so we can literally just draw P here just to make it or visualize it so key previous none is connected to our link class so now we just need to iterate uh through it so right here is c equal to V it's not so we just move current up one let me erase this and draw this so now cz3 but we also need to move this value so we're going to get rid of this and we're going to say p equals uh essentially p.m next essentially p.m next essentially p.m next so p is now here is 3 the value we're looking for no so we need to move this up again and people had moved up as well so now we have C at five and we have P at three oh c is now equal to the value that we wanted to remove so now all we do as we say p dot next equals current dot next right so we're skipping over so P Dot and X is going to equal current dot next so now it would be one three seven eight as our final length less um so that's how you draw it out now I can put it in Python maybe it'll make sense a little more okay so we want to create a dummy node and this is just going to be an empty node so we'll say dummy equals list node um and then what we want to do is connect this dummy node to the head of the length list so dummy.x equals head um so basically say our linked list is one two three four before this one is our dummy right so dummy is before the head of the link Blitz anyways so now that we have that we need our previous value and we're going to say preview equals dummy right because it's before the head and then current is at the head of the one plus so that way we have our two pointers and then we need to iterate through the list so we could do this by using a while statement so while current does not equal none so while there's nodes actually in the link list right we don't want to just iterate over nothing um if the current value or current value of the node we're at is equal to the value they gave us then we want to say the previous value that it's connected the value that's connected to the previous value of current is going to be the value ahead of current so we're skipping over it we're skipping over the link so pretty.x equals current.x so pretty.x equals current.x so pretty.x equals current.x and if it's not we're just going to move uh previous at one and no matter what we want to continue moving our current uh forward actually we don't even need to do pretty Dynamics we do preview equals current because once we're at a value we want that to be previous once we move from it and then we just need to return our head.nax which is going to give us the head.nax which is going to give us the head.nax which is going to give us the new linked list without the node so if I click run this should work just has no value oh not head dot next it's a return dummy that X which was the dummy node we've created that makes sense and then we should get the right answer yep so yeah really all you're doing is I actually need to submit this just clicked around should work though yep so that solution works but really all we're doing is just skipping over the link right and this uh I guess you could say example here it says they want to get rid of the value 6. well our previous value would be at five and we would just say that proved at next equals current.next which current would equals current.next which current would equals current.next which current would be at six and then after six is null so they'd just be one two three four five right you're just skipping over it can seem kind of confusing at first but when you really draw it out and just see that you're just literally skipping over a note and Link less it makes a lot more sense but I hope this helped and uh yeah thank you for watching
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
56 |
another day another problem so let's Solve IT hello guys I hope you are all doing well in this video we're gonna solve the problem merge interval so let's get started first I will show you a technique that I use to read the problem and try to visualize the solution a lot of people don't know how to read the problem correctly they think that the dinosaur must not be from the questions but instead you can solve the problem from reading the questions and the details that they give us so let me show you an example of how you can solve the problem from just reading the question so the problem is that they give us an array of intervals where each intervals have two value inside unless that have the start and end and they ask us to merge all the overlapping interval and return an array of non-overlapping and return an array of non-overlapping and return an array of non-overlapping interval that cover all the intervals and the input so as you can see sometimes the answer is inside the problem question we just need to break the problem question into pieces and visualize the solution so let's say we have this list of intervals so the first thing we're going to do is to sort all the intervals by their starting value from less to greatest and then we're going to create an output result array where we can store all the non-overlapping intervals and then we're non-overlapping intervals and then we're non-overlapping intervals and then we're gonna start as racing throughout the sorted interval arrays so the first interval will directly be pushed to the result array and we're gonna move to the next value and if it's this next interval intersect with the last interval and the result array means we're gonna check if the start of the current interval is less than the end of the interval inside the result array if true we extend the interval inside the result array by changing the value of the end to be the end of the current interval for example here we have this interval with the star one and the end value is 3. inside the result array and we have the current interval of the star 2 and the end six so they intersect and the three and two so we're gonna eliminate the end and the start and group The 1 and 6 value inside the array inside the result but there is a case one will have an array with the start and the end inside another array intervals that have the value star and the end so we don't do anything and we skip to the next interval and we continue iterating throughout the list of intervals when we keep adding each interval if they not intersect with other intervals to the result array and finally we return the result array so let's jump at code in the solution first we initialize a result a double Loop throughout the sorted interval array we'll check out the first if the result is empty or after the first iteration we add the first interval we check if the end is smaller than the current interval start value we append the current interval to the result array else we change the result interval and value to be the max between the current and durable and value inside the result and the current interval and value and finally we return the results array so the time complexity of the solution is often login because we perform a sorry an algorithm on the interval list the sorted function has a Time complexity of off and login for the most direct type the rest of the solution has a Time complexity of off and as it's involve a single Loop throughout the sorted interval less and as we know in complexity analysis we drop the less significant terms and for the space complexity is often as the result array will contain a maximum of n intervals means that the size of the output array depends on the size of the input array that's it guys thanks for watching see you in the next video
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
462 |
hi guys welcome to tech geek so again i'm back with today's lead code problem that's minimum moves to it to moves to equal array elements that means you have to make the array elements equal and how many moves you have to do minimum that you have to take so that's a leak for medium question you can see lead code medium 462. before beginning with this i'd like you to please i like to request you so sorry yeah please like share and subscribe to my channel in case of any queries do let me know in the comment box i'll be happy to help you out in every particular process and not just this if there are interview process questions or any particular approach you get stuck to please do that and before showing the solution to i'd like to request you all uh i actually explained the approach and the solution is only for those if you get stuck so don't blindly go towards the solution you should stop the video try it on your own and if in case your test case or anything fails in that case you should go after the solution so if you even if you are a beginner please give it a shot you should not do just copy of the code or something like that because that won't help you out in any particular way so that's what i wanted to say now let's see how and what the question says for okay so the question says we have been given an array that's norms of size n return the minimum number of moves that are required to make all error elements equal that means how many number of moves should we do to make the r elements equal now in one move either you can do plus one increment element or decrement the element okay by one so either we can make an element with plus one or minus depending on the condition now test cases are designed so that we fill 32-bit integer okay they have been given 32-bit integer okay they have been given 32-bit integer okay they have been given one example okay so example here is one two three so let's consider each and every piece okay and now let's begin here we have been given one two and three okay this is sorted but not in every case you get sorted the very first thing let's consider we want to make one as the equal element it's just a hit and trial so don't think so what we need to do we need to subtract it two times like minus sorry this minus one and this would be subtracted twice minus one and minus one that is two moves of this and one means of this so in total we will require three moves if we want to make all three as one okay the next condition would be to make all as two what we need to do we need to put two plus one here and minus one here so obviously one plus one this will be two this is already two so no moves required and again this is two so here the output is true again let's check for three we'll check all three conditions here though that is not what we have to do in this question but just explanation if you want to do three again this would be same add one here that's one move add one and again one in total here also we need three moves so overall looking to this which is the uh smallest number of moves that are required this is two so this is what our actual solution should be now this was a hit and try let's say you have a n number of elements then how can you do that you cannot check on your own like plus one minus one no every time you cannot so what you are going to do in this case okay let's look at the second example first 1 10 2 and 9 as i said it won't be sorted every time so you get that 2 10 so sorry for my writing okay 1 10 2 9 no still therefore if you try to do it will take much more time as compared to 1 2 3 but still again trying checking for one checking for ten checking for two checking for nine that's not what we need to do in our problem solving we need to get a proper approach right so what we have to do is first sort the elements okay one two nine and then okay now you know one thing we need to get an element that should be chosen that is an appropriate thing which will give us minimum numbers that is the element which is quite closest to each element right that is what we need to do so i guess for getting a closest element we must be aware of the word median if you guys know the statistics median that's a middle element obviously in so many elements the middle one would be the one that is approximate or easy to reach so what we'll do we'll find the median how many elements are there 4 so let's say this array was a so length by 2. okay what is length by 2 that is the way we find the median i hope that is what you guys are aware of so the median here would be a of 2 okay a of 2 so 0 1 2 so this is the element that's 9 so that means the element that is to be made like all other elements should be made equal to this element okay now how we'll do we'll run a loop from i equals to 0 to n minus 1 and we'll take one minimum moves let's say m for now this is zero we will find the absolute difference between this middle element and all other elements and we'll sum them up that is these are the minimum moves so minimum moves plus equals to would be absolute difference why absolute difference because we don't want to subtract even if we are subtracting then also we are adding it as a move that is a of mid here it is 9 i am writing a it should be of mid actually and a of i okay this should be what we need to do let's check okay for this question let's check it out okay first is 1 minus 9 absolute difference 8 2 minus 9 again 7 9 minus 9 is 0 times 10 8 plus 8 60 so that is the minimum number of moves that are required you can see even the solution says they are 16 moves right now coming to a question why didn't we take two okay so let's set for two also you get to know if you take two as the medium okay then the difference is 1 0 7 8 so you can see the result is again the same if you remember in median there was a condition if there are even elements we take this plus this as an average but in this case we are not going for average so when there are even number of elements you can take either this one or n minus one that's mid minus one both will give you the accurate result okay but if talking about odd number of elements then this is the only one that is to generalize the question not to check it should uh like n is even or odd this is the particular thing that we should go up so i guess this is uh clear with you all what you have to do sort the array very first second find the median middle element then find the absolute difference between all the elements and the middle elements sum them up once you sum them up you know what are the minimum number of moves required so this is basically an easy question if you know the concept now let's look at the code again a request to each one of you don't blindly follow the code go up with your own solution again sorting the array finding the median making minimum moves are zero traversing the array adding the absolute difference and returning the minimum moves so this was just an easy thing that you need to do and for this you know that it would be o or n log n y of n log n because you're sorting the array so sorting is o of n log n so that is the time complexity and talking about the space complexity that's order of one so this is what the question says in case there are any queries regarding the question complexities approach any other pro that's beneficial do let me know in the comment box thank you and keep following thank you
|
Minimum Moves to Equal Array Elements II
|
minimum-moves-to-equal-array-elements-ii
|
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_.
In one move, you can increment or decrement an element of the array by `1`.
Test cases are designed so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** 2
**Explanation:**
Only two moves are needed (remember each move increments or decrements one element):
\[1,2,3\] => \[2,2,3\] => \[2,2,2\]
**Example 2:**
**Input:** nums = \[1,10,2,9\]
**Output:** 16
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Math,Sorting
|
Medium
|
296,453,2160,2290
|
395 |
hi guys welcome to beginner techies in this video I'm going to discuss about another problem of sliding window in the last couple of videos I have already discussed your problems and uh I have solved this problem with the help of sliding me today and also discuss about the sliding window if there is a problem so how can we actually identify whether this problem is applicable to solve with the help of sliding window technique so if you don't have understanding about the sliding window technique first I would highly recommend you to go through that video I will share the link of that video into the description box okay so let's see this problem how can we solve this problem with the help of sliding window technique this is the most frequently a question in coding interviews so let's go through the problem in state 2 first so the problem is longest substring with at least K repeating character given a string is and an integer K return the length of the longest service string of s such that the frequency of each character in this substring is greater than let's say this example so that we can get better understanding here input is given string and K is equal to 3. right so we have to find out the max length of substring right and in that substring each character should be each the frequency of each character should be greater or equal to K this is the conditions we have to check into the service frame so if you see this a repeated three times and B repeated two times so if we just consider this substring a and then b so B is repeated two times only Which is less than K right so the max length should be the like the string the substring will be nuclear and max length would be the size of this substrate so this will be the output if you see this uh example the string s is given K is equal to 2. here character is a b c so if you see the substrings first a is to so we will like the size of uh substring will be at least case size right so let's see if the substring is a b in this case a is less than k v is less than K so this will not be considered again a so a is greater equal to a this is fine again B so if we see this substring a b in this substring a is repeated 2 times B is repeated two times okay so this will be the uh like uh considered substring like and the size of this substring is 4 now we will move forward and check again so here if we consider this substring a b so this substring is also valid substring right because in this substring a is 2 times and B is three times which is greater equal to K and then move forward again we will like there might be some more a character with a and b but here it is C only so C is repeated one time which is less than K so till this position a b this will be the valid substring okay and this is the max substring Mass length of substitutional right this size will be 5. this will be the output so draw example over here so that we will get understanding a B K is equal to 3 right this is the example given example one right so we have to find out the max length of substring and in that substring every character a frequency of every character should be greater equal to K here if you see this is the substring AAA which is valid right and length of this substring is 3. if we go with this is not a valid because here frequency of B character is less than K right this will not be a valid so this is the final output will be so the final output will be 3 only so how can we approach this how can we solve this problem if you are talking about sliding window technique so yeah this problem can be solved with the help of sliding window table because in this problem we are talking about stream right in this problem we are talking about substring and window size we have to make it has two types of Windows size fixed rent variable right I have already discussed these things in the previous videos I will share the link in the description okay so this problem uh like this condition is uh like this condition are uh satisfied with this problem so we can go ahead with sliding window ticket sliding video now the problem is like how can we approach how can we create a window how can we expand a window how can we shrink a window if you are thinking if you are talking about sliding window technique then two things we should be here sharing the window at certain point of time expand the window right expand the window these two things we have to consider while applying sliding into technique okay right so let's see how can we apply sliding menu technique over here we have this example K is equal to 3 right and for sliding window technique I generally use two variables I is equal to zero a is equal to 0. window size will be what window size will be Q minus right so this is the right pointer this is the left pointer okay so at J is equal to 0 we have a nth frequency of a is one at J is equal to 1 we have a again frequency here is sorry frequency of a is2 J is equal to 2 we have another a frequency of a is 3 right so we have this right we got this substring right because this is greater than equal to K so at this step we have to calculate the length of window our substring you can say substring okay so once we got the um substring once we got the length of substrain so at this step we have to either shrink but expand right link or expand this is what we have to decide at this step but here we cannot decide because there might be another is there might be some other characters further okay so in that case we cannot decide to shrink or expand if we see J is equal to 3 we have B and the frequency of B is 1. right Which is less than k we cannot calculate substring length right so we have to think about the approach we have to apply sliding into technique but there will be slight changes so here the idea is so the idea is let me consider the same example or we have another example right let me uh copy the another example here this one okay this will be better so a b is a b PC K is equal to 2 okay so we have this example and we have to find out the maximum we cannot apply the approach we have discussed here right we have to think about some other approach but we have to apply sliding window technique so the idea is either we calculate unique character uh in this substring sorry in this string or we can are like in like if we consider any substring so any substring can have maximum 26 unique character right or else we can consider 26 Max unique character 26 Max unique uh characters right because in alphabet in the constant if you see here so the constraint is given so s consists of only lower case English letters so this string will consist only English letters right so we have total 26 character in English alphabets so each substring in a substring if you have a large data set in a substring we can have Max to Max 26 unique characters right it should not be more than 26 so either we can calculate the unique number of unique character from the string or we can simply run through the like 26 we can consider the 26 Max unique character so this is what we have to do let's suppose I am going I'm just considering this approach okay we have Max unique directories how much a b and certain three character a b so if we find out the if we found any valid substring from this string any valid is free substring so that substring should have maximum these three character ABC right so that we have to check right so let's see uh like here total right so max unit characters are Max unique character is equal to here a is B and C these are the three unique character in this service in this history so if we get any valid substring in that substring we will have these we will have only these three characters so if any string is given we have to find out the unique character so once we get the unique character then we will start from the one like from the unique character one till the size of that unique character so here we will start from Max unique chair is equal to 1 till the size of what this one okay so right now the size is 3 so we can consider three okay so here we can remove this so size 3. right so if Max unit carry is one if initially we are considering this so in this case in the sliding window in this sliding window there will be only one unique character if it is too sorry if it is to then there will be too unique character if it is three if it is 2 then to unique character in the window if it is 3 then how much 3 in a character right very unique in the window side in the windows so this is what we have to think about right this way uh this approach we have to apply so let me draw uh one table over here so that we will get better understanding about this okay here the character here the UniCare and here frequency of each character and here maximum okay so if yeah so I have to declare two variables I is equal to zero J is equal to zero as I did as I declare here already right okay so I is equal to zero J is equal to zero so if I if J is equal to 0 J is the right pointer first I will increase the J okay so J is equal to 0 character is a okay let me uh a b c it a b C this is our history yeah so J is equal to 0 character is a UniCare is one here we have a only right so a is a unique character frequency One max length we cannot calculate because we can only calculate once a tree Once the substring is greater equal to 3 right greater than equal to K here is three now J is equal to 1 and character is B in this case this is uh another unique character so unique character count becomes 2 right which is greater than what Max unique initially we have we are doing Max unique okay let me add one more column here okay Max unique cash okay this is one right this is one we are iterating on this right Max UniCare is one so in this case UniCare is unicab is 2 and Max unit carries one in the sliding window there will be maximum one unique cat if Max UniCare is one so in this case the condition is getting failed right so if UniCare is greater than Max unique care let me add the conditioning here if unique care is greater than maths unit care in this case we will shrink the window we will the window remove ith element okay right so in this case we have to remove the ith element so I is equal to 0 J is equal to 1. now we have to remove ith element so ith element at zero position we have this a right this should be removed I'm just removing this to avoid any kind of confusion and this B yeah right so I is equal to 1 J is equal to 1. okay so now J is equal to 1 J will become 2 so add 2 we have a right again we have uh two unique characters right but Max unique character is one maxini character is one but again we have two unique characters which is greater than one right which is greater than one so again we will shrink the window so I is equal to 1 because UniCare is get the myosinical so I will become 2 and J is equal to 3 so in this case this row will also be removed okay now J is equal to 3. in this case another character is B again we have another unique character we should have only one unique character right as per this condition but this is second year second character right second unique character again the condition is fair in this case we have to shrink in this case we have to remove this ith element okay we have to remove ith element and I will become 3 and J will become 4. again we will check for here for B so here it is B okay so this is unique character right B is this is unique character so here it should be 1 it should be one so it is equal to any character this condition is satisfied but frequency is what frequency is 2 B is occurred two times right Which is less than k is 3. k a is three right so again um we cannot calculate the maximum because the condition is not satisfied now J is equal to 5 in this case there is another character C if there is C then we have two unique characters right in their window this is second unique character which is greater than Max Unica you should have only one unique air in this window let me and this other in this window so here in this case condition is fair we have to shrink again right we have to shrink again and I will become what I will become 4 and 5. so we have to remove these two character okay so this way we have to remove pushing the window so for Max UniCare 1 we did not get any valid substring right you did not get any valid service free so now we need to check further for Max unicad 2. right now we have checked only one right now we have to check for two now this should be issued two so in this case J is equal to this will iterate again J will be zero this is a UniCare 1 frequency one maximum can we cannot calculate now again J is equal to 1 next character B yeah so unicar is 2 here it is also to condition is satisfy frequency is this is the base frequency it is one which is not condition is not satisfied it should be calculated equal to three right so we cannot calculate maximum again J is equal to sorry j is equal to 2 again we have a yeah so unit character is UniCare is two right um a two times nb1 times there are two unique characters only in this window right so unique character is two frequency is what two but a it is 2 right for a it is 2 for B it is one frame so again it is yeah it is K is equal to 3. here it is less than K so the condition is not satisfied J is equal to 3 now what is the character B so here if you see um again we got the B so again in this uh if we see in this uh window in this window we have a total two unique characters right still we have two unique characters can this condition is satisfied we should we don't need to give any string we just need to expand okay right so frequency is what to right we have two a's two B's right in this window but still the condition is not satisfied okay sorry K is three okay sorry K is 2 in this case K is not three it should do it a is right so the condition is satisfied so we have to calculate this word this window this length so the length of this window size is what 4 right so till now we got the a b means 4 right now we check further J is equal to 4. right again we have what T right again we have only two unique characters right so the condition is still satisfy with Max unit care right so frequency is what these frequency is 3. B is 3 a is what two right so still this condition is satisfied right because B is greater than equal to 3 V is greater equal to K and a is greater equal to K right both the condition are satisfied so in this case we will consider this because we have to find out the max length so max length will be 5 in this case okay right now we will check for pi this is C and here C is different character if we see in this window so we will have total three unique character right total three unit character so we cannot uh write so the condition is getting filled right here it is 2 and here it is 3 unit carries 3 Max unit carries two in this case we will sharing the window we have to remove these three we have to remove till B right so we have to shrink okay this the I'm just removing this thing for understanding because okay so we have to remove all the calculation so again we will check for Maxine care 3. in this case J is equal to 0 car is a and unique carries what a sorry one similar with we cannot calculate Lane right so same way if we see so we cannot get uh like a valid substring with this uh with the three unique characters so our output will be what we have calculated with Max any character is equal to 2 if so our valid substring length will be 5 in this case okay so this way we have to uh like build up an object right so let us uh write the code into it so that we will get understanding okay so let's write the code here it so first I'll calculate the length of history okay right and now I will create one set to calculate the unique characters okay let me name it as Max unique tab is equal to Mu has it okay so we'll write one for Loop here enter is equal to zero I less than what is dot length right and I plus okay so here in the max Unica alert but it should be character alert is that right what fine okay right okay so now I'm just uh yeah so we have to right one outer loop unique hair is equal to 1 and I less than Max unique f right Dot size I plus and here I will create these variables is equal to 0 which will be in 8.2 into J is equal to okay now okay so here we'll start from J less than Android length of a string now we have to check what we have to check if unique care if UniCare um we have to check two things right the first thing is frequency of each character should be greater equal to K this is one thing we have to check and another thing is we have to check is you can see of each character greater equal to K and it should not be so unique care count less than unique that's equal to any care okay so these two things we have to consider right so for that I will create one variable here in the same variable into unical account is equal to 0 and we have this right so we have to uh maintain one map here it should be character and integer so count map air map okay this one you have to fill it right have to add the condition so unique care count should be less equal to what any car right unique cash this should be less than any care and here we have to add the character into the this Dot J airmap get a default is dot cap at here if it is not there then it will be 0 otherwise it will okay so now we have to check uh number dot yes dot carrot okay if it is equal to 1. if it is 1 if then we have to if this like if this is unique character then we have to foreign otherwise we have to so this is one condition we have to add and another condition is we have to check the frequency first we have to check the like unique characters and this second condition is we have to check the frequency right so in the count map we need to check test dot parrot dot okay is equal to K so in this case we have to increment the word we have to maintain one more variable here called a Time is equal to okay so this should be count a Time right and here we have to increment J plus or else we have to shrink if this condition is not satisfied like if unique account is greater equal to Unique care Max any care so in that case we have to shrink the window what we will do so in the care map we will simply code for this is dirt at so we have to remove the ith element and map dot get s dot tab at I minus 1. right so we have to remove if it is a care map dot get is dot get at I equal to 0 then in this case we have to decrease the unique Care on we have to remove the unique care count and this should be decrease if care map dot get map.get is Dot map.get is Dot map.get is Dot here at s dot carrot I equal to a minus 1 if it is less than frequency then we have to if it is less than k so then we have to reduce minus and here we have to intimate right and here we will check if UniCare account if unique account is equal to any cares we have unique care and count K time is equal to unique here in this case we have two find out the max length so here we have to Define one more variable into max length is equal to zero okay so here we will matter Max so mad dot Max right minus mat.max mat.max mat.max we have to find out the max length it should be my slip and it should be K minus I this is the window and from here we can simply return right so let me run this problem cannot find simple okay sorry this should be any care right it measure okay so this bracket should be closed here is this so these two test cases are passed let me submit this so out for 37 31 test cases are passed six test cases are getting paid what is the issue with this a okay so this one is failing okay so this should be here equal right equal to right so uh the all the test cases are passed and now the solution is working fine so let's do one uh Quick Change here in the summation we can see uh total 37 Ms it took let me just do one quick change here let me just uh I'm just making it 26 because in the English alphabet we have total 26 character so instead of calculating these things we can ignore this part and um yeah so we can simply use 26 and let's see what are the impact so this is our Summit but it took 45 EMS right so every time we are uh like we are uh doing we are uh iterating 26 times right so if we see if we are just considering this uh solution like if you are just uh calculating the number of what uh like number of if you get the number of uh unique characters so we just need to iterate uh till the size of a unique character right we don't need to iterate every uh 26 times right so we can just like improve this one if we simply use this Max unique like we can calculate the unique number of unique characters and we can iterate till the size of a unique character so in this case the like uh like the complexity of this uh overall solution will be like if you are considering 26 then yeah so the complexity will be 26 into Android complexity will be complexity 26 into n but if we are considering the above solution then it will be complexity will be what complexity will be Max unique whatever the size into n so let's suppose in this case we have total three unique characters then the complexity would be 3 into n but if we are going through this 26 like uh if you are checking all the um if you are considering 26 uh unique characters then in that case the complexity will be 20. so this is the difference if you are going with the if you are calculating the unique characters and if uh if we are going uh with if you are considering 26 unique characters if you are considering all the alphabet in a single substring then yeah so these are the uh like little differences in the performance so see you in the next video thank you bye
|
Longest Substring with At Least K Repeating Characters
|
longest-substring-with-at-least-k-repeating-characters
|
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.
**Example 1:**
**Input:** s = "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times.
**Example 2:**
**Input:** s = "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only lowercase English letters.
* `1 <= k <= 105`
| null |
Hash Table,String,Divide and Conquer,Sliding Window
|
Medium
|
2140,2209
|
889 |
Hai gas welcome you today's video and today we are going to do problem 889 of lead company whose name is Construct binary tree from pre order and post order driver so basically here we have been given one pre order and one post order has also been given. And from these two we have to construct our trick, so let's see how we will approach its solution, so this is what I live, our input, here in Curzon mostly what we do, how do we see one in which our first sub question or If sub part of D question is solved and if that sub part of our question is being solved, then we can give the next part to Recogen to solve and it gives it to us, then we call it recursive caller faith. So the particular problem in it is a little bit because of its anti-irritation, not so much, but still anti-irritation, not so much, but still anti-irritation, not so much, but still I will try my best to understand you and if you did not like this explanation so much, then do not take any tension, you will get it very well with dry iron. You will know what we are doing, so first of all, we have given this preorder and post order, so if I imagine like this, my preorder would be one and for example, this would be my free order and this would be my post order, oh one. So do I do this know foreign example if this is mine then what I would do is an index let index which would be Priya and if mine which I am fairy is going to note create Renault which will be the root of mine is this equal you new reload and zero inside that then what This would have reduced my entire answer, wouldn't it have been solved because I have only one note, so this one note of mine would have been created like this and then what I would have done is if the IF value of route or the value of route, we can say of our post order. Also, our tree has been created, so what to do plus and return the root and here also we will do plus because we have already made its root, so what will happen here, we will see first of all our function in our function. First of all, the root will be created from the index of our Priya IDEX, so this is our 03 index one, so the root of one has been created and then I checked whether the value of my root which is equal to one is that post. If ID is from the value of It's simple and this is only when we have one element only if we have only one element so right here this is our index 0123 456 and similarly post order also 012 3 4 5 6 So now in this how if I we know this That the root comes first in the pre order, so our first element is going to be the root, so if I create this root like this, then the value of my root will be equal to the zero value of the post order, obviously it will not be because here the post order. Last of all, we are going to get that route meeting, so what will I do, this means that our tree is incomplete, so if our train is complete, then what will we do? Research my faith, I will do this tomorrow and will say that IF Value of root is not equal with post of post order means my puri is not made so what I will do is I will redo the function tomorrow and in that I will add my joke tomorrow will be our free order and is of post order and from that What will I do because my Priya order is plus so hence my next note will start becoming road and then I will start making left and right from me, similarly I am going to do this with the right also and here I will capture on the function. I am going to do left of the root and right of the root, then left of the root, this will go left and this will go right of the root, so what will happen with this, if you want an in depth explanation then please look at the dial because it is dry like this. There is a possibility of finding out more from the iron itself, so what I did first of all, I saw that whatever is the index of my order, which is the element of my dear order, that index, if what is the post order, will be equal to the index of the post order. It means that my tree has already been created but if it is not so then from the left I will add ours tomorrow and from that our entire algorithm is like this, the value of the note at this point is ours which is equal to you in our post. With the post IDEX of the order, our free is already created, so what should I do, then what should I do, I will apply the vicarious tomorrow and similarly, the right of the root will also be used for the reverse tomorrow, but when will I apply this tomorrow, I will apply this tomorrow only when this condition of mine is met. Note is equal to this is what will happen with our post IDEX similarly and when I have my own complete tree then what I will do is I will index the post order plus return root [ return root [ return root directly return post index and we will Return Route This is the code and this is the code for note creation and this is the route note on pending D creation, meaning you will understand everything, if you have not understood anything yet then keep a little patience, then this is the first thing I One wait which will start from zero similarly one India one wait post ID Equal tu neutrinode in which we will put whatever is the value of the fairy idea of proorder then after that I will whatever is the value of the fairy idea of proorder then after that I will whatever is the value of the fairy idea of proorder then after that I will see that if the value of my root if note is equal tu this note is our note creation then after that this is our checking then I this I will do recovery tomorrow for whom free and for post and here our post order will be updated here every time when we are creating this of preorder then our index will be already created because once I create this route then There is nothing less for me in this index because I have already made a note of it, so I will add the index of free order plus every time I am making a route or note of mine here, so every time I make a note. Then I will index the provider and increment it because it has become mine. Load has been created. Note. Okay, so now I will do it here tomorrow Priya. Who will it be for? This will be one on the left of my root and similarly this will be on the right of me. Also reduce the value of the root by one to the right of the root and make tomorrow free here and post it pass and if both of these fall, it means that my tree is already complete, that means what will I do? I will increment the post index if both of D about function root what we will do is we will increment and return and this is getting accepted ok new renoad and idea root creation in trainode then after that we will check if tree complete it Which will be my IF root value if note is equal with the post of my post then what to do then do it on the left of my root if the value of root is not equal with the post index of post order then here also I have to reduce Do it in the right of my route, you fill it for free, we tell it to the request man and if it has not been made then we will see by submitting this code, this is our code, we will see whether it creates a tree or not And Here a goes in one step because what we check after that is whether my root value note is equal to the post index of the post so the value of our root this time is Rahat one and our post index of the post Hey ka The number of post index is four, so one, note this is equal to four, so this one goes to the left and one goes to the left corner and let's see what it does, we here the index of fairy order was plus after doing one. After create then after that again new left tomorrow and we see that we create a new one and a route number then for you we do it here create a new one note okay then what happens after that we then Let's check from whether my tu jo hai note is equal to tu hai with four because the index of post index is still zero relief so this condition is also true and here when you are divided then this tu yourself is also here fairy. Used to do index plus. Okay, so this is when the condition is true, so what we do here again is we put tu's left kal and what happens after tu's left kal is put is we go to a new function again. And we add a note of new free index in the root which is 4 at this time, so look at this now, this is a very important time, so now it is ours and this is the time when our free index is, meaning for. Only this much you can do it, you can imagine and this post index in the post order is 0 and this four has come, so is this the tribune for the post order for four and for the preorder which has become our note. If it has been done then yes its tree has been created because there is only one note 4 more in the free index and our post index has also been done but the post index is zero and its tree for the post has already been created so these two IF becomes water and so what do we do, we index the post and return the root, then it becomes four, attack here on your left side, this was our smaller sub problem which we were looking for. To apply recursive fat, then what happens after that, you run your right call, this is four, it goes from the stock and you run your right call, then what we do is we check whether mine which is 5 First of all, we add the note of five at the root, so it becomes the note of five and then we see whether my 5 is the value of the root, is that note equal to you, post after post. From the index, the post index of the post has already become 5 because if the post is index then the post is of one or again if the condition is met then again for 5 our first 5 is divided then it becomes There are three, so only this one can be considered for the free order and this was the post index which was only this one can be considered and so what we do is we index the post plus which makes it you and us. Let's return the root to your right, so this 2k goes to the right, five is fine, so what happens now, after that, both the 2's are gone yesterday, so what do you do yourself, you add a plus to the post index. Plus and returns, okay then what happens now, 2's left is gone tomorrow, one's is gone, so one checks again whether the value of my note is the same now, one note is equal to you, my post order's posts. The value of the index here is 30123, so now for the viewers, one, note this is equal to 6, so we run right, when we run right tomorrow, what happens to our pre index, the fourth one in the order is 101234. So these three notes are created here, with this statement, then we do this pre-index, plus then we do this pre-index, plus then we do this pre-index, plus from here, okay, then it checks whether the value of mine is equal to you, so this condition is It is true, that is why three itself comes to its left color. When three moves to its left, then what happens in the stock? We create the new root of the free index, which is Pari of five, so dear. If five is six, then we create a mode of six, but when we create the note of six, then we check whether my sex, then this condition is a caste, so that is why it is not ours. Since this is also not running because now this condition has become true, so now only if you have paid attention, this method is also running for six, five index and post's IDEX is running right now, so right now only for the wallet tree itself. The key tree is already created because we have created it, so both of them get destroyed and what we do is we add the post index plus in the post order, but when it is divided into five, we also add plus the pre index. So it becomes plus, both the IFs don't run, the post index also becomes plus and we return six, which one is to the left of three, okay 3, have you seen what is the value of my note right now? Now, what is the index of post order? So my 3 is not there now, that means it is not there since 7, so 3 runs its right, what happens to it, we do this is the note and seven gets added in this type. Then what does seven do? Seventh checks whether the value of mine right now is 7 is equal note equal tu is equal to seven, so it has become water, again the same thing has happened now, our free index is now six and this is after north is created. Seven is done and similarly our post index is 4 due to which these two of ours are 7 and so only for 7 its own has been already made so we both of these become our IF conditions false we do force Post index plus which is 5 and we return the right of root 3 right now both of 3 are gone yesterday so what 3 does is it increases the post index itself by one and it returns this Now this attack has been done for One, you can see that both of them have left yesterday. What does One do itself? It indexes the posts. Plus-plus which indexes the posts. Plus-plus which indexes the posts. Plus-plus which becomes 7 means what for 1. The post index for was one was six which is this is the error of one and when the one was created what was its pre index which was zero again which was the index of one so for one this is what we saw from this condition from which our tree It was completely finished building so what we used to do was post index plus and return the root from which we return this root our mentha I hope guys you have got a lot of clarity in this dragon now if not Hey, don't worry, we will see you again This is my tree 12 34567, okay, what will be the order, I will delete it, now its free order will be 1256734 and its post order will be okay, so now we are here. We will continue to do this, first of all our preorder relief is index free index relief is zero so as we run the function we note down its root so here it becomes plus and this is one then after that what do we check is the value of my root. Which is one, which is equal, with post index zero, which is six, then this note is equal, if you are there, then this condition is true, this is why one moves to its left, what does one do by moving to the left, one does? Add new one no which is tu and then Shyam does tax plus and this gets printed, tu gets added here tu wala note, again what do we check whether my tu note is Equal, you are six, so this also comes to our mind, so again what do we do, we make a new index, note a new root, create which is free of free index plus, so now we have a free index and you are therefore five. Goes create here and we change the free index to plus which is three then after that it becomes three add in the step sorry five becomes what five note is equal to 6 so it becomes true again. Its condition is fulfilled, so five itself, who moves to his left, then what happens, we make a new note, whatever happens, ours gets printed, at this time, what happens is that the value of our root is six, that note is not equal to you. Rahat six so this if didn't run becomes water and this if also didn't run and so what we do is we index the post plus was plus and we return root so this six does return itself This attack is on the left side of five, so now for six you could see again that for printed six it was three and post index was 0 which means value six and similarly you can see in post also, okay so now What happens after that is 6, what does tax do, now our post index has been created, you are one, so its is 7, okay, so now five checks whether mine is my own value, the value of the root is five. Note, if you are equal, you are seven, then this condition is exactly equal, hence, five moves right and left, what does five do by moving right, the fourth of the free index, which is the fourth index, means it does the root of the fourth index of Pari. Create, so this seven becomes root create and we add 7 here, but now what happens to 7 also, seven, you have seen yourself that my value is 7, so note, it is not equal to seven because it is equal to 7, so this What it does itself is just add the post index plus and it returns, so now you can also see for the intake, when we created this 7, we have this plus index, it means there is an element, it is 7. And for the post also, the element of the first index is 7, so the entire tree of the seventh is already created. In this condition, therefore, we are returning the seven by adding the post index. If its parents are okay, then we also know this. So what happens now? After this, both of the fives are already gone, so what five does itself is post index it plus and return what is my value post index post of post index meaning post of which 3 Its value is zero one you three so our post index of the post here is our post index now is three so the post of post means the three of the post is the element is you so we check this is you note this equal you This value and this statement is absolutely correct, so what we do is this water is a species statement, so we do not run this condition and we index the post directly, plus, okay, so this post gets indexed, root yourself. Gives return to one and this goes to our route tax now what happens now first one checks whether my value note is equal to you post index which is then what is our 01234 on post off which is then this condition Is true, hence one executes right. When one executes right tomorrow, what do we do? We create the value in the fifth index, then its root becomes here, three is created. From this statement, what happens after that? Let's check whether the value of my root which is three is note equal tu hai with four so this should also be jati hai tu condition so three itself what does its left move and when this three is divided then this pre index Also done relief is six meaning and this becomes four add what happens is we check if my per note is equal to four then this condition is there and what we do is add plus to the post index and Let's return to the left of route 3, now you can also see that our post index was and hence the error was that the error of post index was only 4 and similarly the value of pari index was six. Six of the index in which its value was its Sabir 4 so both of them remain equal so its tree is already created so we just return the post index by doing plus as it happened with one in our base kaise then what after that Is it and 3 have you seen that right now my post index file which is 3 and my value is and what we do, now you can also see here that our post index right now is post of post. The index which is six and we have this one and when we did the print then the value of the print was pari of zero and hence now this condition has become completely correct due to which our whole has been made and we return this one root one. The root is our function, so you can see that our tray is made exactly the same way, 12576712 567 and then 3434, so this is ours, again this is a little bit into it does not mean much, but if this is basic to you, then coding is like this. If it is not difficult then I hope you have understood this code and the driver has understood each and every line of it, then its time complexity will be there. If we create this program and then return it, then it becomes average. And the space complexity is that we are creating each and every note, so that too is off and the amount of space required for research tax was just this. The problem was that nine did not entertain me a bit and I found it a bit hard to make it suffer but I did. I have tried my best to convey to you whatever I have learned or learned from this problem, I am Shikha Sakoon, but still if any mistakes have been made then please construct a critique season also. That's all there was in the video, you must do the dry iron yourself and after submitting the question, write in the comments that you have submitted, so that was all. Now we will meet in the next video. Til Cup Coding and Cup Driving.
|
Construct Binary Tree from Preorder and Postorder Traversal
|
buddy-strings
|
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_.
If there exist multiple answers, you can **return any** of them.
**Example 1:**
**Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\]
**Output:** \[1,2,3,4,5,6,7\]
**Example 2:**
**Input:** preorder = \[1\], postorder = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= preorder.length <= 30`
* `1 <= preorder[i] <= preorder.length`
* All the values of `preorder` are **unique**.
* `postorder.length == preorder.length`
* `1 <= postorder[i] <= postorder.length`
* All the values of `postorder` are **unique**.
* It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
| null |
Hash Table,String
|
Easy
|
1777,1915
|
207 |
hello everyone in this video we are going to see the lead code question number 207 course schedule there are a total of n number of courses you have to take labeled from 0 to nus1 you are given an array of prerequisites a comma B indicates that you must take cos B first if you want to take Co a for example the pair 0a 1 indicates that to take the course zero you have to first take the course one return true if you can finish all the course otherwise return false we are given two examples in the first example the number of courses is two and the prerequisites are one comma 0 so there are two courses in order to finish the course one you should finish the course zero so this is possible let's see the second example the number of courses are two the PRI requisites are 1 comma 0 and 0 comma 1 that means that to take the course one you have to finish zero and to take zero you have to finish one so this is not possible so we are returning false I hope the question is clear now let's get into the approach let's take an example of this scenario which has four courses and a list of prerequisites I am representing this in a diagram for taking the course zero one and two are the prerequisites and for the course one course three is a prerequisite as a first step I'll create a dictionary with a list of all the child nodes and its corresponding parents in the value for the child node one zero is the parent similarly for the child node 2 zero is the parent for the child node three one is the parent as a Next Step I'll create a list of number of branches for the course zero there are two branches for the course one there is one branch and for the course 2 and three there is no Branch the next step is to create a queue with a list of courses that doesn't have a dependency in our example course 2 and the course three doesn't have a dependency so we are adding two and three in the Q the next step is to pop each node from the left side of the queue and identify its corresponding parent and remove from the branch now we have removed the co two which doesn't have a dependency and check the parent of index 2 which is node Zer and see if the parent has any dependency in our case Co 0 has a prerequisite of cos one now we are popping the next element from the Q which is node three and identify its corresponding parent and remove the branch now we are checking the parent of three which is one and see if one has any dependency in this case node one doesn't have any prerequisites so we are adding one to our Q now we are coping the node one from the que and identify its corresponding parent and we are removing the branch now we have removed the node one and check what is the corresponding parent of node one in this case the parent of node one is zero so we are adding zero to our q and we are popping the node Zero from our Q now our Q is empty and we are checking if all the elements in the branch is zero in our case all the elements in the branch is zero so we are returning true after iterating through all the elements if the branch has still nonzero elements that means that course cannot be completed and we will immediately return false I hope the approach is clear now let's get into the solution first we are declaring the variable child as the default dictionary which has the list of all the parents child equals to default dictionary of list now we are declaring the variable Branch equals to list of zeros multiplied by the number of courses now we are populating the value for the child and the branch variables by iterating through the prerequisite list for I comma J in prosites for each child we are appending the parent child of J dot up and off I and increment the Corr responding Branch branch of I plus equals to 1 now we are declaring the Q as a double-ended Q so that we can pop the double-ended Q so that we can pop the double-ended Q so that we can pop the element from the left side Q equals to a double-ended Q DQ now we are upending the cses that doesn't have a dependency in the Q for I in range of the number of courses if the branch of I equals to zero that means that course doesn't have a dependency and we are appending that to the Q if branch of I equals to 0 Q do up and off I now we will iterate through the Q until the Q is empty well Q I'm popping each node from the left side of the Q node equals to Q do pop left and I'm finding all its corresponding parent nodes and removing from the branch for I in Child of the node branch of I minus equal to 1 if it's parent node doesn't have a dependency we are adding the parent node to the Q if branch of I equals to 0 then we are adding that to the Q after retracing through all the elements of the queue we are coming out of this while loop and see if the branch has any nonzero elements for I in Branch if I not equals to Z that means that the course cannot be completed so we will immediately return false if not we will return true let's submit it the solution got accepted the time complexity of this approach is often because we travel through each node at most twice we Travers to node two and node three once and we Traverse through node zero and node one twice the space complexity of this approach is also W ofn because we are creating a dictionary and two lists and the number of elements in the list and the dictionary varies depends on the number of prosites I hope you like this video I'll see you in the next video thank you
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,685 |
hey everyone welcome back today we are going to solve problem number 1685 sum of absolute differences in a sorted array first we will see the explanation of the problem statement in the logic and the code now let's dive into the solution so in this problem we are given a nums array in a sorted order and we need to find the sum of absolute differences right so for example if we consider two we need to take the absolute differences with all other values and we need to add them right we need to sum them right so for example we need to take difference between 2 and three right that is one possible absolute difference we can take then we can take 2 and five right so this is for only for the current value two so if we do this we are going to get 1 and here we are going to get three right we going to get four so then we need to open this four in our result list right this will be the first value that is for the current elements index since we use two for this sum of absolute difference right similarly we need to try that one for 3 and two and then we need to try for 3 and five in the first index that particular value will be upended right we can also do it for the current value itself 2 - 2 for the current value itself 2 - 2 for the current value itself 2 - 2 for example but this is anyways it's going to be zero so we don't have to do that so we can just avoid this one so this particular method will be order of n squ when we try to do it for each and every element in two Loops but we have another way for doing this one which is order of enter so now we will see how we going to do this so initially we are going to have these four right so here we have the length of the array that is three and then we have the total sum of the array so if we sum them we are going to get 10 here then we have preum which will be zero then we are going to have the result list which is initialized as zero at the start so this is done based on the length of the array we have three values so three zeros here so first we are going to consider two and we going to update the total by subtracting this two right so total is going to become eight now so what we are going to do here is that we going to Cal the sum of absolute differences on the left side of two and we going to calculate the sum of absolute differences in to the right side of two in order to calculate the left side we have to multiply the current value two with its index so its index is zero then we need to reduce the prefix sum right prefix sum is zero here so it is going to be zer 0 so we can see that here on the left side we don't have any values so it's going to be zero now we need to try to find the right side of two so here we are going to get a value since we have 3 and five to the right of two so first we need to calculate the length of the array that is 3 which is nothing but n minus the current index that is 0o the current values index is zero right and we need to R by one so here we are going to get two right so here we going to get two now we need to multiply this two with the current value is two right the current value is two so here we going to get four then we need to subtract this four from the total sum so here we are going to get four again so total is 8 and here we going to get four so this calculation we saw at the start right so if you try to do the sum of absolute differences between 2 3 and 2 5 we are going to get 4 so 2 - 3 + 2 - 5 so here we going to 4 so 2 - 3 + 2 - 5 so here we going to 4 so 2 - 3 + 2 - 5 so here we going to get 1 here we are going to get three by adding these two we are going to get four so it's working so then we need to add this left and right we are going to get four since 0 + 4 is going to be 4 we get four since 0 + 4 is going to be 4 we get four since 0 + 4 is going to be 4 we need to replace this 4 in the E index of result list right so here we are going to replace with four then we need to update the prefix sum by adding the current value right so now we need to take the next value that is three right so we need to update the total by subtracting three from the total itself right so total becomes 5 now so now we need to calculate the sum of absolute differences to the left side of three and sum of absolute differences to the right side of three so in the left side we have 3 and two so here we are going to get one so we will check so for that we first take the current index value that is one so three's index is one then we need to multiply with three itself with its value then we need to subtract the prefix sum that is two prefix sum is two so here we are going to get one right so both are same so then we need to find the right side of three that is 3 - 5 that is only side of three that is 3 - 5 that is only side of three that is 3 - 5 that is only one value right 3 - 5 so we have to get one value right 3 - 5 so we have to get one value right 3 - 5 so we have to get two so let's check so first we need to take the length of the array that is three the total length is three that is n right 3 and we need to subtract by one then we need to subtract by the current index one itself right the current index value is one as well so here we are going to get one then we need to multiply with the current value that is three so we have three then we need to subtract this three from the total sum so total - 3 so total is 5 - 3 is going so total - 3 so total is 5 - 3 is going so total - 3 so total is 5 - 3 is going to be 2 right we need to add two and one and we need to update in the current index value in the result list so by adding one and two we going to get three we are going to replace three here in the current index value then we need to update the prefix sum by adding the current value to the prefix sum so current value is three previously it was 2 in the perect sum so we are going to get five so then we need to pick the next value which is five so we need to update the total by subtracting by five within itself so now we need to calculate the sum of absolute differences on the left side of five so 5 - 2 is going to be 5 - 2 is going to be 5 - 2 is going to be 3 right then we need to add 5 - 3 right then we need to add 5 - 3 right then we need to add 5 - 3 which is going to be 2 so here we are going to get five so let's check so first we need to take the current index value which is two so the current values index is 2 right then we need to multiply with the current value so here we are going to get 10 and we need to subtract it by prefix sum so here we are going to get five and we don't have to calculate the right side since there is no value here so we can just avoid that so obviously VI L this side will be zero so by adding these two we are going to get five we need to replace this five in the current index in the result list so here we are going to put five and we need to update the prefix sum by adding five to the prefix sum right we are going to get 10 so now we have done with all the values in the original array so we can just return the result right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like and sub subscribe this will motivate me to upload more videos in future also check out my previous videos and keep supporting guys so initially we are going to have the total length of the array then we are going to have the total sum then we are going to have the preum set to zero then we are going to create the result list of zeros at the start based on the length of the array right so here we are going to iterate through the array so first we need to update the total sum by subtracting the current value from the total sum then we need to calculate the sum of absolute differences in the left and right side then we need to update the preum by adding the current value to it and then we need to sum the calculator left and right so then we need to update that value current index in the result list right then finally we need to return the result that's all the coders now we will run the code as you guys see it's pretty much efficient so time complexity will be order of N and space will be order of and as well thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos keep supporting happy learning cheers guys
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
1,773 |
Soon God talks Latwal Number Se Zuki Hai Tata Matching Broad Festival Subscribe Color Name Dispenser Tape Alert Mother Item subscribe The Channel If you wash then I am explaining to you by giving an example Example I am like we have given an accused and a rule and item Like covered item and this second item now I have this item association blue picture okay now this description is this way like that item so this is the first of this item first subscribe that item this white color subscribe Ghrit and do subscribe Barun that one of the China is different that I will code in the war is ok so here like more return on the number text message through loot that if type will be volume type color will be ok like explain here I try to say like the rule is this is my color and volume is a color then look in the keys it is the color of the volume and the rule is yellow color solution ok then the rule is that this is my color and volume is a color so now I will check it according to the color so that If I go to this first item, then the item color is this type, second subscribe and then the second item, quoted item, second item, quoted in intex, subscribe, take, example, what is mine, bullet of rule in example2, you, what is the type of rule in me? Now school or hatred type is away and this is our ghagra then the second computer is okay with the computer here it is the second subscribe my computer is ghrit that disinvestment second item's was brot this item is the phone and this pulse is the first The phone is your match so I will be the last one so okay so let me check it so the first thing I do is take the index of intex request 2018 now what do I do now the first thing I will check is the rule key that has been given to me So this is the rule according to which it works that what I want is that type hr more item is fine than type so I see here if the rule is that a ke roe ke date one more is fine 2030 beautiful color then I tight So if there is more interest type of color then what will happen that if I fix that it is Bigg Boss then now I will check that name if the name of the roles is my name then what will I do index to induct request to check so if the rule Here it is not changed in place of color, then I am checking the name of each item, it is not mine, Neem is always my interest in the store, okay, three text messages will come, now from here I have indexed like this. Like they gave me a rule and from there I switched to the contact side, what do I do after contact, first give a hands-free call to the medical college mark, a hands-free call to the medical college mark, a hands-free call to the medical college mark, how much is this item, I follow the rule, okay, now I will go, so that I get a list of one. List of minister in these given items so now I do this list Matargashti ok so string with lenses ok and this is one item in me I take Hey I refer your item statement ok now after traveling what do I What do I do here, I will check only the item that is the tooth gate and here I will index okay dot alas a rule value on that Rohit black coat first here gave me carat okay volume with this if my match eats what do I will take plus less, now how is it happening, let me try to explain to you, so I traveled in the list, then the first item will be picked up, then the second item will be picked up, the first item picked up is the first item, like massage, this is the first item, okay. I have given the first item a 28 gate index, so as if I have a rule that if I give a color here, then the rule will go first, fix the carica cost, keep it intact, God, then on the pretext of going to the intex phone and checking each item, I will give one item to the intex phone. If the color is represented in then the first item is this went to the look. This item is the item number in the people and this item is the first. If I pick a tomato, then the first item is mine. I picked this. Okay, now what should I do? This is the first item of item dot get index. So the item to take. Off interest is getting one, okay so the item will dance, so this is the first item that is picked up, when the gate God will do it, what is it in English, this Schezwan internet, add color to it, so why is the color there, its blue and I rule it It is said only here jet equals bluetooth silver so this in item song silver 2804 so finally subscribe that I click here I do office field and see coach that team reporter is happening we are I submit I your Successful time is done, money was time, my second chapter on Dhanteras, according to the cent of the verb, money, thanks for watching.
|
Count Items Matching a Rule
|
percentage-of-users-attended-a-contest
|
You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` and `ruleValue == typei`.
* `ruleKey == "color "` and `ruleValue == colori`.
* `ruleKey == "name "` and `ruleValue == namei`.
Return _the number of items that match the given rule_.
**Example 1:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "color ", ruleValue = "silver "
**Output:** 1
**Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\].
**Example 2:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "type ", ruleValue = "phone "
**Output:** 2
**Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match.
**Constraints:**
* `1 <= items.length <= 104`
* `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10`
* `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`.
* All strings consist only of lowercase letters.
| null |
Database
|
Easy
|
1338
|
141 |
200 Hi Guys Today Evening At Least Cycle This Printed Or Cycle In The List Sunth And Cycle Defined You Are Inquiry Into Your Native Can Never Getting Out Of The Earliest You Can See That Year 320 Maang - Poems From Her Against You Can See That Year 320 Maang - Poems From Her Against You Can See That Year 320 Maang - Poems From Her Against 2050 Dekh Le Means Urinal Loop You Are You And You Have To Give Video Kamal Tire For Middle East Subscribe So That Coriander Leaves And Avoid Subscribe Thank You Can Just Like This Is The Subscribe Lu List The Indian Media World And Avid Readers For Marital Tuesday Leak List But Its two and car book regional road platelets hundred percent place sense don't ghee means a lips this note loop dry and width him like this point subscribe and subscribe the Video then subscribe to subscribe this Video yo honey add this point to cancer potato cases appointed s What A Book Titled It Must Be Devoted And It's A Point Where Serial That Will Give Center Important Acidity When Bigg Boss Tempo Element Have Different Species In Car One Is Much Faster Bank And Two That Was Converted Into Carto Greece's Team The Best Hotspot Of History Very He Interesting Show Iinf Code To Make Clear Wheat Fiber Beach Is Difficult To Not Dandruff But Simply Return Forms Means The National How Can And Literature Of Clans Judge Means That List Notes Locker Fictionous Locker And He Didn't Take Another's Certificate Per And It's Them Don't's Certificate Per And It's Them Don't's Certificate Per And It's Them Don't's setting of the second element boil quote 9 trick there wife fast car is note equals to concern that history take car tinder diameter immediately and fast channel me if this channel is totally optional Thursday subscribe button to 1000 subscribe and subscribe otherwise around normal Ka Dat Is Next Don't See It's Going To Attend Soya Is Just For Scheduled Tribe Car And Hair Oil Type Add Karungi Movies Lutiya Dubo Degi Is Look 3.10 Contact Okay Done Dubo Degi Is Look 3.10 Contact Okay Done Dubo Degi Is Look 3.10 Contact Okay Done With That And Love You Determine It's True And Subscribe To Hai Ki Tight Pass Jab Basic paste ke gift submit nau hai or golden gypsy fast and hundred percent now we are sure when Bigg Boss 50% of percent now we are sure when Bigg Boss 50% of percent now we are sure when Bigg Boss 50% of reservation memory last Video then subscribe to the Page if you liked The Video then subscribe to subscribe luta quantity style like share so this point for the video of units and thank you for watching thank you never tell me
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
1,232 |
Hello hello guys welcome back to join this video will see give in assam coordinator points want to take off the volume straight line half yadav challenge so let's look at the problems sexual subscribe points collect daily point to straight line in the subscribe and subscribe the Channel Please subscribe and subscribe the problem happened so let's not look at how to solve this problem not fair given two point to 1 MB no difference between two points on Twitter subscribe - subscribe Twitter subscribe - subscribe Twitter subscribe - subscribe this Video then subscribe to the Page if you liked The Video then subscribe your two points on letters between health points so what will you to will just fine president use this point will start getting some point will calculate the best subscribe The Channel Please subscribe and subscribe the - and when skin problem Problem the - and when skin problem Problem the - and when skin problem Problem Change Ars History for Minute This Formula Should n't Have to Care About Division Pure Formal Letter This Thank You Can You Right You Can Right Way To - Top Tight Right You Can Right Way To - Top Tight Right You Can Right Way To - Top Tight Backstreet Boys 60 Miles 283 - * Backstreet Boys 60 Miles 283 - * Backstreet Boys 60 Miles 283 - * Multiple - subscribe The Channel Please subscribe and subscribe the Difference and Way Calculate the Current Difference Operating From This Thank You Will Find the Current Difference and Way Calculate Every Time You Later This Point You Can Just Apply This Difference Years Differences with Rs Current Difference and Current Tax Differences with a Difference using this formula and you can easily find out we are having SIM slot not very far better than the rate division method of this time will be the solution how can we go this is the difference between the different points which Will Start From This Point To Will Calculate The Con Is On Please Click on the link for detail view Exactly Anil San Play Return Forms Otherwise After Reading For Each And Every Point E Do Not Find Any Point Having Different People Dhan Finally E Will Return True Saying that all the points of lying in a single straight line so you are able to understand solution study approach and solution in different languages and approach and solution in different languages and approach and solution in different languages and subscribe Benefit from like share and subscribe
|
Check If It Is a Straight Line
|
sum-of-mutated-array-closest-to-target
|
You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point.
|
If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value.
|
Array,Binary Search,Sorting
|
Medium
| null |
1,846 |
hello guys today Cod problem so uh this problem is very uh simple problem so let's code together uh basically in this problem we have given the topics like uh counting and shorting and Grading so let's start the code of this problem initially but we have to do that uh int answer equals to array of okay and short okay short array do begin dot end okay then in I = 1 I less than R do size I ++ and ++ and ++ and if array of IUS one minus AR of I than absolute value of I ials of IUS 1 and equals to maximum of array I in and answer okay and okay uh the first element of array must be one and the absolute difference between any two adjacent elements must be less than or equals to one okay so accepted thank you for your patience
|
Maximum Element After Decreasing and Rearranging
|
maximum-element-after-decreasing-and-rearranging
|
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109`
| null | null |
Medium
| null |
393 |
hey everybody this is larry this is day 13 of the leco daily challenge hit the like button hit the subscribe button join me on discord whoops one bun let me know what you think about today's prom uh no extra coins today's prime is utf-8 utf-8 utf-8 validation okay let's see i think i've done this recently because it was one of the uh i could be wrong but i think this is one of the brine or grind 75 or 50 or whatever it is um and i think i've done this recently like a month ago ah actually less than oh no it was about a month ago but seems like i have a lot of city mistakes so maybe hopefully this time i will have fewer silly mistakes uh let's see wow two thousand uh the ratio is not very good okay so what which one is this one again i feel like i've done it so well i mean i and apparently i have but uh okay so it just seems like there are some rules and we just have to fit it i say this now knowing that i feel got wrong answer four times is a little bit interesting but okay uh okay i need the least significant eight bits of the chin that just used to store the data okay fine uh okay yeah so it's only between 255 okay so okay fine so n is equal to the length of data oops so i think this is just try to follow the rule as best as you can i don't know that there's anything well they're allowed other than or i don't know that there's any algorithm that's tricky about it's just about being careful of edge cases which i quit it was not but during the blind 75 i was just speed racing right so i don't know that would yeah i don't depend how you want to say it i don't know if it counts but okay so okay uh the first bit is okay so for one by characters maybe i'll just go um i is zero something like this so we could do it maybe multiple one as a time a one by characters then okay if that is up i do uh seven is greater than zero so if this oh wait no this is this would be if this was okay so it's a one byte character what does it say oh we don't return whether it is about it okay one by character then can we increment we continue right otherwise then the first n bits are all ones for an n byte character the first n bits are all ones n plus one by bit is zero four by n minus one by two the most significant two bits being ten did i misunderstood this oh and the bytes are 10 okay so that means that otherwise we have to count the number of bytes oh and then yeah while that is a five we end it with something like that maybe wow this is greater than zero we increment and this can only go up to four well okay so i guess we have to do maybe an n check i don't know if this is um uh less than five i guess just to be sure and then if b is greater so we do zero one two zero okay so we have this is greater than four we return false okay uh otherwise we have b bits and then we check that the next n minus one okay so then that means that for uh let's say j in range of b uh well we checked that uh okay if i plus j is you know our bounds then we return force otherwise if theta sub i plus j uh this has to start at one because we already know that i doesn't have it so uh if this and this is awkward something like that if this is you go to 10 or if it's not equal to 10 meaning uh if it's not equal to then we turn force otherwise we can continue okay and then here we i increment by b okay and then we turn true otherwise this is good i don't know this time i'm much slower than last time i did it i assume because i feel very slow today okay let's try this real quick there's a lot of possible wrong enders where at least i got this part correct uh let's give it some it mostly because i'm lazy it's still 7 a.m here in dublin so yeah it's still 7 a.m here in dublin so yeah it's still 7 a.m here in dublin so yeah 145 huh i don't know why this is wrong so um uh okay maybe i should be a little bit less lazy though but okay let's print out the bin of x for x and data so that we can kind of visualize this in a you know binary kind of way um that's how i use it well why is this giving me this oh i guess i'm just converted to a nest a little bit rusty in the morning still got a lot well okay so this one it goes one zero okay huh so thinks there's one bite does it have to be one byte well what do i return true expect to enter is false i say the next cereal byte is good right oh it has to be or doesn't really say whether why is this force again because it just say that this one and then the next n minus one pi i actually don't know like i might i can definitely you know special case this but i just don't see how you could read that from the input from the sample like if like i don't i can't tell whether this end can be won or whether the rest has to be zero right like i it doesn't say that it has to the first one bit is well once next one is zero and then it doesn't say anything about the other bits right so i don't know which part of this i have to validate i think that's the uh thing okay maybe just try if b is equal to one or this i really don't know they don't really i can read this from here i could be wrong right uh because it's just unclear maybe i made the same thing last time oh that really well i mean i'm happier that i cut it early but it's just unclear that i mean it anyway okay so 896 day streak yay consistency is key it's not quite the end this end cannot be one right like if they just add that maybe that's fine but like because i hear i have to do some guesswork i show him i guess that's one way to do it i didn't do it that way though but um i'm just curious what i did last time now this is my code from last time i guess it's very similar actually i have a help count prefix thing but one time ever and then i have oh did i this is the same name i got the wrong same wrong enough uh answer at least that's consistent uh and then i added what did i add hmm i think i fixed this in other way last time i don't know what i did to well okay let's see some print statement oh i did if offset is equal to one this is false and i still got another one answer yeah i guess i was a little bit more sloppy last time i don't know or maybe that i chose the n is greater than four maybe i'm just trying like what is this fix then oh this fix was me returned through was inside and i take it outside that's actually a very silly mistake okay well but i would i was speed running this last time so and then here i oh yeah and then here i do an offset is greater than five so i guess this time i was a little bit better about it but to be honest well the two things really um one this is the specs can be a little bit better uh but otherwise i think i did a pretty okay on this one i just wasn't sure if you know n is equal to one we can still do this you can like that's literally if you they add like five words we would have done it first try the second thing is that yeah okay a lot of people hate this but this is probably as work relevant as uh as you can get as on a clinical interview question right um and then maybe part of that is asking for more specs if you get this on an interview because and that also the most we uh most assembles uh a work interview or a work situation uh so people always complain about how you know interview doesn't it's not similar to what you do at work and then when it does people complain about how they're doing work for free so i don't know so make up your mind not i mean you know i'm just ranting in general i mean if that's not you feel free to ignore but no um but so i do feel this is kind of in that sense related to um relating to you know you the most resemble your actual work um so in that sense it's fine uh i don't know don't really have much more to say to this one though this is uh linear time oh i forgot to take out the print statement actually oops but um linear time and yeah uh constant space seems like right uh if you don't count the random print statement that i had by accident uh yeah uh that's pretty much all i have though so let me know what you think stay good stay healthy to get mental health i'll see you later and take care of that stuff bye
|
UTF-8 Validation
|
utf-8-validation
|
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:
1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code.
2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`.
This is how the UTF-8 encoding would work:
Number of Bytes | UTF-8 Octet Sequence
| (binary)
--------------------+-----------------------------------------
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
`x` denotes a bit in the binary form of a byte that may be either `0` or `1`.
**Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data.
**Example 1:**
**Input:** data = \[197,130,1\]
**Output:** true
**Explanation:** data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
**Example 2:**
**Input:** data = \[235,140,4\]
**Output:** false
**Explanation:** data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
**Constraints:**
* `1 <= data.length <= 2 * 104`
* `0 <= data[i] <= 255`
|
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character.
Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem.
mask = 1 << 7
while mask & num:
n_bytes += 1
mask = mask >> 1
Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks.
mask1 = 1 << 7
mask2 = 1 << 6
if not (num & mask1 and not (num & mask2)):
return False
|
Array,Bit Manipulation
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.